example4_void_casting.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
#include <iostream>

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

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

int main() {
    Derived d;
    Base* bp = &d;

    bp->print();  // Calls Derived::print()

    // Explicitly call Base::print using void cast
    (bp->*static_cast<void (Base::*)() const>(&Base::print))();

    return 0;
}
Back to void