c++ - Calling a virtual function on a reference -
in following code, why last call of eat() on reference c return "an animal b eating." ? understanding, c reference instance b of derived class dog , eat() virtual function. should have returned "a dog b eating."
#include <string> #include <iostream> using namespace std; class animal { protected: string name; public: animal( string _name ): name(_name) { } virtual void eat() { cout << "an animal " << name << " eating." << endl; } }; class dog : public animal { public: dog( string _name ): animal(_name) { } void eat() { cout << "a dog " << name << " eating." << endl; } }; int main( int argc , char ** argv ) { animal a("a"); a.eat(); dog b("b"); b.eat(); animal & c = a; c.eat(); c = b; c.eat(); return 0; }
this output:
an animal eating. dog b eating. animal eating. animal b eating.
in order make use of dynamic polymorphism provided virtual functions (distinguishing between derived , base classes during runtime), need access derived class object via base class pointer or reference.
i've commented out code confusion might have taken place:
int main( int argc , char ** argv ) { animal a("a"); a.eat(); dog b("b"); b.eat(); // make reference (alias) animal object , set object a. // point on, whenever write c, think "a". animal & c = a; // so, a.eat() c.eat(); // = b (animal = dog): danger! slicing! here, assignment operator // slices derived object , assigns base object "part" (remember, // read "a", see "c" in code): // a.operator=(const a& b) c = b; // a.eat() = object of type a, naturally, here call a::eat() c.eat(); return 0; }
Comments
Post a Comment