1

I have the following simple inheritance example in C++.

#include<bits/stdc++.h>

using namespace std;

class Animal{
    public:
    string mName;

    Animal(string pName){
        mName=pName;
    }

    virtual void printAnimal(){
        cout<<"Animal "<<this->mName<<endl;
    }

};

class Dog: public Animal{

    public: 
    Dog(string pName): Animal(pName){}

    void printAnimal(){
        cout<<"Dog "<<this->mName<<endl;
    }
};

class Cat: public Animal{
    public:

    Cat(string pName): Animal(pName){}


    void printAnimal(){
        cout<<"Cat "<<this->mName<<endl;
    }
};

Animal getCat(){
    return Cat("Tom");
}

Animal getDog(){
    return Dog("Scooby");
}

int main(){
    getCat().printAnimal();
    getDog().printAnimal();
}

To my understanding, if we override a virtual function given in the base class, then no matter whether the reference is to the base class or the derived class, when the overridden function is called, it should call the function defined in the derived class and not the base class.

So one would expect the output of the above program to be,

Cat Tom
Dog Scooby

But I get,

Animal Tom
Animal Scooby

Why is this happening? What is the correct way to do this?

samurdhilbk
  • 419
  • 1
  • 5
  • 16

1 Answers1

2

You can pass the shared_ptr instead, to prevent object from object slicing as mentioned by @dude: Demo

shared_ptr<Animal> getCat(){
    return make_shared<Cat>("Tom");
}

shared_ptr<Animal> getDog(){
    return make_shared<Dog>("Scooby");
}

int main(){
    getCat()->printAnimal();
    getDog()->printAnimal();
}

Edit: changed return value from pointer to shared_ptr to prevent memory leak, as correctly suggested in comments.

Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79