C++ Polymorphism
Polymorphism means 'many forms'. In C++ it lets you call the same method on different objects and have each object respond in its own way. Combined with inheritance, it lets you write flexible code that treats many related types through a single, shared interface.
One method, many behaviors
The key to polymorphism in C++ is the virtual function. When a base class marks a method as virtual, a derived class can override it, and the correct version runs based on the actual object, not the type of the pointer or reference used to reach it.
Overriding a virtual method
#include <iostream>
using namespace std;
class Animal {
public:
virtual void sound() {
cout << "Some generic animal sound\n";
}
};
class Cat : public Animal {
public:
void sound() override {
cout << "Meow\n";
}
};
class Cow : public Animal {
public:
void sound() override {
cout << "Moo\n";
}
};
int main() {
Cat c;
Cow w;
c.sound(); // Meow
w.sound(); // Moo
return 0;
}Each class provides its own version of sound(). The override keyword is optional but recommended, because it asks the compiler to confirm that you really are overriding a base method and not accidentally writing a new one.
- virtual: marks a base method so derived classes can override it.
- override: tells the compiler this method replaces a virtual base method.
- A base pointer or reference chooses the right version at runtime.
Calling through a base class pointer
#include <iostream>
using namespace std;
class Shape {
public:
virtual void area() {
cout << "Area of a generic shape\n";
}
};
class Square : public Shape {
public:
void area() override {
cout << "Area = side * side\n";
}
};
int main() {
Shape* s = new Square(); // base pointer, derived object
s->area(); // prints the Square version
delete s;
return 0;
}Polymorphism lets you write one piece of code, such as a loop that calls sound() on a list of animals, and have each object behave correctly on its own. It keeps your programs open to new types without rewriting the code that uses them.
Exercise: C++ Polymorphism
What must a base class function be declared as for a derived class override to be invoked through a base class pointer?