I have some confusion regarding the RTTI mechanism in C++.
Suppose in have class A and class B that inherits from A. Now consider the following code:
B* b = new B();
A* a = dynamic_cast<A*>(b);
I know that polymorphic classes with virtual methods have virtual tables and vptr's, but I thought that the pointers only give information about the virtual functions. How does the program know at runtime the type of b, using vptr's and vtables?
Imagine you have
struct B {
virtual doSth() {
cout << "hello";
}
};
struct A : public B {
doSth() {
cout << "hello world";
}
};
Now suppose A::doSth() is at 0x0f43 and B::doSth() is at 0x0a41
then dynamic_cast(b) can be implemented as (pseudo-code)
if ( (address pointed to by b::doSth()) == 0x0f43 ) {
// cast is OK
} else { // (address pointed to by b::doSth()) == 0x0a41
// not possible to cast
}
So you really just need b to hold a pointer to the right doSth() method to know its true type
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With