logo CodeStepByStep logo

polymorphismMysteryHamburger

Language/Type: C++ inheritance polymorphism

Consider the following classes; assume that each is defined in its own file.

class Hamburger : public Bacon {
public:
    virtual void m2() {
        cout << "H 2" << endl;
        Bacon::m2();
    }

    virtual void m4() {
        cout << "H 4" << endl;
    }
};

class Mayo : public Hamburger {
public:
    virtual void m3() {
        cout << "M 3" << endl;
        m1();
    }

    virtual void m4() {
        cout << "M 4" << endl;
    }
};

class Lettuce {
public:
    virtual void m1() {
        cout << "L 1" << endl;
        m2();
    }

    virtual void m2() {
        cout << "L 2" << endl;
    }
};

class Bacon : public Lettuce {
public:
    virtual void m1() {
        Lettuce::m1();
        cout << "B 1" << endl;
    }

    virtual void m3() {
        cout << "B 3" << endl;
    }
};

Now assume that the following variables are defined:

Lettuce* var1 = new Bacon();
Bacon* var2 = new Mayo();
Lettuce* var3 = new Hamburger();
Bacon* var4 = new Hamburger();
Lettuce* var5 = new Lettuce();

In the table below, indicate in the right-hand column the output produced by the statement in the left-hand column. If the statement produces more than one line of output, indicate the line breaks with slashes as in "x / y / z" to indicate three lines of output with "x" followed by "y" followed by "z". If the statement does not compile, write "COMPILER ERROR". If a statement would crash at runtime or cause unpredictable behavior, write "CRASH".

var1->m1();
var1->m2();
var1->m3();
var2->m1();
var2->m2();
var2->m3();
var2->m4();
var3->m1();
var3->m2();
var4->m2();
var4->m3();
var4->m4();
((Bacon*) var1)->m1();
((Bacon*) var1)->m3();
((Mayo*) var5)->m3();
((Lettuce*) var4)->m3();
((Hamburger*)var2)->m4();
((Mayo*) var2)->m4();

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.