I am trying to make sense of the statement in book effective c++. Following is the inheritance diagram for multiple inheritance.
I could not see any reason why there is requirement of separate memory in each class for vptr
At runtime, when you invoke a (virtual) method via a pointer, the CPU has no knowledge about the actual object on which the method is dispatched. If you have B* b = ...; b->some_method();
then the variable b can potentially point at an object created via new B()
or via new D()
or
even new E()
where E
is some other class that inherits from (either) B
or D
. Each of these classes can supply its own implementation (override) for some_method()
. Thus, the call b->some_method()
should dispatch the implementation from either B
, D
or E
depending on the object on which b is pointing.
The vptr of an object allows the CPU to find the address of the implementation of some_method that is in effect for that object. Each class defines it own vtbl (containing addresses of all virtual methods) and each object of the class starts with a vptr that points at that vtbl.