Separate declaration and definition of static member functions

Hi All:

I'm trying to declare my class in a header file.
1
2
3
4
5
6
class MyClass
{
   static int i;
public:
   static void setInt(int k);
};


Then I do the following definition of setInt in a separate cpp file.
1
2
3
4
void MyClass::setInt(int k)
{
   i = k;
};


I've also made sure that I have included the header file in the function definition cpp file.

But I am getting link error, saying can't find object or something alike. I looked it up, and found "static" has internal linkage.

So my question is, how do I work around this? I don't want to define my static function in header file.

Thanks
Last edited on
About compile errors http://www.cplusplus.com/forum/articles/40071/#msg216270

You need to define the static members.
In my_class.cpp int MyClass::i; //initial value if you want
Thanks for the reply!

Sorry that I didn't provide the link error:
my_class.obj : error LNK2001: unresolved external symbol "private: static int Base::i"

Obviously, in my_class.cpp, the instruction "i=k" can't access the static data member i of MyClass.


You need to define the static members.
In my_class.cpp int MyClass::i; //initial value if you want

Yeah, your solution works.
One further question about your solution: if the int MyClass::i; is the definition of my static member, does that mean static int i; in my_class.h is only a declaration? Then I'm a bit confused: a variable in C++ needs only declaration, doesn't it? Why do we need definition of a data member?

Thanks.
One more thing to double-check:

If I have a few more classes derived from MyClass, they will all have int i because they are derived from MyClass; However, since int i is static in the base class MyClass, all the derived classes will hence share the same int i, won't they?
Last edited on
In your .h you only tell how is the class. You don't construct anything there.

Yes, I think that all the derived will share it. That was an issue here http://www.cplusplus.com/forum/general/27880/
Beeeaaaauuuutiful!
Thanks for the link, dude.
Topic archived. No new replies allowed.