Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to downcast with non-polymorphic base class

In C++ , without making my destructor virtual Is it still possible to downcast pointers/references of my non-polymorphic base class?

like image 426
Adrika Avatar asked Oct 29 '22 00:10

Adrika


1 Answers

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.

like image 172
Tadeusz Kopec for Ukraine Avatar answered Nov 15 '22 07:11

Tadeusz Kopec for Ukraine