In the following code, why does the last call of eat() on the reference c return \"An animal b is eating.\" ? From my
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.