example2_pointer_conversion_inheritance_hierarchy.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
#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; }
};

int main() {
    Base* basePtr = new Derived();
    basePtr->print();  // Prints "Derived"

    // Downcasting
    Derived* derivedPtr = static_cast<Derived*>(basePtr);
    derivedPtr->print();  // Prints "Derived"

    delete basePtr;
    return 0;
}
Back to static_cast