Calling a virtual function on a reference

前端 未结 5 835
误落风尘
误落风尘 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:34

    A reference is an alias for an object. After you bind a reference to an object (and that must happen at initialization time), what you do on the reference is done on the object being referenced.

    In particular, you cannot re-bind a reference that has been already bound to an object and let it reference a different object. Thus, the following assignment (because that's an assignment, not an initialization):

    c = b;
    

    Is equivalent to the following:

    a = b;
    

    Since c is a reference to object a. The above assignment results in slicing, which is not what you wanted: c won't be a reference bound to b, but it will still be a reference bound to a, to which b has been assigned.

提交回复
热议问题