Advertisement

Help with static class members

Started by February 10, 2003 02:43 PM
4 comments, last by SpaceRogue 21 years, 9 months ago
I''m trying to make a simple class that contains a static int that counts the instances of the class. When I add a line to my class constructor that increments the count I get linker errors. What''s wrong?
Oh, here''s the error:


error LNK2001: unresolved external symbol "public: static int Object::Count" (?Count@Object@@2HA)
Advertisement
No idea what''s wrong, try posting some code.

Sand Hawk

----------------

(Inspired by Pouya)
----------------(Inspired by Pouya)
You need to define the variable somewhere, ie:
// header fileclass something{    static int count;} // implementation fileint something::count = 0;
I guess that''s your error.

I had that same problem. You must give your static variable a value in a cpp file if you want to use it:

In the .h file
class Test
{
public:
Test();
~Test();
static int var;
};

Then in the .cpp file

int Test::var=0;

Test::TesT()
{
var++;
}
This will work.

Good Luck!

www.nzcal.com/hp/realmgames
-------------------Realm Games Company
Sorry I didn''t post my code...I wasn''t thinking.

Greatone, that was the problem. I had declared the variable in the class header, but hadn''t initialized it. To my credit I did try once, but I had left the type (int) off of the initialization and it failed to compile as well. When it failed, I removed the line and looked elsewhere for the problem, not realizing how close I was to fixing it.

Thanks.

This topic is closed to new replies.

Advertisement