In-Class Exercise

Virtual Functions


This exercise introduces early and late binding of calls to member functions. 


Given Information

The two client programs in the following sections use the Animal class hierarchy listed below. 

Animal Module

Animal.h

 // Virtual Functions
 // Animal.h

 #include <iostream>

 class Animal {
   public:
     virtual void display() const;
 };

 class Horse : public Animal {
   public:
     void display() const;
 };

Animal.cpp

 // Virtual Functions
 // Animal.cpp

 #include "Animal.h"

 void Animal::display() const {
     std::cout << "Animal" << std::endl; 
 }

 void Horse::display() const {
     Animal::display();
     std::cout << "Horse" << std::endl;
 }

Walkthroughs

The first walkthrough calls member functions on monomorphic objects of different type within the hierarchy.  The second walkthrough calls member functions on a polymorphic object of varying type within the hierarchy.

Two Monomorphic Objects

What is the output of the following program?

 // Virtual Functions
 // h16.m.cpp

 #include "Animal.h"

 void foo(Animal a)  {
     a.display();
 }
 void goo(Animal& a) {
     a.display();
 }

 int main() {
     Animal a;
     Horse h;

     a.display();
     foo(a);
     goo(a);
     h.display();
     foo(h);
     goo(h);
 }

One Polymorphic Object

What is the output of the following program?

 // Virtual Functions
 // h16.cpp

 #include "Animal.h"

 void foo(Animal a)  {
     a.display();
 }
 void goo(Animal& a) {
     a.display();
 }

 int main() {
     Animal* a;

     a = new Animal();
     a->display();
     foo(*a);
     goo(*a);
     delete a;
     a = new Horse();
     a->display();
     foo(*a);
     goo(*a);
     delete a;
 }



  Designed by Chris Szalwinski   Copying From This Site   
Logo
Creative Commons License