In C++ , without making my destructor virtual Is it still possible to downcast pointers/references of my non-polymorphic base class?
Virtual destructor has little to do with downcasting. The goal of making destructor virtual is to allow safe deletion through pointer to base.
Base * ptr = new Derived;
delete ptr; // undefined behavior if Base destructor isn't virtual
Downcasting can be performed using static_cast
, on your own responsibility
void processBase(Base * ptr)
{
// undefined behavior if ptr does not point to Derived
// object or some object that inherits from Derived
Derived * derived = static_cast<Derived *>(ptr);
}
There is also dynamic_cast
that will check if downcast is legal, but it requires that casted expression points (or refers) to a polymorphic object (i.e. object that has at least one virtual function declared or inherited).
5.2.7.6 Otherwise, v shall be a pointer to or an lvalue of a polymorphic type (10.3)
If the type of casted expression is not polymorphic, the program will fail to compile.
To summarize - making destructor virtual will make your class polymorphic, but same will be achieved by declaring any other virtual member function. To use dynamic_cast
you need a polymorphic type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With