Given two classes each with two integer member variables but one of the classes' integers is a static variable. What is the size of each of these classes?
Well, the naive answer would be to assume that as both classes have two integers and an integer is (usually) four bytes then both classes would be 8 bytes.
This isn't true though, as a static member variable of a class is not actually stored in the class.
Here is an example of some code showing this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #include <stdio.h> #include <string.h> class NoStatic { public: NoStatic(){} int val0; int val1; }; class StaticClass { public: StaticClass(){} int val0; static int val1; }; int StaticClass::val1 = 0; int main() { int sizeNoStatic = sizeof(NoStatic); //8 bytes int sizeStatic = sizeof(StaticClass); //4 bytes return 0; } |
This is an important thing to consider when writing generic code and a good argument against just copying memory from one data structure to another without really looking at the code.
What do you think would happen in this example? :
1 2 3 4 5 6 7 | StaticClass classTestStatic; classTestStatic.val0 = 10; classTestStatic.val1 = 15; NoStatic classTest; memcpy(&classTest, &classTestStatic, 8); |
The none static version of the class would not be given the value from the static variable in the static version of the class.
If we run the code and look at the memory addresses of the StaticClass instance we see this
So, we can see that variable 'val0' is stored at the same address of the class (0x00ddfa9c), meaning it is the first variable in the class. So if this was a non-static class we would expect 'val1' to be 4 bytes after this address at 0xddfaa0 however it is at 0x00b88130 which shows us it is not stored in the class and proves to us that a static is, like people say, nothing more than a glorified global variable.
So the real question for the reader is: Why is a class with all static variables one byte in size?
Thanks for reading!