example1_safe_downcasting.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

class Base {
public:
    virtual void print() { std::cout << "Base" << std::endl; }
    virtual ~Base() {}
};

class Derived : public Base {
public:
    void print() override { std::cout << "Derived" << std::endl; }
    void derivedMethod() { std::cout << "Derived method" << std::endl; }
};

int main() {
    Base* basePtr = new Derived();

    // Safe downcasting
    Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);

    if (derivedPtr) {
        derivedPtr->derivedMethod();
    } else {
        std::cout << "Cast failed" << std::endl;
    }

    delete basePtr;
    return 0;
}
Back to dynamic_cast