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?

user1079475
  • 379
  • 1
  • 5
  • 17

1 Answers1

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.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
  • 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? – user1079475 Nov 24 '20 at 09:55