How to Use Virtual Function in C++: Simple Guide
In C++, use the
virtual keyword before a base class method to allow derived classes to override it. This enables runtime polymorphism, so calling the method via a base class pointer calls the derived class version if overridden.Syntax
Use virtual before a base class method declaration to make it overridable in derived classes. The method signature stays the same in derived classes, but you can provide a new implementation.
- virtual: marks the method as virtual
- return_type: type of value returned
- method_name(): method name and parameters
- override (optional in derived): clarifies method overrides base virtual method
cpp
class Base { public: virtual void show() { // base class version } }; class Derived : public Base { public: void show() override { // derived class version } };
Example
This example shows a base class pointer calling a virtual function. The derived class version runs because the function is virtual.
cpp
#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; } }; int main() { Animal* animalPtr = new Dog(); animalPtr->sound(); // Calls Dog's sound() delete animalPtr; return 0; }
Output
Dog barks
Common Pitfalls
Common mistakes include:
- Not marking the base class method as
virtual, so derived overrides won't work polymorphically. - Forgetting to use
overridein derived classes, which helps catch errors. - Deleting derived objects through base pointers without a virtual destructor, causing undefined behavior.
cpp
#include <iostream> using namespace std; class Base { public: void show() { // Missing virtual cout << "Base show" << endl; } }; class Derived : public Base { public: void show() override { // override keyword here causes error because base show() is not virtual cout << "Derived show" << endl; } };
Quick Reference
| Concept | Description |
|---|---|
| virtual keyword | Marks a base class method for runtime override |
| override keyword | Optional in derived class to ensure correct overriding |
| Polymorphism | Allows calling derived methods via base pointers |
| Virtual destructor | Ensures proper cleanup when deleting via base pointer |
Key Takeaways
Mark base class methods with
virtual to enable overriding in derived classes.Use
override in derived classes to catch mistakes and clarify intent.Always declare destructors as virtual if you delete derived objects through base pointers.
Virtual functions enable runtime polymorphism, calling the correct method version based on the object type.
Without
virtual, base class methods cannot be overridden polymorphically.