OOP - Week 7, Lecture 1: Base-Class Pointers and Virtual Functions
A Zoo With Many Kinds of Animals
A zoo program keeps its animals. A dog barks, a cat meows, and a bird tweets. Every animal can make a sound, but each one makes its own. With what we know from Week 6, we write a base class Animal and one derived class for each kind, and each derived class has its own sound():
class Animal {
public:
void sound() const; // prints "makes a sound"
};
class Dog : public Animal {
public:
void sound() const; // prints Woof
};
class Cat : public Animal {
public:
void sound() const; // prints Meow
};
The zoo has many animals, and we want to go through all of them in one loop and ask each one to make its sound. But an array holds one type. A Dog array cannot hold a Cat, so we would need one array and one loop for each kind, and a new kind of animal would need a new array and a new loop.
What we want is one array of animals and one loop, where each animal makes its own sound. This is polymorphism, and it needs two things: a pointer of the base class, and virtual functions.
1. A Base-Class Pointer Can Point to a Derived Object
A Dog is an Animal, so a pointer of type Animal* is allowed to hold the address of a Dog:
Dog d("Rex");
Animal* a = &d; // allowed: a Dog is an Animal
The opposite is not allowed: a Dog* cannot hold the address of an Animal, because not every animal is a dog.
Now a is a pointer of type Animal*, and it points to a Dog object. There are two sound() functions: the one of Animal and the one of Dog. Which one runs when we call a->sound()?
Without virtual, the compiler looks only at the type of the pointer, which is Animal*, and it picks the sound() of Animal. It makes this choice when the program is compiled, so it does not matter that the object is really a Dog:
a->sound(); // Rex makes a sound: the sound of Animal runs, not the one of Dog
d.sound(); // Rex says Woof: d is a Dog
This is not what we want: the object is a dog, so it should bark. It is the same idea as in Week 6, where the function of the derived class hid the one of the base class: the name is looked up in the class that the code is written for, which here is Animal. A reference of the base class has the same problem: with Animal& r = d;, the call r.sound() prints Rex makes a sound.
2. Virtual Functions
To let the object decide, write virtual before the function in the base class:
class Animal {
public:
virtual void sound() const;
};
Now, when sound() is called through a pointer or a reference of type Animal, the program looks at the real object at the moment of the call and runs the version of that object:
Animal* a = &d;
a->sound(); // Rex says Woof: d is a Dog
The functions in the derived classes override the virtual function of the base class. They have the same name and the same parameters, and the keyword override after the function tells the compiler to check it:
class Dog : public Animal {
public:
void sound() const override;
};
Some points about virtual:
- Write
virtualin the base class. A function that overrides it is virtual too. - It only matters when the call is made through a pointer or a reference of the base class, like
a->sound(). When the function is called directly on an object, as ind.sound(), the version of the class of that object runs, with or withoutvirtual. - An
Animalobject still uses thesound()ofAnimal. - The function must have exactly the same name and parameters, with
constif the base one has it. If something is different, it is a new function that does not override anything.
Write
overridein the derived classes. If the function does not match a virtual function of the base class, for example whenconstis missing, the compiler gives an error. Withoutoverride, the mistake compiles, and the base version runs.
3. An Array of Base Pointers
Now one array can hold all the animals, because each element is a pointer of type Animal*, and every dog, cat and bird is an Animal. The array zoo has three slots. Each slot stores the address of one animal (&d, &c, &b), not a copy of the animal:
Dog d("Rex");
Cat c("Tom");
Bird b("Tweety");
Animal* zoo[3] = {&d, &c, &b};
for (int k = 0; k < 3; k++)
zoo[k]->sound(); // the same call: Woof, then Meow, then Tweet
The loop does not need to know which kinds of animals are in the array. If the zoo gets a fish, we write the class Fish : public Animal with its own sound(), create a Fish object, and add its address to the array. The loop body stays exactly the same:
Fish f("Nemo");
Animal* zoo[4] = {&d, &c, &b, &f};
for (int k = 0; k < 4; k++)
zoo[k]->sound(); // the same line: now it also runs the sound of the Fish
A function can also take a reference of the base class, and then it works for every kind of animal:
void makeNoise(const Animal& a) {
a.sound();
}
makeNoise(c); // Tom says Meow
4. Putting It Together
The program has Animal and three derived classes, each in its own header and .cpp file. main makes an Animal, a Dog, a Cat and a Bird, uses a base pointer, an array of base pointers, and a function with a base reference. The animals are ordinary objects, so there is nothing to delete yet. Lecture 2 shows what changes when they are created with new.
#ifndef ANIMAL_H
#define ANIMAL_H
#include <string>
using namespace std;
class Animal {
private:
string name;
public:
Animal(const string& n);
string getName() const;
virtual void sound() const;
};
#endif#include <iostream>
#include "Animal.h"
using namespace std;
Animal::Animal(const string& n) : name(n) {
}
string Animal::getName() const {
return name;
}
void Animal::sound() const {
cout << name << " makes a sound" << endl;
}#ifndef DOG_H
#define DOG_H
#include "Animal.h"
class Dog : public Animal {
public:
Dog(const string& n);
void sound() const override;
};
#endif#include <iostream>
#include "Dog.h"
using namespace std;
Dog::Dog(const string& n) : Animal(n) {
}
void Dog::sound() const {
cout << getName() << " says Woof" << endl;
}#ifndef CAT_H
#define CAT_H
#include "Animal.h"
class Cat : public Animal {
public:
Cat(const string& n);
void sound() const override;
};
#endif#include <iostream>
#include "Cat.h"
using namespace std;
Cat::Cat(const string& n) : Animal(n) {
}
void Cat::sound() const {
cout << getName() << " says Meow" << endl;
}#ifndef BIRD_H
#define BIRD_H
#include "Animal.h"
class Bird : public Animal {
public:
Bird(const string& n);
void sound() const override;
};
#endif#include <iostream>
#include "Bird.h"
using namespace std;
Bird::Bird(const string& n) : Animal(n) {
}
void Bird::sound() const {
cout << getName() << " says Tweet" << endl;
}#include <iostream>
#include "Dog.h"
#include "Cat.h"
#include "Bird.h"
using namespace std;
void makeNoise(const Animal& a) {
a.sound();
}
int main() {
Animal fish("Nemo");
Dog d("Rex");
Cat c("Tom");
Bird b("Tweety");
fish.sound();
Animal* a = &d;
a->sound();
Animal* zoo[3] = {&d, &c, &b};
for (int k = 0; k < 3; k++)
zoo[k]->sound();
makeNoise(b);
return 0;
}Click each line of output to see what caused it.