Possible Duplicate:
Structure of a C++ Object in Memory Vs a Struct
memory layout c++ objects
This is probably a really dumb question, but I will ask anyway. I am curious what an object looks like in memory. Obviously it would have to have all of its member data in it. I assume that functions for an object would not be duplicated in memory (or maybe I am wrong?). It would seem wasteful to have 999 objects in memory all with the same function defined over and over. If there is only 1 function in memory for all 999 objects, then how does each function know who’s member data to modify (I specifically want to know at the low level). Is there an object pointer that gets sent to the function behind the scenes? Perhaps it is different for every compiler?
Also, how does the static keyword affect this? With static member data, I would think that all 999 objects would use the exact same memory location for their static member data. Where does this get stored? Static functions I guess would also just be one place in memory, and would not have to interact with instantiated objects, which I think I understand.
Static class members are treated almost exactly like global variables / functions. Because they are not tied to an instance, there is nothing to discuss regarding memory layout.
Class member variables are duplicated for each instance as you can imagine, as each instance can have its own unique values for every member variable.
Class member functions only exist once in a code segment in memory. At a low level, they are just like normal global functions but they receive a pointer to
this. With Visual Studio on x86, it’s viaecxregister usingthiscallcalling convention.When talking about virtual functions, polymorphism, then the memory layout gets more complicated, introducing a “vtable” which is basically a bunch of function pointers that define the topography of the class instance.