//animals.h
#include
//declaration of a base class (abstract)
class Animal {
public:
// pure virtual function -- MUST be overriden by derived class
virtual void pinch() = 0;
// virtual function -- MAY be overriden by derived class
// default behavior provided if not overriden
virtual void cry()
{ cout<<"Do not hurt me!\n\n"; }
};
//derived classes
class Cat : public Animal
{
public:
void pinch() { cout<< "MIAOW! \n "; }
};
class Dog : public Animal
{
public:
void pinch() { cout<< "WWOOF! \n" ; }
};
class Cow : public Animal
{
public:
void pinch() { cout << "MOOO! \n" ; }
};
class Tiger : public Animal
{
public:
void pinch() { cout << " GRRRRRR...Tasted good!\n"; }
void cry() {cout << " Who's next?" << endl << endl;}
};
//zoo.C
//test for virtual functions
#include "animals.h"
main ( )
{
Animal *a;
Animal *zoo[4];
int i;
Cat Felix;
Dog Snoopy;
Cow Liz;
Tiger ShereKhan;
zoo[0]=&Felix;
zoo[1]=&Snoopy;
zoo[2]=&Liz;
zoo[3]=&ShereKhan;
cout << "Welcome to the virtual zoo" << endl << endl;
// pinch and listen to each animal separately
// first treating it as a pointer to Animal
a=&Felix;
a->pinch ( );
a->cry ( );
// now calling it directly as a Cat
Felix.pinch();
Felix.cry();
// Same for the dog, first as a type of an Animal
a=&Snoopy;
a->pinch ( );
a->cry ( );
// Now calling it as a Dog
Snoopy.pinch ( );
Snoopy.cry ( );
// Just check on the other animals
// Cow
a=&Liz;
a->pinch ( );
a->cry ( );
// Tiger
a=&ShereKhan;
a->pinch ( );
a->cry ( );
// Now pinch all the animals in the zoo
cout << "Now for the whole zoo at once" << endl;
for (i=0; i<4; i++)
zoo[i]->pinch();
zoo[i]->cry();
}
}