I’ve always wondered, when you cast an object pointer to its base class, what exactly happens to the memory? I presume that the memory storing all the member functions and variables in the sub class are still there, just ‘off-limits’ now. Is this right? If so, how do abstract/virtual functions work? How come the sub class implementation can be called from a base class pointer in this case?
Also, does it vary depending on the language? Obviously C++ uses the stack and the heap, whereas Java would only use the heap.. Does this mean the memory for the polymorphic relationship is handled differently?
And how do things like private, protected and even virtual inheritance work in relation to this?
What you are asking is implementation detail.
Broadly speaking the usual approach is to store a pointer to a table of function pointers as part of the object (the functions are not part of the actual object’s memory footprint) and depending on the concrete object this table (vtable in C++, some similar construct in
JavaI imagine) points to the actual runtime object’s methods and as a result the fact that you are using a pointer to the base class does not affect you from actually calling a method overriden by the derived classThis is not related to your question. Modifiers (public/private/protected) are a static time construct. I.e. the compiler enforces usage according to the modifiers. The underlying memory is unrelated here.