8

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?

Dan Dv
  • 473
  • 3
  • 12
  • "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. – Mike Seymour Jul 17 '14 at 14:15
  • @MikeSeymour besides the vtable, what else is pointed at? – Dan Dv Jul 17 '14 at 14:20
  • 1
    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. – Mike Seymour Jul 17 '14 at 14:22
  • [This](http://mentorembedded.github.io/cxx-abi/abi.html#rtti) may or may not be helpful. – lcs Jul 17 '14 at 15:24

1 Answers1

2

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

Bérenger
  • 2,678
  • 2
  • 21
  • 42
  • 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? – Moby Disk Jul 17 '14 at 17:47
  • If b is an array of bytes, the dynamic_cast won't even compile because b is not of type B. – Bérenger Jul 17 '14 at 18:34
  • 1
    @Moby Dick. No it does not compile (or should not). See http://stackoverflow.com/questions/4131091/dynamic-cast-from-void – Bérenger Jul 17 '14 at 21:00