C++ Abstract Classes
Abstract Classes
In the Polymorphism chapter, the Animal class had an animalSound() function that printed "The animal makes a sound". But a general animal does not really make one sound. Each kind of animal makes its own.
In cases like this, you can make the function pure virtual. A pure virtual function has no body. Instead, you write = 0 after it:
virtual void animalSound() = 0;
A class with at least one pure virtual function is called an abstract class. Every class that inherits from it must have its own version of the function:
Example
class Animal {
public:
virtual void animalSound() = 0;
};
class Pig : public Animal {
public:
void animalSound() override {
cout << "The pig says: wee wee\n";
}
};
class Dog : public Animal {
public:
void animalSound() override {
cout << "The dog says: bow wow\n";
}
};
int main() {
Pig myPig;
Dog myDog;
myPig.animalSound();
myDog.animalSound();
return 0;
}
You Cannot Create Objects of an Abstract Class
An abstract class is not complete, because one of its functions has no body. So you cannot create an object of it. You can only create objects of the derived classes:
Example
Animal myAnimal; // Error: Animal is an abstract class
Dog myDog; // OK
This is also a safety check: if Dog forgot to define animalSound(), Dog would also be abstract, and you would get an error when you try to create a dog.
Why Use Abstract Classes?
An abstract class describes what all the derived classes can do, without saying how. This lets you handle different objects in the same way, for example in a loop, with pointers to the abstract class:
Example
Using the Animal, Pig and Dog classes from above:
Pig myPig;
Dog myDog;
Animal* animals[2] = {&myPig, &myDog};
for (Animal* a : animals) {
a->animalSound();
}
The loop does not need to know if an animal is a pig or a dog. It just calls animalSound(), and each object runs its own version.