typeid of a polymorphic class, when given a pointer to a derived class, says it's a pointer to base class! why?

277 views Asked by At

g++ 6.3.1.

This gdb session illustrates that dynamic_cast<> does the right thing, and the compiler shows the derived vtbl. dynamic_cast<> with the wrong derived class correctly returns 0 while it returns the correct pointer wit the right class. Yes typeid().name() shows the base class (or, a mangling thereof), P2TEBase! Why is this so?

(gdb) whatis pteExpect
type = TEBase *

(gdb) p *pteExpect
$1 = {
  _vptr.TE = 0x43cef8 <vtable for TEDerived1+16>
}

(gdb) p dynamic_cast<TEDerived2*>(pteExpect)
$2 = (TEDerived2*) 0x0

(gdb) p dynamic_cast<TEDerived1*>(pteExpect)
$3 = (TEDerived1*) 0x43cef8 <vtable for TEDerived1+16>

(gdb) l 170
170    Error( "Required %s not found", typeid( pteExpect ).name() );

(gdb) n
Reading in symbols for akstatus.c...done.
E 10.09 18:18:07.438818 main.cpp:170 Expect() - Required P2TEBase not found
1

There are 1 answers

0
Swiss Frank On

typeid is being called on the pointer to TEBase and therefore the type of this variable truly is a pointer to the base type, even if it happens to point to something else.

In order to log the class name of the derived class, simply use typeid( *pteExpect ).name() and you will see the 9TEDerived mangled name that g++ 6.3.1 will produce. Now, you aren't asking about the pointer (always a pointer to TE even if the object isn't the base class) but instead now you're asking for the thing that's pointed to, which, for a derived class of a polymorphic class, is the derived class.