#include <iostream>
using namespace std;
class Base {
public:
void F(){cout << "Base::F" << endl;};
virtual void G(){cout << "Base::G" << endl;};
};
class Derived : public Base {
public:
void F(){cout << "Derived::F" << endl;};
void G(){cout << "Derived::G" << endl;};
};
int main(){
Derived *pDerived = new Derived;
pDerived->F(); //F was redefined
pDerived->G(); //G was overriden
Base *pBase = new Derived;
pBase->F();
pBase->G();
}
The output of this code is:
Derived::F
Derived::G
Base::F
Derived::G
Why does not the code produce the following output?
Derived::F
Derived::G
Derived::F
Derived::G
i.e. When a derived class object is initialized through a base class pointer, why is the function definition for a non-virtual function different from that of a derived class object initialized through a derived class pointer? Shouldn't the same type of object be initialized when we call "new Derived" whether it be from a base class pointer or a derived class pointer?
pBase
toDerived*
and see what happens. – juanchopanza