OOP: POLYMORPHISM
Virtual Functions
A virtual function is a member function in a base class that can be overridden in a derived class and called dynamically through a base-class pointer or reference.
The keyword is:
virtual
The Problem Without virtual
#include <iostream>
using namespace std;
class Animal {
public:
void sound() const {
cout << "Animal sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() const {
cout << "Bark" << endl;
}
};
int main() {
Dog dog;
Animal* animal = &dog;
animal->sound();
return 0;
}
Output:
Animal sound
Why? The pointer type is Animal*, so without virtual, the compiler binds the call to Animal::sound().
The Solution With virtual
#include <iostream>
using namespace std;
class Animal {
public:
virtual ~Animal() = default;
virtual void sound() const {
cout << "Animal sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() const override {
cout << "Bark" << endl;
}
};
int main() {
Dog dog;
Animal* animal = &dog;
animal->sound();
return 0;
}
Output:
Bark
Why override Is Useful
override tells the compiler:
This function must override a virtual function from the base class.
If the signature is wrong, the compiler gives an error.
This protects against mistakes like:
void sound(); // missing const, so it does not override void sound() const
Rules for Virtual Functions
- Virtual functions are declared in the base class.
- Derived classes override them using the same signature.
- Runtime polymorphism works through base-class pointers or references.
- Constructors cannot be virtual.
- Destructors can be virtual and should be virtual in polymorphic base classes.
overrideis optional but strongly recommended.
Viva Answer
A virtual function is a base-class function that supports runtime polymorphism. When it is called through a base-class pointer or reference, C++ checks the actual object type at runtime and calls the overridden derived-class version.
Quick Check
- What does
virtualchange in the example? - Why does the base pointer call
Dog::sound()after addingvirtual? - Why should we use
override?