When you get a pointer to a polymorphic object, you have two types: the "static" type of the object, which in your case will be A * and its "dynamic" or "real" type, which depends on what was actually assigned to it .
Dropping A * into B * forces the compiler to consider this pointer as a pointer to B ; it is safe if you really know that this pointer is actually a pointer to B , otherwise the compiler will start writing pointless code (calling methods B for data of a different type).
The checks you are trying to implement are the home version of RTTI, which is a mechanism that lets you know what a "real type" of a pointer is or a reference to a polymorphic class, and it moves safely around. Check out typeid and dynamic_cast in your C ++ manual for more information on this. (By the way, IIRC dynamic_cast designed not only for security in the event of an incorrect dynamic type, but also for your pointer, if you use it in complex class hierarchies, it can also perform additional magic, so avoid C-style casting for polymorphic classes)
By the way, in general, he believed that the "smell of code" should manually check the "real type" of the pointer in order to use it and use its methods: the ideal of OOP could only do work, although
virtual methods are available in the base class.
A big warning: RTTI only works with polymorphic classes, that is, with classes that have at least one virtual method. On the other hand, if you are building a class hierarchy in which objects are passed as pointers to a base class, you will almost certainly want to create a virtual destructor, so that's okay.
source share