Dan Dv
Dan Dv

Reputation: 493

How does RTTI work?

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?

Upvotes: 9

Views: 2607

Answers (1)

B&#233;renger
B&#233;renger

Reputation: 2758

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

Upvotes: 3

Related Questions