What is Virtual Function in C++: Explanation and Example
virtual function in C++ is a member function that you declare in a base class and expect to override in derived classes. It enables runtime polymorphism, meaning the program decides which function to call based on the actual object type during execution, not the pointer or reference type.How It Works
Imagine you have a remote control that can operate different types of devices like a TV or a music player. The remote has a button called "play". When you press it, the device should respond correctly depending on what it is. In C++, a virtual function works like that button. It allows the program to decide at runtime which version of the function to call based on the actual device (object) you are controlling, not just the type of the remote (pointer or reference).
Technically, when you declare a function as virtual in a base class, C++ creates a table called the virtual table (vtable) that stores pointers to the actual functions. When you call the function through a base class pointer or reference, the program looks up the vtable to find the right function to execute for the actual derived class object. This mechanism is called dynamic dispatch.
Example
This example shows a base class with a virtual function and two derived classes overriding it. The program calls the function through a base class pointer, but the correct derived class function runs.
#include <iostream> using namespace std; class Animal { public: virtual void sound() { cout << "Animal makes a sound" << endl; } }; class Dog : public Animal { public: void sound() override { cout << "Dog barks" << endl; } }; class Cat : public Animal { public: void sound() override { cout << "Cat meows" << endl; } }; int main() { Animal* animalPtr; Dog dog; Cat cat; animalPtr = &dog; animalPtr->sound(); // Calls Dog's sound() animalPtr = &cat; animalPtr->sound(); // Calls Cat's sound() return 0; }
When to Use
Use virtual functions when you want to write flexible and reusable code that works with different types of objects through a common interface. For example, in a graphics program, you might have a base class Shape with a virtual function draw(). Different shapes like circles and rectangles override draw() to display themselves correctly. This way, you can store different shapes in the same list and call draw() on each without knowing their exact type.
Virtual functions are essential in implementing polymorphism, which helps in designing systems that are easy to extend and maintain.
Key Points
- A virtual function allows derived classes to provide their own implementation.
- It enables runtime decision of which function to call, known as dynamic dispatch.
- Declared with the
virtualkeyword in the base class. - Helps achieve polymorphism and flexible code design.
- Without virtual functions, the base class version is always called when using base pointers or references.