Question 6 [5] with sample solutions
Show the precise output from the program below.
#include <iostream>
using namespace std;
class parent1 {
public:
virtual void print() = 0;
};
class parent2 {
public:
void print() { cout << "print version 1" << endl; }
};
class child1: public parent1 {
public:
child1() { cout << "start child type 1" << endl; }
~child1() { cout << "end child type 1" << endl; }
void print() { cout << "print version 2" << endl; }
};
class child2: public parent1 {
public:
child2() { cout << "start child type 2" << endl; }
~child2() { cout << "end child type 2" << endl; }
void print() { cout << "print version 3" << endl; }
};
class child3: public parent2 {
public:
child3() { cout << "start child type 3" << endl; }
~child3() { cout << "end child type 3" << endl; }
void print() { cout << "print version 4" << endl; }
};
int main()
{
parent1 *p1 = new child1;
parent1 *p2;
child3 c3;
p1->print();
p2 = new child2;
p2->print();
delete p2;
c3.print();
}
SAMPLE SOLUTION
start child type 1
start child type 3
print version 0
start child type 2
print version 0
print version 4
end child type 3
NOTES: because p1 and p2 are pointers to parent1's,
and because C++ uses static binding by default,
the p1->print(), p2->print(), and delete p2
operations all call the parent1 methods,
not the child methods.
|