Student Exercises

Questions such as these have appeared on previous exams. They are good exercises in understanding inheritance, virtual functions and polymorphism.

Exercise 1

Predict the output from this code. There are no compiler errors.
Cut and paste this code, then compile and link to verify your predictions. #include <iostream> using namespace std; class B { public: virtual void Hello( ) const {cout << "Hello from B\n"; } virtual void IAm ( ) const { cout << "I am B\n"; } void GoodBye( ) const { cout << "Bye from B\n"; } }; class D : public B { public: virtual void Hello ( ) const { cout << "Hello from D\n"; } virtual void IAm ( ) const { cout << "I am D\n"; } void GoodBye ( ) const { cout << "Bye from D\n"; } }; class C : public D { public: virtual void IAm ( ) const { cout << "I am C\n"; } void GoodBye( ) const { cout << "Bye from C\n"; } }; int main ( ) { B *pB = new C; pB->Hello( ); pB->IAm ( ); pB->GoodBye ( ); cout << endl; D *pD = new C; pD->Hello( ); pD->IAm ( ); pD->GoodBye ( ); cout << endl; C *pC = new C; pC->Hello( ); pC->IAm( ); pC->GoodBye( ); }

Exercise 2

For each pair of lines of code in main( ), determine whether or not the code creates a compiler error. If so, state why. If not, what is output by the code.

You can verify your answers by copying/pasting this code and then compiling/linking and running it.
When you see a compiler error, comment out that code to continue.

#include <iostream> using namespace std; class A { protected: int val; public: virtual void Foo( ) { cout << "A in Foo!" << endl; } void Bar( ) { cout << "A in Bar!" << endl; } }; class B : public A { public: void Bar( ) { cout << "B in Bar!" << endl; } }; class C : public B { public: virtual void Foo( ) { cout << "C in Foo!" << endl; } void Bar( ) { cout << "C in Bar!" << endl; } }; class D : public A { public: virtual void Foo( ) { cout << "D in Foo!" << endl; } }; void test( B* b) { b->Foo(); } int main ( ) { A *a1 = new B; test( a1 ); C *c1 = new C; test( c1 ); A a2; a2.Foo(); B *b1 = new A; b1->foo(); D d1; test( &d1 ); A *a3 = new C; a3->Bar(); B b2; cout << b2.val; return 0; }


Last Modified: Monday, 28-Aug-2006 10:16:04 EDT