Reputation: 395
I have a class structure :
A <- B
where A is base class and B is the derived one. Some independent code creates object of both these classes. A has a static variable (lets say 'static_a') which is used in A as well as B.
Where should I define this static_a ? When I define that in A.h, it gives me linker error saying multiple definition. Then I moved it to A.cc file, and compilation passes. But, I am confused whether the class B (which is defined in B.h and B.cc, which doesnt see the definition in A.cc) will get the correct values defined for the variable static_a, as it is defined in A.cc ??
Thanks for the help!
Upvotes: 1
Views: 2061
Reputation: 258568
Declare your variable in the header and define it (initialize it) in the cc file. B class only need the declaration of your static. No need to worry, it will work.
A.h
class A{
public:
static int x;
};
A.cc
int A::x = 0;
B.h
class B : public A{
void foo()
{
if ( A::x == 0 )
//this is true
}
}
Upvotes: 2
Reputation: 75130
A static variable definition is a little like declaring an extern
variable or a function prototype. It lets the linker know the variable or function exists somewhere in all the compilation units, but it does not create the variable, it just says that it will exist somewhere. It doesn't make the variable exist.
When you put the definition in a header file, every file that includes that header will redeclare the variable, and that's why you get linker errors. You're creating multiple variables with the same name, so the linker has no idea which one to use.
When you put an actual definition in a cc
file, you're creating the variable there once, and every time somebody uses it anywhere else across the project, they're using that one.
So basically, you're doing everything right.
Upvotes: 4