logo CodeStepByStep logo

polymorphismMystery2

Language/Type: C++ inheritance polymorphism

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

class Computer : public Animal {
public:
    virtual void two() {
        cout << "C 2" << endl;
        Mineral::two();
    }

    virtual void three() {
        cout << "C 3" << endl;
    }
};

class Mineral : public Vegetable {
public:
    virtual void one() {
        cout << "M 1" << endl;
    }

    virtual void two() {
        cout << "M 2" << endl;
    }
};

class Animal : public Mineral {
public:
    virtual void one() {
        cout << "A 1" << endl;
        two();
    }

    virtual void three() {
        cout << "A 3" << endl;
    }
};

class Vegetable {
public:
    virtual void two() {
        cout << "V 2" << endl;
    }
};

Now assume that the following variables are defined:

Vegetable* var1 = new Computer();
Mineral*   var2 = new Animal();
Vegetable* var3 = new Vegetable();
Animal*    var4 = new Computer();

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->one();
var1->two();
var1->three();
var2->one();
var2->two();
var3->one();
var3->two();
var4->one();
var4->three();
((Animal*) var1)->one();
((Mineral*) var1)->two();
((Computer*) var1)->three();
((Vegetable*) var2)->three();
((Animal*) var2)->one();
((Computer*) var4)->two();
((Computer*) var4)->three();

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.