0

Lets examine following case

struct A{ virtual ~A(){} }; struct B : public A{ virtual ~B(){} }; struct C : public B{ virtual ~C(){} }; int main(){ A* a = new C(); B* b = dynamic_cast<B*>(a); } 

How does dynamic_cast know that B is a super class of C at the runtime. I understand that dynamic_cast accesses type_info of *a and finds that *a is actually of type C by examining name property. But how not having all the information that compilator has about classes inheritance does dynamic_cast know that B is a superclass of C having only information that the type of *a is C? Does that make any sense?

2
  • 4
    What makes you think that the RTTI doesn't have all the type hierarchy information? Commented Nov 21, 2020 at 18:23
  • 3
    See How does dynamic_cast work?. Commented Nov 21, 2020 at 18:24

1 Answer 1

2

The premise is wrong: dynamic_cast does indeed have all the information it needs. The compiler encodes the type information in read-only type information records that are a part of the binary while it executes. The vtable pointer embedded in each polymorphic object allows dynamic_cast to find this “baked in” type information, since the virtual method table contains more information than just method pointers. That’s the common way it’s implemented, and also a matter of a fixed ABI on x86-64, ie all compilers for that architecture encode this information the same iirc.

Sign up to request clarification or add additional context in comments.

1 Comment

But vtable holds only type_info object which doesn't have anything but exact type in it. Or is it a key to some entry in class map that holds list of whole hierarchy that is not accessible for casual user?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.