Calling a virtual function on a reference

前端 未结 5 832
误落风尘
误落风尘 2021-01-25 08:06

In the following code, why does the last call of eat() on the reference c return \"An animal b is eating.\" ? From my

5条回答
  •  天涯浪人
    2021-01-25 08:35

    Animal & c = a;
    c.eat();
    
    c = b; ///^^^
    c.eat();
    

    In C++, reference cannot be rebind to other object once it is being initialized. c is still an alias of object a, which is an Animal, therefore, you saw the output which is expected.

提交回复
热议问题