Calling a virtual function on a reference

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

    Because you can't rebind references. Once you initialized them, their name always refers to the object you have initialized them with.

    An object can have a name, e.g. Animal a("A"); creates an object of type Animal and introduces a name a which refers to this object.

    References on the other hand introduce names without introducing objects (let's not consider temporaries):

    Animal& c = a; // a new name `c` which refers to the same object as `a`
    
    // another (evil) example:
    Animal& c = *(new Animal("C")); // `new` introduces an object without name
                                    // `c` now refers to this object
    

    Concerning the assignment:

    Animal & c = a;
    // the name `c` is now equivalent to the name `a`
    
    c = b; // equivalent to `a = b;`
    

    This last assignment takes the object referred to by b, and copies its sub-object of type Animal to the object which c refers to. As a and c are equivalent, that's the same object a refers to. Therefore, a.name is set to "B".

    The virtual function call c.eat() of course operates on an id-expression (c) whose dynamic type is Animal - the same type as a - therefore, Animal::eat is called instead of Dog::eat.

提交回复
热议问题