Virtual Functions - Kamills-12/2143-OOP GitHub Wiki
A virtual function lets you override a method in a child class, and have that child version actually get called even when you’re using a pointer or reference to the base class.
In short:
Use the correct version of a function, no matter what type of pointer you're holding.
This is the case of runtime polymorphism.
- It’s how C++ picks the right function at runtime.
- Lets you treat objects generically but still get custom behavior.
- Without it, the base class version always gets called.
#include <iostream>
using namespace std;
class Animal {
public:
virtual void speak() {
cout << "Animal sound." << endl;
}
};
class Dog : public Animal {
public:
void speak() override {
cout << "Woof!" << endl;
}
};
int main() {
Animal* a = new Dog();
a->speak(); // Outputs: Woof!
delete a;
return 0;
}