Consider this simple hierarchy:
class Base { public: virtual ~Base() { } };
class Derived : public Base { };
Trying to downcast Base* p
to Derived*
is possible using dynamic_cast<Derived*>(p)
. I used to think dynamic_cast
works by comparing the vtable pointer in p
to the one in a Derived
object.
But what if we derive another class from Derived
? We now have:
class Derived2 : public Derived { };
In this case:
Base* base = new Derived2;
Derived* derived = dynamic_cast<Derived*>(base);
We still get a successful downcast, even though the vtable pointer in Derived2
has nothing to do with a vtable pointer in Derived
.
How does it actually work? How can the dynamic_cast
know whether Derived2
was derived from Derived
(what if Derived
was declared in a different library)?
I am looking for specific details about how this actually works (preferably in GCC, but others are fine too). This question is not a duplicate of this question (which doesn't specify how it actually works).
See Question&Answers more detail:os