Re: Delegation through pure virtual
aksinghdce <aksinghdce@gmail.com> wrote:
The constructor of Join set the vptr of Der1 and Der2 to point
to vtable which are valid for Der1 and Der2 which are members of
Join.
--
James Kanze
Thats a real nice explanation. I would like to learn more about this;
please do me a favor and suggest me a book and/or an article or such
so as to let me dive deeper. Thanks a ton :)
Perhaps the confusion stems from not realizing that objects
instantiated from classes with virtual functions have a vtable
pointer inside them (in practice almost always at the very beginning
of the memory block occupied by the object). This means that the
the instantiations (ie objects) of the same class can actually
point to *different* vtables. (The structure of these vtables is
obviously always the same, but their content can differ, ie. the
function pointers inside them can point to different functions.)
How virtual functions are handled (even in diamond inheritance
situations) is rather simple, relatively speaking. However, it
becomes interesting how access to base class member variables is
handled in a diamond inheritance situation with virtual inheritance.
In a non-diamond-inheritance (or a non-virtual inheritance) situation
accessing member variables of the base class is trivial, but in
a virtual diamond inheritance situation it's a bit more complicated.
Another interesting topic is how dynamic_cast works in complex
multiple inheritance situations. For example, assume this situation:
class A { public: virtual ~A(); ... };
class B { public: virtual ~B(); ... };
void foo(A* a)
{
B* b = static_cast<B*>(a); // Will not compile
B* b = dynamic_cast<B*>(b); // Will compile
}
The classes A and B are not related to each other in any way, and
hence the static_cast will obviously fail to compile because the
types are incompatible. The dynamic_cast will, however, compile.
If the object given to foo() is not related to B in any way, the
dynamic_cast will simply return a null pointer.
Can the dynamic_cast give something else than null in some
situation? The answer is yes. For example if called like this:
class C: public A, public B { ... };
C c;
foo(&c);
Now the dynamic_cast will actually detect that the object is
actually also of type B, and it will change the pointer to point
to the B part of the object.
*How* it does that is the interesting question.