Search code examples
c++multiple-inheritancedynamic-castdowncastvirtual-inheritance

Virtual multiple inheritance and casting


I tried creating a class that inherits from multiple classes as followed, getting a "diamond"
(D inherits from B and C. B and C both inherits from A virtually):

  A
  / \
B   C
  \ /
  D

Now, I have a container with a linked list that holds pointers to the base class (A).
When I tried doing explicit casting to a pointer (after typeid check) I got the following error:
"cannot convert a pointer to base class "A" to pointer to derived class "D" -- base class is virtual"

But when I use dynamic casting it seems to work just fine.
Can anyone please explain to me why I have to use dynamic casting and why does the virtual inheritance causes this error?


Solution

  • "Virtual" always means "determined at runtime". A virtual function is located at runtime, and a virtual base is also located at runtime. The whole point of virtuality is that the actual target in question is not knowable statically.

    Therefore, it is impossible to determine the most-derived object of which you are given a virtual base at compile time, since the relationship between the base and the most-derived object is not fixed. You have to wait until you know what the actual object is before you can decide where it is in relation to the base. That's what the dynamic cast is doing.