user1079475
user1079475

Reputation: 420

How does dynamic casting works when you don't cast to the most derived

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?

Upvotes: 0

Views: 88

Answers (1)

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.

Upvotes: 2

Related Questions