If I have a class like
class MyClass {
public:
int myMember1;
int myMember2;
int myMember3;
};
Every time I instantiate an object of MyClass
space for three consecutive int
is allocated, what about when I have something like
class MyClass {
public:
static int myMember1;
int myMember2;
int myMember3;
};
How the memory is allocated this time?
I'm asking because I'm not entirely sure how the memory would be allocated when I declare multiple instance of the same class, is there a pointer to the static member maybe?
As others already stated, you have to explicitly allocate space for the static member variable outside the class definition.
In response to your other question, static member variables are not associated with class objects. That is to say, they will continue to exist even after your MyClass object has ceased to exist (until the termination of your program), and be shared across all instances of your class.
Say you created multiple instances of the MyClass class like so:
class MyClass {
public:
static int myMember1;
int myMember2;
int myMember3;
};
int MyClass::myMember1 = 1;
int main()
{
MyClass mc1;
MyClass mc2;
mc2.myMember1 = 2;
std::cout << mc1.myMember1 << '\n';
std::cout << mc2.myMember1 << '\n';
return 0;
}
The output will be:
2
2
How the memory is allocated this time [with the static member]?
Each instance of the object will have 2 integers in, and all instances have access to the static
integer (but don't "own" it) - it is not part of the instances, it is in the scope of the class.
N.B. the member is declared in the class, but must be defined outside the class (in the cpp file), e.g.;
int MyClass::myMember1 = 42;
... is there a pointer to the static member maybe?
No. You can get a pointer the static member if you require, but one is not allocated to each instance.
The static member is allocated (and initialised as per the initialisation in the cpp file) when the application launches and can be accessed as other "global" objects are (albeit that the static is not in the global namespace, there is only one instance of it). The accessibility of the member (i.e. public
, private
vs. protected
) follows the normal rules.
To see the effect on the size, you can use sizeof()
;
class MyClass {
public:
int myMember1;
int myMember2;
int myMember3;
};
class MyClass1 {
public:
static int myMember1;
int myMember2;
int myMember3;
};
int MyClass1::myMember1 = 42;
int main(int argc, char* argv[])
{
using namespace std;
cout << sizeof(MyClass) << " " << sizeof(MyClass1) << endl;
}
The above (depending on alignment and the size of the int
), could produce an output of 12 8
.
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With