What will the following program display? why? explain public: virtual void eat()
ID: 3865568 • Letter: W
Question
What will the following program display? why? explain
public:
virtual void eat() {cout << "Yummy" << endl;}
virtual void speak() {cout << "Hello" << endl;}
virtual void sleep() {cout << "ZZZZ" << endl;}
};
class Student : public Person{
public:
void speak() {cout << "I love school" << endl;}
void study() {cout << "Studying for Midterm test" << endl;}
void getReadyForTest () {
study();
sleep();
}
};
class UCLAStudent : public Student {
public:
void speak() {cout << "Go Warriors!" << endl;}
void sleep() {cout << "ZZZ... CS2 ...ZZZZ" << endl;}
void getReadyForCS32Test() {
study();
eat();
sleep();
}
};
int main( ) {
Person* array[3];
array[0] = new Person();
array[1] = new Student();
array[2] = new UCLAStudent;
for (int i=0; i < 3; i++) {
array[i]->eat();
array[i]->speak();
array[i]->sleep();
}
Student * sp = new Student();
ElCaminoStudent *ecp = new ElCaminoStudent;
sp->getReadyForTest();
ecp->getReadyForCS32Test();
}
Explanation / Answer
Explaination:
int main( ) {
Person* array[3];
array[0] = new Person();
array[1] = new Student();
array[2] = new UCLAStudent;
for (int i=0; i < 3; i++) {
array[i]->eat(); // calls person class eat(), Student class eat() and UCLAStudent class eat method
prints "YUMMY" for each object as eat(0 method is not redefined in derived classes.
array[i]->speak(); // calls person class eat(), Student class eat() and UCLAStudent class speak method
//prints "Hello", "I Love School" and "Go Warriors!" as speak() is redeined in derived classes
array[i]->sleep(); // calls person class eat(), Student class eat() and UCLAStudent class sleep method
//prints "ZZZZ" for Person object , "ZZZZ" for Student object as not redefined in Student class and "ZZZ... CS2 ...ZZZZ" UCLAStudent class object as it is redefined .
}
Student * sp = new Student(); // pointer to Student class object
ElCaminoStudent *ecp = new ElCaminoStudent; // this is undefined class so create error
sp->getReadyForTest(); // getReadyForTest() method calls study() and sleep() method in Student class so it outputs "Studying for Midterm test" and "ZZZZ" .
ecp->getReadyForCS32Test(); // error as ElCaminoStudent class is not defined so pointer to an object of this class will not work.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.