If you know (somehow) that the object pointed to is actually an instance of an A
, then you can use static_cast
:
G* p = get_the_thing();
A* a = static_cast <A*> (p); // OK
However, if the object pointed to by p
above doesn't instantiate an A
, then the above code will yield undefined behavior.
A more safe approach would be to use dynamic_cast
,
G* p = get_the_thing();
A* a = dynamic_cast <A*> (p); // OK
Here, a
will be NULL
if p
isn't actually an A
. However, dynamic_cast
can only be used in this manner with polymorphic classes: the base class must have at least one virtual
function. A virtual
destructor would do nicely here.