0
#include<iostream>

using namespace std;
class Base {
public:
    Base()
    {
        cout << "Base constructor\n";
    }
    void f() {
        cout << "Base\n";
    }
};
class Derived :public Base {
    
public:
    Derived()
    {
        cout << "Derived constructor\n";
    }
    void f() {
        cout << "Derived\n";
    };
};
void main() {
    Derived *der;
    Base *base;
    der = (Derived*)new Base();
    der->f();

    der = new Derived();
    der->f();   
}

The output of above program is

Base constructor
Derived
Base constructor
Derived constructor
Derived

I m not sure how did derived class' function gets called when the derived class's object itself is not created. Could someone explain? Thanks!

user641247
  • 35
  • 6
  • This is undefined behavior. Anything can happen. – Sam Varshavchik May 15 '21 at 12:40
  • The use of a *cast* is telling the compiler "ignore what you see, and trust me, I know what I'm doing". But here the cast is obviously lying to the compiler. Lie to the compiler, and the footgun safety is off. – Eljay May 15 '21 at 12:49

0 Answers0