Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 937
Dan Dv Avatar asked Jul 17 '14 14:07

Dan Dv


1 Answers

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

like image 171
Bérenger Avatar answered Sep 30 '22 07:09

Bérenger