Understanding Virtual Functions in C++
The Foundation of Runtime Polymorphism

If you have ever written object-oriented C++ code, you have probably encountered the word virtual. It is one of the most important features in C++, and it is the foundation of runtime polymorphism.
In this article, I will explain virtual functions from scratch:
What they are
Why they were added
When they became part of C++
What problem they solve
How they make programming easier
Practical use cases
How to use them correctly
A clean example you can understand easily
1. What Is a Virtual Function?
A virtual function is a member function in a base class that you expect derived classes to override.
The key idea is this:
A base class declares a function as
virtualA derived class provides its own implementation
When you call the function through a base class pointer or reference, the program calls the derived class version
This is called runtime polymorphism.
A simple example:
#include <iostream>
using namespace std;
class Animal
{
public:
virtual void sound() const
{
cout << "Animal makes a sound\n";
}
};
class Dog : public Animal
{
public:
void sound() const override
{
cout << "Dog barks\n";
}
};
class Cat : public Animal
{
public:
void sound() const override
{
cout << "Cat meows\n";
}
};
int main()
{
Animal* animal1 = new Dog();
Animal* animal2 = new Cat();
animal1->sound(); // Dog barks
animal2->sound(); // Cat meows
delete animal1;
delete animal2;
}
Output:
Dog barks
Cat meows
This is the magic of virtual functions.
2. Why Are Virtual Functions Needed?
Without virtual functions, C++ would not support polymorphism in the way object-oriented programs expect.
Suppose you have a base class Shape and derived classes like Circle, Rectangle, and Triangle.
Each class has a method called draw().
Without virtual functions, a base class pointer would always call the base class version:
Shape* s = new Circle();
s->draw(); // calls Shape::draw(), not Circle::draw()
That is not what we want.
We want:
Shape* s = new Circle();
s->draw(); // should call Circle::draw()
This is exactly what virtual functions provide.
3. When Were Virtual Functions Added to C++?
Virtual functions are not a new feature added in a recent C++ standard. They are part of the language from the early days of object-oriented C++.
They were introduced as part of the C++ language design in the 1980s and later standardized in the C++98 standard, which was the first major ISO standard for C++.
So the short answer is:
Virtual functions are a core C++ feature
They are part of the language since early standardization
They are available in C++98, C++11, C++17, C++20, and C++23
4. What Problem Do Virtual Functions Solve?
Virtual functions solve a major problem in object-oriented programming:
Problem
When we work with a group of objects that share a common interface, we want to call the same function on each object, but each object should behave differently.
Example
Think of a game:
Player
Enemy
Boss
NPC
All of them may have a function called update() or attack().
We want code like this:
for (auto* entity : entities)
{
entity->update();
}
Each object type updates differently, but the loop stays the same.
This is the essence of polymorphism.
Without virtual functions, code becomes messy and hard to extend.
5. How Do Virtual Functions Make Life Easier?
They make life easier because they allow abstraction.
Instead of writing separate logic for every derived class, you can write code against a base class interface.
This leads to:
Less duplicated code
Cleaner designs
Easier extension
Better maintainability
Better object-oriented modeling
For example, imagine a program that handles many types of documents:
PDF
Word
Excel
Text
Each document can have a common method:
open()
You can write:
void openDocument(Document* doc)
{
doc->open();
}
And the correct implementation runs automatically.
That is much cleaner than writing:
if (doc is PDF) openPDF()
else if (doc is Word) openWord()
else if (doc is Excel) openExcel()
6. The Core Idea Behind Virtual Functions
A virtual function allows the compiler to call the correct function at runtime based on the actual object type.
This is different from normal function calls, which are resolved at compile time.
Normal function call
Shape* s = new Circle();
s->draw(); // compile-time resolution
This will call Shape::draw() unless the function is virtual.
Virtual function call
Shape* s = new Circle();
s->draw(); // runtime resolution
This will call Circle::draw() because draw() is virtual.
This is called dynamic dispatch.
7. How to Declare and Use a Virtual Function
A virtual function is declared in the base class using the virtual keyword.
Example:
class Base
{
public:
virtual void print()
{
std::cout << "Base class print\n";
}
};
Then derived class can override it:
class Derived : public Base
{
public:
void print() override
{
std::cout << "Derived class print\n";
}
};
The override keyword is optional but recommended. It helps catch errors.
Example:
#include <iostream>
using namespace std;
class Base
{
public:
virtual void print()
{
cout << "Base\n";
}
};
class Derived : public Base
{
public:
void print() override
{
cout << "Derived\n";
}
};
int main()
{
Base* ptr = new Derived();
ptr->print(); // Derived
delete ptr;
}
Output:
Derived
8. Pure Virtual Functions
Sometimes a base class should not provide a default implementation. In that case, we use a pure virtual function.
class Shape
{
public:
virtual void draw() const = 0; // pure virtual
};
A class containing a pure virtual function is an abstract class.
You cannot create objects of that class directly.
Example:
class Shape
{
public:
virtual void draw() const = 0;
};
class Circle : public Shape
{
public:
void draw() const override
{
std::cout << "Drawing a circle\n";
}
};
int main()
{
Shape* s = new Circle();
s->draw();
delete s;
}
This is very useful when you want to define a common interface without an implementation.
9. Why Is override Important?
In modern C++, we should use override when overriding a virtual function.
Example:
class Base
{
public:
virtual void show()
{
}
};
class Derived : public Base
{
public:
void show() override
{
}
};
If you accidentally type a wrong function signature, the compiler will report an error.
This reduces bugs.
10. Destructors and Virtual Destructors
This is very important.
If you delete an object through a base class pointer, the base class destructor must be virtual.
Example:
class Base
{
public:
virtual ~Base() = default;
};
class Derived : public Base
{
public:
~Derived() override
{
std::cout << "Derived destructor called\n";
}
};
int main()
{
Base* ptr = new Derived();
delete ptr; // calls Derived destructor correctly
}
If the base destructor is not virtual, only the base destructor is called. That can cause resource leaks and undefined behavior.
This is one of the most important rules in C++ object-oriented design.
11. Simple Real-World Example
Let us build a clean and readable example with shapes.
#include <iostream>
#include <vector>
using namespace std;
class Shape
{
public:
virtual ~Shape() = default;
virtual void draw() const
{
cout << "Drawing a generic shape\n";
}
};
class Circle : public Shape
{
public:
void draw() const override
{
cout << "Drawing a circle\n";
}
};
class Rectangle : public Shape
{
public:
void draw() const override
{
cout << "Drawing a rectangle\n";
}
};
class Triangle : public Shape
{
public:
void draw() const override
{
cout << "Drawing a triangle\n";
}
};
int main()
{
vector<Shape*> shapes;
shapes.push_back(new Circle());
shapes.push_back(new Rectangle());
shapes.push_back(new Triangle());
for (const auto* shape : shapes)
{
shape->draw();
}
for (const auto* shape : shapes)
{
delete shape;
}
}
Output:
Drawing a circle
Drawing a rectangle
Drawing a triangle
This is a perfect example of runtime polymorphism.
12. Practical Use Cases of Virtual Functions
1. Game Development
Game objects often share common behavior like:
move()
attack()
update()
render()
Each object behaves differently.
Example:
class Enemy
{
public:
virtual void attack() = 0;
};
class Goblin : public Enemy
{
public:
void attack() override
{
cout << "Goblin attacks!\n";
}
};
class Dragon : public Enemy
{
public:
void attack() override
{
cout << "Dragon breathes fire!\n";
}
};
Polymorphism lets the game loop handle enemies uniformly.
2. UI and Graphics Frameworks
Frameworks often have base classes like:
Button
TextField
Window
MenuItem
Each one can override render() or onClick().
3. Payment Systems
A payment app can have:
CreditCardPayment
UPIpayment
NetBankingPayment
All of them implement a common interface:
virtual void processPayment() = 0;
This makes the payment logic generic.
4. Database Drivers
Different database backends may implement:
connect()
query()
disconnect()
A common database interface can support multiple providers.
5. Device Drivers
Embedded systems often use sensor or device classes:
TemperatureSensor
PressureSensor
MotionSensor
All of them may implement read() differently.
13. Why Virtual Functions Are So Important in OOP
Virtual functions are one of the core reasons object-oriented programming is powerful.
They let us model real-world systems with shared behaviors but different implementations.
This gives us:
abstraction
extensibility
reuse
cleaner architecture
easier maintenance
Without virtual functions, object-oriented design would be much weaker.
14. Important Rules to Remember
Rule 1: Use virtual in the base class
virtual void display();
Rule 2: Override in derived classes
void display() override;
Rule 3: Always make base destructors virtual
virtual ~Base() = default;
Rule 4: Pure virtual functions create abstract classes
virtual void move() = 0;
Rule 5: Do not call base function unless you intend to
If you override a method and want to reuse the base logic, call it explicitly:
void Derived::show()
{
Base::show();
// additional logic
}
15. Common Mistake: Forgetting the virtual Keyword
This is a very common bug.
class Base
{
public:
void print()
{
cout << "Base\n";
}
};
class Derived : public Base
{
public:
void print()
{
cout << "Derived\n";
}
};
Now if you do:
Base* ptr = new Derived();
ptr->print(); // calls Base::print()
This is not polymorphic because print() is not virtual.
That is why the virtual keyword matters.
16. A More Professional Example: Employee System
#include <iostream>
#include <vector>
using namespace std;
class Employee
{
public:
virtual ~Employee() = default;
virtual void salarySlip() const
{
cout << "Generic employee salary slip\n";
}
};
class FullTimeEmployee : public Employee
{
public:
void salarySlip() const override
{
cout << "Full-time employee: salary based on monthly package\n";
}
};
class ContractEmployee : public Employee
{
public:
void salarySlip() const override
{
cout << "Contract employee: salary based on hours worked\n";
}
};
int main()
{
vector<Employee*> employees;
employees.push_back(new FullTimeEmployee());
employees.push_back(new ContractEmployee());
for (const auto* e : employees)
{
e->salarySlip();
}
for (const auto* e : employees)
{
delete e;
}
}
Output:
Full-time employee: salary based on monthly package
Contract employee: salary based on hours worked
This kind of design is very common in real software systems.
17. Summary
Virtual functions are one of the most important features in C++.
They allow:
runtime polymorphism
base class abstraction
function overriding
cleaner design
easier extensibility
They solve the problem of writing code that depends on concrete types when we really want to work with common behavior.
In short:
A virtual function lets derived classes customize behavior
The correct function is chosen at runtime
This is the foundation of polymorphism in C++
18. Final Thoughts
If you are learning C++, virtual functions are a must-know topic.
They are used in:
game engines
frameworks
libraries
operating systems
database layers
UI applications
large software systems
Once you understand virtual functions, you begin to write much more modular and scalable C++ code.
They are not just a syntax feature. They are a design concept that changes how you think about software.
19. Interview Questions You May Be Asked
What is a virtual function?
A virtual function is a member function in a base class that can be overridden in a derived class.
Why do we use virtual functions?
To achieve runtime polymorphism.
What is runtime polymorphism?
When the appropriate function is called based on the actual object type at runtime.
What is a pure virtual function?
A function declared as = 0 in a base class, making the class abstract.
Why is a virtual destructor important?
To ensure the correct derived destructor is called when deleting a derived object through a base pointer.
About the author
- Satish Waghole Expert Developer | Automotive Software Architect | Tech Enthusiast
Comments
Join the discussionNo comments yet. Be the first to comment.




