Calling a virtual function on a reference

前端 未结 5 830
误落风尘
误落风尘 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条回答
  •  梦毁少年i
    2021-01-25 08:35

    You cannot re-bind a reference once you have bound it, so you have to use pointers instead of references:

    Animal *c = &a;
    c->eat();
    
    c = &b;
    c->eat();
    

    Now it will work exactly as you have wished it.

提交回复
热议问题