I have a base class (car) and a class that inherit the base class (honda):
class car
{
virtual void polymorphic_class()
{ }
};
class honda : public car
{ };
When I use the following code and I cast my class a get a null pointer:
list<car> cars;
honda h;
cars.push_back(h);
honda* h_ptr = dynamic_cast<honda*>(&cars.back());
// h_ptr is NULL
Why? How I have to cast properly my object?
Polymorphism works on pointers and references, not on object instances.
In this case, your list contains objects of type
car, not of any derived type. When you insert ahonda, it will copy thecarpart and ignore the rest; this is sometimes referred to as slicing.For polymorphism, you could use a list of pointers:
NOTE: If you do allocate using
newas in my example, remember to eitherdeletethem, or store smart pointers (likestd::unique_ptr<car>) rather than raw pointers. You’ll also need a virtual destructor in order to delete objects using a base-class pointer.You can avoid the slicing problem by making the base class abstract; if it contains pure virtual functions, then you can’t instantiate objects of that type, only of derived types that override those functions:
If you don’t actually want an abstract interface (e.g. if you only access derived-class functionality using
dynamic_castrather than through virtual functions), then you could make the destructor pure virtual instead; then the derived classes won’t have to explicitly override anything. The base class destructor must still be implemented and, due to a quirk of the language, that implementation must be outside the class definition:This is a somewhat unusual approach, since polymorphism through virtual functions is usually more efficient and more convenient.