Virtual Functions and Abstract Classes
Runtime polymorphism in C++ is achieved through virtual functions. Abstract classes have at least one pure virtual function.
Example
class Animal {
public:
// Virtual function — can be overridden
virtual void speak() const {
cout << "..." << endl;
}
virtual ~Animal() = default;
};
class Dog : public Animal {
public:
void speak() const override {
cout << "Woof!" << endl;
}
};
class Cat : public Animal {
public:
void speak() const override {
cout << "Meow!" << endl;
}
};
// Polymorphic behavior
void makeSound(const Animal& animal) {
animal.speak(); // calls the correct version
}
Dog dog;
Cat cat;
makeSound(dog); // "Woof!"
makeSound(cat); // "Meow!"
// With pointers
vector<unique_ptr<Animal>> animals;
animals.push_back(make_unique<Dog>());
animals.push_back(make_unique<Cat>());
for (auto& a : animals) a->speak(); 