Search code examples
c++referenceoverridingoverloading

Calling the overriding function through a reference of base class


I googled and learnt the differences between function hiding and function overriding.

I mean I understand the output of testStuff(), which is seen in the below code snippet.

But what confuses me is that a instance of derived class could be assigned to a reference of the base class. And calling the overriding function through the said reference finally invoking the function of the derived class other than the base class.

Could somebody shed some light on this matter?

Here is the code snippet:

#include <iostream>

using namespace std;

class Parent {
  public:
    void doA() { cout << "doA in Parent" << endl; }
    virtual void doB() { cout << "doB in Parent" << endl; }
};

class Child : public Parent {
  public:
    void doA() { cout << "doA in Child" << endl; }
    void doB() { cout << "doB in Child" << endl; }
};

void testStuff() {   //I can understand this function well. 
  Parent* p1 = new Parent();
  Parent* p2 = new Child();
  Child* cp = new Child();

  p1->doA();
  p2->doA();
  cp->doA();

  p1->doB();
  p2->doB();
  cp->doB();
}

int main()
{
    Child cld;
    Parent prt  = cld;
    Parent &ref_prt  = cld;

    prt.doA();
    ref_prt.doA(); 

    prt.doB();
    ref_prt.doB(); //The one which most surprised me! I know `Child::doB()` overrides `Parent::doB()`. And I understand the output for `testStuff()`.
                   //But I still do not understand this line and `Parent &ref_prt=cld`.
    return 0;
}

Here is the output:

doA in Parent
doA in Parent
doB in Parent
doB in Child

Solution

  • But what confuses me is that a instance of derived class could be assigned to a reference of the base class. And calling the overriding function through the said reference finally invoking the function of the derived class other than the base class.

    It is indeed exactly like that.

    If a member function is virtual in a class, then calling it through a pointer-or-reference to that class will result in a dynamic dispatch, so if the actual object is of a derived class which overrides that function (btw, it neededn't declare it virtual because it's already virtual; and it'd better delcare it override, so that it errors out if it doesn't really override, e.g. because you mistyped the name), than that override will be called.

    Tha page linked above should sufficient to shed light on this as well as other doubts.