1

Referring to the following:

class A { ... };

class B 
{
    static A a; // this fails
    ...
    static A& getA() { static A a; return a; } // this works
    ...
};
...
B b;
b.a  <-- gives error: undefined reference to B::a

Why can I not have a static A in class B, but it is fine to return it from a method?

[edit]
Just something curious:

struct C
{
    static const int x = 5;
};

int main()
{
    int k = +C::x;
    std::cout << "k = " << k << "\n";
    return 0;
}

output: k = 5

C::x is not defined in implementation-scope, neither is there an instance of C, and yet, with the unary + C::x is accessible ... !?

slashmais
  • 7,069
  • 9
  • 54
  • 80

1 Answers1

3

You most certainly can have exactly that.

What you've probably forgotten to do is define the object (exactly once) outside the class:

class B { 
    // ...
};

A B::a;

Edit: based on edit to question, this is now basically a certainty instead of just a probability.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • I get the same even for `static int n` in class B; what is it about `static` that requires that it must be defined outside the class? – slashmais Jan 13 '14 at 05:58
  • @slashmais: It's just how C++ requires that you do things. There is some sense to it (that data item needs to be defined even if no instance of the class is ever created), but for most practical purposes, it's just something you have to do, and such is life (or such is C++, anyway). – Jerry Coffin Jan 13 '14 at 06:02
  • @Jerry Coffin, Is there anything wrong if I have so many public static class member variables in c++ (non multi-threaded Linux program environment). I have moved some of my global variables to a class as public static. – uss May 26 '15 at 15:08
  • @sree: Perhaps it would make more sense to just put them into a namespace? – Jerry Coffin May 26 '15 at 16:01