How does RTTI work?
Asked Answered
K

1

9

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?

Krakow answered 17/7, 2014 at 14:13 Comment(4)
"I thought that the pointers only give information about the virtual functions" - why did you think that? The vptr points to all the dynamic type information - the vtable, and whatever is needed by RTTI.Cristoforo
@MikeSeymour besides the vtable, what else is pointed at?Krakow
Whatever implementation-specific metadata is needed to support RTTI. I'm afraid I don't know how it's generally implemented, but I'm sure Google could tell you if you're interested.Cristoforo
This may or may not be helpful.Transmundane
S
3

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

Stipulation answered 17/7, 2014 at 15:25 Comment(3)
I assume there is an implied line that says something like: void *b = (void *)new B() in there. If so, wouldn't it be possible that b is some totally unrelated thing, like an array of bytes, that happens to have a 0x0f43 at the right offset?Discernible
If b is an array of bytes, the dynamic_cast won't even compile because b is not of type B.Shanel
@Moby Dick. No it does not compile (or should not). See https://mcmap.net/q/830260/-dynamic_cast-from-quot-void-quotShanel

© 2022 - 2024 — McMap. All rights reserved.