Search code examples
c++staticprivate

How I can access a private static member variable via the class constructor?


How can I use and modify the s_member private static variable from the constructor or in general from an other member function?

This is what I tried.

a.h:

#ifndef A_H
#define A_H

#include <set>

class A
{
    public:
        A();
        virtual ~A();

    private:
        static std::set<int> s_member;
};

#endif

a.cpp:

#include "a.h"

A::A()
{
    A::s_member.insert(5); // It causes error.
}

I get this error:

/tmp/ccBmNUGs.o: In function `A::A()': a.cpp:(.text+0x15): undefined
 reference to `A::s_member' collect2: error: ld returned 1 exit status

Solution

  • You have declared A::s_member but not defined it yet. To define it, put below code, outside of class:

    std::set<int> A::s_member;
    

    For example:

    std::set<int> A::s_member;
    
    A::A()
    {
      // ...
    }
    

    The problem is not related to accessing and private/public.