Can some one explain me how inheritance is implemented in C++ ?
Does the base class gets actually copied to that location or just refers to that location ?
What happens if a function in base class is overridden in derived class ? Does it replace it with the new function or copies it in other location in derived class memory ?
first of all you need to understand that C++ is quite different to e.g. Java, because there is no notion of a “Class” retained at runtime. All OO-features are compiled down to things which could also be achieved by plain C or assembler.
Having said this, what acutally happens is that the compiler generates kind-of a
struct, whenever you use your class definition. And when you invoke a “method” on your object, actually the compiler just encodes a call to a function which resides somewhere in the generated executable.Now, if your class inherits from another class, the compiler somehow includes the fields of the baseclass in the struct he uses for the derived class. E.g. it could place these fields at the front and place the fields corresponding to the derived class after that. Please note: you must not make any assumptions regarding the concrete memory layout the C++ compiler uses. If you do so, you’re basically on your own and loose any portability.
How is the inheritance implemented? well, it depends!
This distinction is very important in practice. Note, it is not true that inheritance is allways implemented through a vtable in C++ (this is a common gotcha). Only if you mark a certain member function as
virtual(or have done so for the same member function in a baseclass), then you’ll get a call which is directed at runtime to the right function. Because of this, avirtualfunction call is much slower than a non-virtual call (might be several hundered times)