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?

3
  • 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. Commented Jul 25, 2012 at 6:32
  • The first one is explained well here. Commented Jul 25, 2012 at 6:33
  • possible duplicate of How to initialize a static member in C++? Commented Jul 25, 2012 at 7:32

1 Answer 1

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; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.