0

Output of this program is "Method B". How can an instance of the parent object call the child class's function through a static_cast?

To make things more confusing, if I make method() virtual, then this code outputs "Method A".

Can anyone explain what is happening here?

class A {
public:

    void method() {
        cout << "Method A" << endl;
    }

};

class B : public A {
public:
    void method() {
        cout << "Method B" << endl;
    }
};

int main() {
    A a;
    B* bptr = static_cast<B*>(&a);
    bptr->method();
}
Dante
  • 139
  • 1
  • 2
  • 6

0 Answers0