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:
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? :
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!