logo CodeStepByStep logo

polymorphismMystery4

Language/Type: C++ inheritance polymorphism

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

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

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

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

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

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

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

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

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

Now assume that the following variables are defined:

Lisa* var1 = new Bart();
Bart* var2 = new Marge();
Lisa* var3 = new Homer();
Bart* var4 = new Homer();
Lisa* var5 = new Lisa();

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();
((Bart*) var1)->m1();
((Bart*) var1)->m3();
((Marge*) var5)->m3();
((Lisa*) var4)->m3();
((Homer*) var2)->m4();
((Marge*) 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.