Reputation: 417
Whenever we have a class with some static member variable, why do we need to define it?
Why can't we use it directly?
I wanted to see if any memory space would be allocated to the static variable if I don't define it, so I wrote this little code and it seems like memory is indeed allocated for the variable.
#include <iostream>
using namespace std;
class A
{
public:
int a;
static int b;
};
// int A::b = 1;
int main()
{
cout<<sizeof(A::b);
return 0;
}
Output:
4
Now, I defined the variable and initialized it (uncommented the int A::b = 1; line) and ran the same code, even this time the output was the same.
So, what is the purpose behind defining it?
Upvotes: 2
Views: 150
Reputation: 1409
For static data member you have to allocate memory for it in your implementation, what you are doing now does not allocate memory but you are just getting the size of the int
.
In C++ 17 you can declare static variable inline, for int
its default value is zero but you can set any value you want. Like this:
static inline int b=4;
Upvotes: 1
Reputation: 172894
The definition is required if the variable is odr-used, while sizeof(A::b)
doesn't.
One and only one definition of every non-inline function or variable that is odr-used (see below) is required to appear in the entire program (including any standard and user-defined libraries). The compiler is not required to diagnose this violation, but the behavior of the program that violates it is undefined.
For example, if you take address of the variable, then it's odr-used and it must be defined.
cout << &A::b;
Upvotes: 2