The CMSC 202 Zoo
The zoo heirarchy
The Animal (Base) class
Code is included here for presentation purposes only.
NO, you're not allowed to do this in your projects.
YES, you will lose lots of points if you do it.
YES, we'll discuss this in a later class.
class Animal
{
public:
Animal ( )
{ m_name = "no name"; m_nrLegs = 0; }
Animal ( const string& name, int legs)
: m_name ( name ), m_nrLegs( legs )
{ }
// virtual destructor
virtual ~Animal ( )
{ }
virtual void Speak ( ) const
{ cout << "Good Morning" << endl; }
const string& GetName ( ) const
{ return m_name; }
int GetNrLegs ( ) const
{ return m_nrLegs;}
void SetName (const string& name)
{ m_name = name; }
void SetNrLegs (int legs)
{ m_nrLegs = legs;}
private:
string m_name;
int m_nrLegs;
};
A Dog class
class Dog: public Animal
{
public:
Dog( )
: Animal("dog", 4), breed("dog")
{ }
Dog(const string& name, const string& breed)
: Animal( name, 4 ), m_breed( breed )
{ }
virtual ~Dog( )
{ }
virtual void Speak( ) const
{ cout << "Bow Wow"; }
void SetBreed(const string& breed)
{ m_breed = breed; }
const string& GetBreed( ) const
{ return m_breed; }
// overloading Speak( )
void Speak(int n) const
{
for (int j = 0; j < n; j++)
Speak();
}
private:
string m_breed;
};
A Whale
class Whale : public Animal
{
public:
Whale ( )
{ }
Whale(const string& name)
: Animal( name, 0 )
{ }
virtual ~Whale ( void )
{ }
};
A small Zoo program
int main ( )
{
Dog aDog ("Fido", "mixed");
Whale aWhale ("Orka");
aDog.Speak( ); // "Bow Wow"
aDog.Speak( 4 ); // Dog's overloaded Speak( )
aWhale.Speak( ) ; // Animal's Speak( ) -- inherited
Animal *zoo[ 3 ];
zoo[0] = new Animal;
zoo[1] = new Dog ("Max", "Terrier");
zoo[2] = new Whale;
for (int a = 0; a < 3; a++)
{
cout << zoo[a]->GetName( ) << "says ";
zoo[a] -> Speak( ); // dynamic binding -- polymorphism
cout << endl;
}
return 0;
Last Modified: Monday, 28-Aug-2006 10:16:04 EDT