Polymorphism
A derived class can have its own version of an inherited method. A Dog can make the sound "Woof" and a Cat the sound "Meow". Polymorphism means that the right version runs even when your code only knows it has "some animal".
A pointer of type Animal* can point to a Dog or a Cat, because a dog is an animal. Here is what happens when you call a method through such pointers:
#include <iostream>
#include <string>
using namespace std;
class Animal {
public:
string sound() {
return "...";
}
};
class Dog : public Animal {
public:
string sound() {
return "Woof";
}
};
class Cat : public Animal {
public:
string sound() {
return "Meow";
}
};
int main() {
Dog d;
Cat c;
Animal* animals[2] = {&d, &c};
for (int i = 0; i < 2; i++) {
cout << animals[i]->sound() << "\n";
}
return 0;
}
Output:
...
...
You met -> with this in the lesson on this and const methods. It reaches a member through a pointer, so animals[i]->sound() calls sound on the object that animals[i] points to.
Now the surprise: both lines print .... The objects are a Dog and a Cat, but the pointers have the type Animal*. The compiler only looks at the pointer type, so it calls the Animal version of sound both times.
The virtual keyword
To fix this, write virtual in front of the method in the base class. In the derived classes, write override after the method's parentheses:
#include <iostream>
#include <string>
using namespace std;
class Animal {
public:
virtual string sound() {
return "...";
}
};
class Dog : public Animal {
public:
string sound() override {
return "Woof";
}
};
class Cat : public Animal {
public:
string sound() override {
return "Meow";
}
};
int main() {
Dog d;
Cat c;
Animal* animals[2] = {&d, &c};
for (int i = 0; i < 2; i++) {
cout << animals[i]->sound() << "\n";
}
return 0;
}
Output:
Woof
Meow
virtual tells C++ to choose the method while the program runs, by looking at the real type of the object. The first object is really a Dog, so Dog::sound runs.
override is optional, but it helps. It asks the compiler to check that the method really replaces a virtual method of the base class. If you misspell the name as sond, the compiler stops with the error marked ‘override’, but does not override.
Why this is useful
The loop in main does not know about dogs or cats. It only knows about animals. If you add a Bird class later, with its own sound, you can put a bird in the array, and the loop itself does not need to change.
One thing is still not right. Animal::sound returns "...", which is not a real sound. The next lesson shows how to leave that body out.
In the exercise, shapes calculate their area through a base class pointer, but the wrong area runs. Add the missing keyword.