Suppose I have
class A { public: void print(){cout<<"A"; }};
class B: public A { public: void print(){cout<<"B"; }};
class C: public A { };
How is inheritance implemented at the memory level?
Does C copy print() code to itself or does it have a pointer to the it that points somewhere in A part of the code?
How does the same thing happen when we override the previous definition, for example in B (at the memory level)?
Compilers are allowed to implement this however they choose. But they generally follow CFront’s old implementation.
For classes/objects without inheritance
Consider:
The compiler changes those last three lines into something similar to:
Once upon a time I would have guessed that this was handled with pointers-to-functions in each
Aobject created. However, that approach would mean that everyAobject would contain identical information (pointer to the same function) which would waste a lot of space. It’s easy enough for the compiler to take care of these details.For classes/objects with non-virtual inheritance
Of course, that wasn’t really what you asked. But we can extend this to inheritance, and it’s what you’d expect:
The compiler turns the last four lines into something like:
Notes on virtual methods
Things get a little trickier when you talk about
virtualmethods. In that case, each class gets a class-specific array of pointers-to-functions, one such pointer for eachvirtualfunction. This array is called the vtable (“virtual table”), and each object created has a pointer to the relevant vtable. Calls tovirtualfunctions are resolved by looking up the correct function to call in the vtable.