In-Class Exercise
Abstract Base Class
This exercise identifies the member functions that all concrete
classes in an inheritance hierarchy must implement.
Given Information
The following code for the Animal hierarchy is from
the Handout on Virtual Functions.
Client Module
The client program is listed on the left and the output is shown on the right
// 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;
}
|
Animal
Animal
Animal
Animal
Horse
Animal
Animal
Horse
|
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;
}
|
Your Task
Define an abstract base class named iAnimal.
Identify the following two member functions as functions that any
concrete class derived from this abstract class must implement:
- void display() const - displays the name of the animal
- void noise() const - displays the sound that the animal makes
// Abstract Base Class
// iAnimal.h
class iAnimal {
public:
};
|
Client Module
The client program that uses your upgraded class is
listed on the left and the results are listed on the right:
// Abstract Base Class
// h17.cpp
#include <iostream>
#include "Animal.h"
int main() {
iAnimal* a;
a = new Cat();
a->display();
a->noise();
delete a;
a = new Cow();
a->display();
a->noise();
delete a;
}
|
Cat
meow meow
Cow
moo moo
|
Animal Module
Complete the following header and implementation files.
Animal.h
// Abstract Base Class
// Animal.h
#include "iAnimal.h"
class Cat : public iAnimal {
public:
};
class Cow : public iAnimal {
public:
};
|
Animal.cpp
// Abstract Base Class
// Animal.cpp
#include <iostream>
#include "Animal.h"
|
|