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 ... !?

2
  • 1
    What is the error you get? Can you please be more specific? In C++ you're allowed to have static objects as part of your class. Commented Jan 13, 2014 at 5:49
  • @legends2k: sorry, fixed it. Commented Jan 13, 2014 at 6:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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: 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, 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.
@sree: Perhaps it would make more sense to just put them into a namespace?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.