George George - 2 months ago 12
C++ Question

Polymorphism in C++: virtual function doesn't give expected result

I have the following small program using inheritance and virtual functions:

#include <iostream>
#include <string>
using namespace std;

class Pet
{
string pname;

public:

Pet(const string& name) : pname(name) {}

virtual string name() const
{
return pname;
}

virtual string description() const
{
return "This is " + pname;
}
};

class Dog : public Pet
{
string favoriteActivity;
public:
Dog(const string& name, const string& activity)
: Pet(name), favoriteActivity(activity) {}

string description() const
{
return Pet::name() + " likes to " + favoriteActivity;
}
};

void describe(Pet p) // Slicing
{
cout << p.description() << endl;
}

int main()
{
Pet p("Alfred");
Dog d("Fluffy", "sleep");
describe(p);
describe(d);
}


When I run it, why do I get the following output?

"This is Alfred
This if Fluffy"


I was expecting the following output instead.

"This is Alfred
This if Fluffy likes to sleep" ?


If someone could please explain to me, I would be most grateful.

Answer

You just have it in the comment, it is slicing. You do not pass the same Dog object, you copy the Pet part as a new object. Your parameter p will be a completely different object with partial data of the original, and most importantly it will be a Pet object, not a Dog. Change it to either pass by reference or pointer, and it will be fine. This will use your original object with all the extra information to be properly displayed.

void describe(Pet *p)   // No more slicing
{
    cout << p->description() << endl;
}

OR

void describe(Pet &p)   // No more slicing
{
    cout << p.description() << endl;
}