9

I'm trying to declare a static object of a class A that I wrote in a different class B, like this:

class A // just an example { int x; public: A(){ x = 4; } int getX() { return x; } }; class B { static A obj1; // <- Problem happens here public: static void start(); }; int main() { B::start(); } void B::start() { int x = obj1.getX(); } 

What I want to achieve is to get int x in B::start() to equal int x in class A (4).

I tried googling all this for the past hour and all I understood was that C++ doesn't allow static objects' declarations. Is that correct?

If so, here's my question. How can I get the same result? What are my available workarounds? Keeping in mind that the rest of my code depends on the functions in class B to be static.

Error

error LNK2001: unresolved external symbol "private: static class A B::obj1"

Thanks!

5
  • 2
    You are missing an object definition. Add it outside the class: A B::obj1; Commented Apr 10, 2015 at 1:52
  • You should include the error messages that you get. Commented Apr 10, 2015 at 1:55
  • stackoverflow.com/a/12574407/962089 Commented Apr 10, 2015 at 1:55
  • @dasblinkenlight Thanks! I read that somewhere actually but I didn't get it. Could you please emphasize on what the object definition is? Why can't I just declare it normally? Commented Apr 10, 2015 at 2:10
  • 1
    @user3551916 objects must have a definition. Sometimes a declaration also serves as a definition but usually it doesn't. In this case it doesn't. Commented Apr 10, 2015 at 2:16

2 Answers 2

7

You should initialize static var, the code:

class A // just an example { int x; public: A(){ x = 4; } int getX() { return x; } }; class B { static A obj1; // <- Problem happens here public: static void start(); }; A B::obj1; // init static var int main() { B::start(); } void B::start() { int x = obj1.getX(); } 
Sign up to request clarification or add additional context in comments.

Comments

7

As thinkerou said, you need to include the declaration of the variable:

A B::obj1; 

For normal, non-static member variables you don't need this step because the variables are declared behind the scenes as part of the constructor. These variables are then tied to the instance of the class you just constructed. But static variables are not tied to any instance of a class; they are shared by all instances of a class. So constructors can't properly deal with them.

C++ gets around this by making you manually declare (and optionally initialize) any static member variables. Depending on where they are declared, they typically get constructed before your main() function starts, so they are available for use immediately.

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.