What is the output of the following code ?
#include <iostream>
using std::cout, std::endl;
class Hamburger {
public:
virtual void meet(Hamburger other) {
cout << "Moin "; other.salute();
}
virtual void salute() { cout << "Moin"; }
};
class French: public Hamburger {
public:
virtual void meet(Hamburger& other) {
cout << "Bonsoir "; other.salute();
}
virtual void salute() { cout << "Bonsoir"; }
};
int main() {
French pelu; French ehlu; Hamburger alex;
pelu.meet(alex); alex.meet(ehlu);
}
When looking at those kind of codes (polymorphism), use this generic approach :
So, for the example above, you have to apply this systematically :
pelu.meet(alex)
=> plain type (French pelu), call French::meet => Bonsoir in first and then
other.salute()
=> reference (Hamburger& other = alex) => the real class is Hamburger (Hamburger alex) => call Hamburger::salute => Moin in second
alex.meet(ehlu)
=> plain type (Hamburger alex) => call Hamburger::meet => Moin in third and then
other.salut()
=> plain type (Hamburger other = ehlu ... call by value !) => call Hamburger::salute => Moin in fourth
=> Bonsoir Moin Moin Moin
Of course, if the reference was not missing for
otherinHamburger::meet(Hamburger other), then dynamic binding would have been used and the last call would have beenFrench::salute, so aBonsoirin fourth.