0

Here is the code,

class A {
public:
    static A *get_a()
    {
        if(_pa == 0)
            _pa = new A;
        return _pa;
    }

private:
    static A *_pa = 0;  //cannot compile
};

In the above code, if I move _pa's definition outof the class,

A * A::_pa = 0;  //can compile

My problem is, static A *_pa = 0 inside the class body is just a declaration, not a definition, right?

Moreover, is it valid to assign a value to a static data member inside the class?

Alcott
  • 17,905
  • 32
  • 116
  • 173
  • 1) Correct, it doesn't even work in C++11, as all that does is sub it in where it would normally be default-initialized (i.e., when an object is created). 2) Yes, static variables can be accessed through the class itself, or objects. – chris Jul 25 '12 at 06:32
  • The first one is explained well [here](http://stackoverflow.com/questions/185844/initializing-private-static-members). – chris Jul 25 '12 at 06:33
  • possible duplicate of [How to initialize a static member in C++?](http://stackoverflow.com/questions/3531060/how-to-initialize-a-static-member-in-c) – RedX Jul 25 '12 at 07:32

1 Answers1

3

Unless it's a const integral type (char, short, int, ...) you have to define the static member in a .cpp-File in addition to the declaration in the header.

header:
class XYZ {
  static XYZ * instance;
};

//cpp:
XYZ * XYZ::instance;
MFH
  • 1,664
  • 3
  • 18
  • 38