Jump to

v05-l3-findOutput2

Consider the code below :

class Person {
public:
    int drink() { return 1; }
};

class Student: public Person {
public:
    virtual int drink() { return 0.5; }
};

int payment(Person& p) { return p.drink(); }

int main() {
    Student bob;
    auto price = payment(bob);
}

What is the final value for the price variable ?

???

While the drink method is correctly redefined in the Student class (same signature), override is not complete since it is not declared virtual in the parent class. Since the payment method act on a Person& type, it can take bob as argument without doing any copy, but the compiler doesn't know that it has to use dynamic binding, hence Person::drink is used.

$\Rightarrow$ the correct answer is then what Person::drink returns, that is 1.

See findOutput.md for a similar question and more details ...