1
votes
#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?

1
It is not the initialization that is different. It is the fact that you are accessing non-virtual methods through a pointer.juanchopanza
@juanchopanza Would you be able to elaborate on that?Brian
That is the design of C++ - there are no automatic virtual functions.user2249683
Cast pBase to Derived* and see what happens.juanchopanza

1 Answers

4
votes

The function F() is not virtual, which means that the function call will be statically dispatched to the version in the static type of the pointer/reference, rather than let it find at runtime what the dynamic type of the object really is.

You can access the same function from a pointer to Derived if you qualify which variant you are interested in:

pDerived->Base::F();