Kishor Kishor - 1 month ago 6
C++ Question

Explanation needed for this weird polymorphic behavior

I was learning about polymorphism and tried some basic stuffs.In the following code, I have a virtual function

display()
in base class
Animal
.I made two derived classes,
Dog
that inherited from
Animal
and
Tommy
that inherited from
Dog
. The
display()
function was overridden in one of the derived class only(
Tommy
class in the following code).

In the
main()
function, I pointed to the derived objects through the base class pointer.I thought the following snippet would give me an error.

ptr = &dog;
ptr->display();


But, it ended up calling the
display()
of the parent class of
Dog
(i,e.
Animal
).Out of curiosity,I removed
display()
function in other derived classes and checked the output but I get the same behavior, always ends up calling the
display()
of the parent class.I don't know why this is happening.I think I am missing something here.Please help.

#include <iostream>

using namespace std;

class Animal
{
protected:
string name;
public:
Animal(string nam):name(nam){}

virtual void display()const {cout<<"Base class.\n";}

};

class Dog : public Animal
{
public:
Dog(string nam):Animal(nam){}

};

class Tommy : public Dog
{
public:
Tommy(string nam):Dog(nam){}

void display()const{cout<<"i am "<<name<<endl;}
};

int main()
{
Animal *ptr;
Dog dog("trace");
Tommy tom("tommy");

ptr = &dog;
ptr->display();

ptr = &tom;
ptr->display();


return 0;
}


The output was:

Base class.
i am tommy

Answer

But, it ended up calling the display() of the parent class of Dog(i,e. Animal).

This is totally expected behaviour as you did not overwrite virtual function display in your derived class Dog.

In order to have specific behaviour for the derived class, you must implement the non-pure virtual function display. You already have implementation for that function in the Tommy class, but no such implementation in the Dog class.

Comments