Safe downcasting

suggest change

Suppose that you have a pointer to an object of a polymorphic class:

Shape *ps;                       // see example on defining a polymorphic class
ps =  get_a_new_random_shape();  // if you don't have such a function yet, you 
                                 // could just write ps = new Square(0.0,0.0, 5);

A downcast converts a pointer or reference to a polymorphic base class, such as Shape, to a pointer or reference to a more specific derived class, such as Square or Circle.

Why downcast?

Most code does not need to know an object's dynamic type because virtual functions allow it to operate through the base-class interface:

std::cout << "Surface: " << ps->get_surface() << std::endl;

Avoid downcasting when a suitable virtual operation belongs in the base interface. Sometimes, however, code genuinely needs a non-virtual operation available only on a derived class.

For example, only a circle has a diameter. std::numbers::pi is C++20:

#include <numbers>

class Circle: public Shape { // for Shape, see example on defining a polymorphic class
    Point center_;
    double radius_;
public: 
    Circle(Point center, double radius)
        : center_(center), radius_(radius) {}

    double get_surface() const override {
        return radius_ * radius_ * std::numbers::pi;
    }

    // This operation is specific to circles.
    double get_diameter() const { return 2 * radius_; }
};

The get_diameter() member function exists only for circles; it is not part of Shape:

Shape* ps = get_any_shape();
ps->get_diameter(); // OUCH !!! Compilation error

How to downcast

If an invariant guarantees that ps points to a Circle, a static_cast is possible:

std::cout << "Diameter: " << static_cast<Circle*>(ps)->get_diameter() << std::endl;

Using the resulting pointer when the object is not actually a Circle produces undefined behavior. When the dynamic type is uncertain, use dynamic_cast and check the result:

int main() {
    Circle circle({0.0, 0.0}, 10.0);
    Shape& shape = circle;

    std::cout << "The shape has a surface of " << shape.get_surface() << std::endl;

    //shape.get_diameter();   // OUCH !!! Compilation error 

    Circle* pc = dynamic_cast<Circle*>(&shape);
    if (pc) {
        std::cout << "The shape is a circle of diameter " << pc->get_diameter() << std::endl;
    } else {
        std::cout << "The shape is not a circle" << std::endl;
    }
}

For this form of checked downcast, the source class must be polymorphic: it must declare or inherit at least one virtual function. A failed pointer cast returns nullptr; a failed reference cast throws std::bad_cast.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents