In the following code, why does the last call of eat() on the reference c return \"An animal b is eating.\" ? From my
In order to make use of the dynamic polymorphism provided by virtual functions (distinguishing between derived and base classes during runtime), you need to access the derived class object via the base class pointer or reference.
I've commented out your code where confusion might have taken place:
int main( int argc , char ** argv )
{
Animal a("A");
a.eat();
Dog b("b");
b.eat();
// Make a reference (alias) to Animal object and set it to the object a.
// From this point on, whenever you write c, think "a".
Animal & c = a;
// So, this is a.eat()
c.eat();
// This is a = b (Animal = Dog): DANGER! SLICING! Here, the assignment operator
// slices the derived object and only assigns the base object "part" (remember,
// read "a", where you see "c" in your code):
// a.operator=(const A& b)
c = b;
// a.eat() = a is object of type A, so naturally, here you call A::eat()
c.eat();
return 0;
}