Table of contents
1.
Introduction
2.
What is a Virtual Function?
3.
Key Characteristics of Virtual Functions in C++
4.
Types of Virtual Functions in C++
4.1.
What is a Pure Virtual Function?
4.2.
Key Characteristics of Pure Virtual Function
4.3.
Example
5.
Rules for Virtual Functions
6.
Working of Virtual Functions (Concept of VTABLE and VPTR)
7.
Using Virtual Function in C++
7.1.
C++
8.
Limitations of Virtual Functions
9.
Frequently Asked Questions
9.1.
What is a virtual and pure virtual function in C++?
9.2.
What is a virtual function with a real-time example?
9.3.
Why do we need virtual functions?
9.4.
What are pure virtual functions?
9.5.
Can you call it a pure virtual function?
9.6.
What is a virtual base class with an example?
9.7.
How do you create a pure virtual function?
9.8.
What is the difference between the virtual base class and the virtual function?
10.
Conclusion
Last Updated: Aug 13, 2025
Easy

Virtual Function In C++

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Virtual functions are used by task compilers when performing dynamic linkages or late-binding functions. A single pointer must be used for referring to objects of every class. So, virtual functions are used when the derived class objects execute the base class functions.

Fundamentally, Virtual functions are used to ensure that the intended functions are called for objects without affecting how the function calls are expressed. This is especially useful when the base class contains addresses of objects of the derived class. 

Functions are intended to be used ‘virtually’ through keywords that precede the original declarations of various functions. C++ identifies the functions that must be invoked during runtime according to the object types specified through the pointers of the base classes.

Virtual Function In C++

Also see, Literals in C, Fibonacci Series in C++

What is a Virtual Function?

Virtual functions are member functions that allow derived classes to redefine them. They are useful for calling functions from derived class objects, enabling different versions of a function to be executed by each derived class. This is especially helpful when a program needs to call different combinations of functions from base class references or objects.

For example, a base class called ‘Human’ may have a virtual function named ‘Play,’ and two subclasses, ‘Alex’ and ‘John,’ can each implement the ‘Play’ function differently. Virtual functions ensure that when calling ‘Play’ on an object of the derived class, the derived class’s version is executed, even if a base class pointer is used.

This means you can process a list of ‘Human’ objects and call the ‘Play’ function on each one. Regardless of whether the object is ‘Alex’ or ‘John,’ the correct version of ‘Play’ will run, making it easier to manage multiple derived class functions without needing to know all possible combinations of class types.

Some programming languages make all methods virtual by default, while others, like  C++ , let you explicitly override or inherit functions.

Here is an example of how virtual functions can be used in Java.

class
interface Woocommerce{    
void print();    
}    
class Bat implements Woo{    
public void print(){System.out.println("Woo!");}    
public static void main(String args[]){    
Bat obj = new Bat();    
obj.print();    
 }    
} 
You can also try this code with Online Java Compiler
Run Code

 

Also see, Four Pillars of OOPS

Key Characteristics of Virtual Functions in C++

  • Declared using virtual keyword: A virtual function is defined in the base class using the virtual keyword to allow derived classes to override it.
     
  • Supports Runtime Polymorphism: Virtual functions enable dynamic (run-time) binding, allowing the appropriate function to be called based on the actual object type.
     
  • Overridden in Derived Class: Derived classes can provide their own implementation of the base class's virtual function using the same signature.
     
  • Requires Base Class Pointer or Reference: To achieve runtime polymorphism, a base class pointer or reference should point to the derived class object.
     
  • Virtual Table (vtable) Mechanism: Internally, C++ uses a vtable (virtual table) to resolve function calls at runtime for classes with virtual functions.
     
  • Must Be a Member Function: Virtual functions cannot be static or non-member functions; they must be defined within a class.
     
  • Destructor Can Be Virtual: Declaring destructors as virtual ensures proper cleanup of derived objects when deleted using a base class pointer.

Types of Virtual Functions in C++

  • Regular Virtual Function
    A regular virtual function is declared using the virtual keyword and has a default implementation in the base class. Derived classes can override it, but it's not mandatory. If not overridden, the base class version is used during runtime.
     
  • Pure Virtual Function
    A pure virtual function is declared by assigning = 0 in its declaration. It doesn't have an implementation in the base class and must be overridden in derived classes. This makes the class abstract and prevents the instantiation of the base class directly.

What is a Pure Virtual Function?

A pure virtual function in C++ is a special type of virtual function that acts as a placeholder in the base class and must be overridden by all derived classes. It is declared by assigning = 0 in the function declaration, indicating that it has no implementation in the base class. The main purpose of a pure virtual function is to enforce a common interface among all derived classes. When a class contains at least one pure virtual function, it becomes an abstract base class, meaning it cannot be instantiated on its own. Pure virtual functions are crucial for implementing runtime polymorphism and for designing scalable object-oriented programs, ensuring all derived classes implement specific functionality according to their own behavior.

Key Characteristics of Pure Virtual Function

  • A pure virtual function has no definition in the base class.
     
  • It is declared using = 0 syntax at the end of the function declaration.
     
  • A class containing at least one pure virtual function is known as an abstract base class.
     
  • Objects of abstract base classes cannot be created. They can only be used as pointers or references.
     
  • Pure virtual functions enforce function overriding, ensuring derived classes must provide their own implementation.
     
  • They help achieve runtime polymorphism and define a consistent interface across subclasses.

Example

#include <iostream>
using namespace std;

// Abstract base class
class Shape {
public:
    virtual void draw() = 0; // Pure virtual function
};

// Derived class
class Circle : public Shape {
public:
    void draw() override {
        cout << "Drawing Circle" << endl;
    }
};

int main() {
    Shape* s;            // Base class pointer
    Circle c;            // Derived class object
    s = &c;
    s->draw();           // Calls Circle's draw() due to polymorphism
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Explanation:
In the above example, Shape is an abstract class because it contains a pure virtual function draw(). The Circle class inherits from Shape and provides its own implementation of the draw() function. The base class pointer s points to the derived class object c. When s->draw() is called, the overridden function in Circle is executed, demonstrating runtime polymorphism. This structure enforces that every shape must implement its own version of the draw() method, making the system extensible and maintainable.

Rules for Virtual Functions

  • The function must be declared in the base class using the virtual keyword.
     
  • Virtual functions allow overriding in derived classes to provide specific behavior.
     
  • Virtual functions cannot be static or friend functions of another class.
     
  • A virtual function should be accessed through a pointer or reference to the base class.
     
  • Constructors cannot be virtual, but destructors can and should be, especially in base classes.
     
  • If a derived class does not override a virtual function, the base class version will be used.
     
  • A class with virtual functions requires a virtual destructor to ensure proper cleanup when objects are deleted.

Working of Virtual Functions (Concept of VTABLE and VPTR)

Virtual functions work through a mechanism known as the VTABLE (Virtual Table) and VPTR (Virtual Pointer). When a class contains virtual functions, the compiler generates a VTABLE for that class, which holds pointers to the virtual functions. Each object of the class has a VPTR, which points to the corresponding VTABLE.

When a virtual function is called through a base class pointer, the VPTR directs the program to the correct function in the VTABLE, ensuring the right function from the derived class is executed. This allows dynamic binding, where the appropriate function is determined at runtime based on the actual object type.

Using Virtual Function in C++

Virtual functions define target functions that are not specified during compilation in C++. Virtual functions go hand-in-hand with OOP concepts (Object-Oriented Programming) and are an integral part of polymorphism.

In languages such as C++, virtual functions are inherited functions that can be easily overridden. Virtual functions are also methods that facilitate dynamic dispatches. Let’s check how we can use a virtual function in C++ with examples.

Here, we can see that the base class implements the function PrintBalance through two derived classes:

  • C++

C++

// deriv_VirtualFunctions.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;

class Account {
public:
Account( double d ) { _balance = d; }
virtual ~Account() {}
virtual double GetBalance() { return _balance; }
virtual void PrintBalance() { cerr << "Not available." << endl; }
private:
double _balance;
};

class SalaryAccount : public Account {
public:
SalaryAccount(double d) : Account(d) {}
void PrintBalance() { cout << "Salary account: " << GetBalance() << endl; }
};

class PersonalAccount : public Account {
public:
PersonalAccount(double d) : Account(d) {}
void PrintBalance() { cout << "Personal account: " << GetBalance(); }
};

int main() {
// Create objects of type SalaryAccount and PersonalAccount.
PersonalAccount salary( 30000.00 );
SalaryAccount personal( 20000.00 );

// Call PrintBalance using a pointer to Account.
Account *pAccount = &salary;
pAccount->PrintBalance();

// Call PrintBalance using a pointer to Account.
pAccount = &personal;
pAccount->PrintBalance();
}
You can also try this code with Online C++ Compiler
Run Code


Output:

Personal Account: 30000
Salary Account: 20000
You can also try this code with Online C++ Compiler
Run Code

 

You can try and compile with the help of online c++ compiler.
In this example, the functions called for PrintBalance are similar except for objects the pAccount refers to. Due to this PrintBalance function being virtual, the versions of functions for each object are defined differently.

The function PrintBalance in each derived class of SalaryAccount and PersonalAccount overrides the functions passing through the Account base class, respectively. If classes that do not offer function implementations of PrintBalance being overridden are declared, default implementations in the Account base class get executed.

This is an excellent example of using virtual functions in C++, as the functions from the derived classes are overriding the virtual function from only base classes when their types are identical. Functions from derived classes cannot be different from virtual functions that belong to base classes, as the argument lists need to be different.

Virtual functions imply that functions are assumed to override base classes and derived classes in C++.

Even though Java treats every method as ‘virtual’, it provides modifiers such as final keywords to prevent derived classes from overriding a method. Here is an example of a virtual function in Java.

class Dog{
void make(){
System.out.println("labrador");
}
}
public class Big extends Dog{
void make(){
System.out.println("Big Dog labrador ");
}
public static void main(String args[]){
Dog ob1 = new Big();
ob1.make();
}
}
You can also try this code with Online Java Compiler
Run Code

Limitations of Virtual Functions

  • Performance overhead: Virtual functions involve a slight performance cost due to dynamic binding, which occurs at runtime instead of compile time.
     
  • Memory usage: Virtual functions require additional memory to store the VTABLE and VPTR, leading to higher memory usage.
     
  • Cannot be inlined: Since the function to be called is determined at runtime, virtual functions cannot be inlined by the compiler, which may affect performance.
     
  • Complex debugging: Debugging programs with virtual functions can be more challenging due to dynamic dispatch, especially when dealing with multiple inheritance.
     
  • No virtual constructor: Virtual functions do not apply to constructors, which limits their use in certain design patterns.

Frequently Asked Questions

What is a virtual and pure virtual function in C++?

A virtual function can be defined as a member function that refers to a base class that can again be redefined by derived classes. Pure virtual functions are member functions of these base classes that are provided with only a single declaration in the base class.

What is a virtual function with a real-time example?

Virtual functions are declarations that use the base class as a reference and a derived class to be defined. A real-time example would be a list of subclasses that go through common functions but in different combinations. For instance, different types of accounts (sub-class), but all are bank accounts (class) that execute the function of printing balances in the accounts.

Why do we need virtual functions?

We need virtual functions to pass functions that behave interchangeably for different combinations of base classes and derived classes. Virtual functions are especially useful for polymorphism during runtime, especially due to users not knowing what will be called out and how.

What are pure virtual functions?

Pure virtual functions are virtual functions that must be defined in derived classes to avoid becoming abstract.

Can you call it a pure virtual function?

No, generally, we cannot call a virtual function. It goes against the set of rules. However, if codes call on pure virtual functions, compilers must include __cxa_pure_virtual, a call-to-library function.

What is a virtual base class with an example?

Virtual base classes are used when derived classes have multiple copies of base classes. These virtual base classes are then used for multiple inheritances so that multiple instances do not end in errors.

How do you create a pure virtual function?

Pure virtual functions can be created by simply declaring them and not writing function definitions. This can be done by assigning 0 and declaring it. Those classes are referred to as abstract classes if there is at least one virtual function.

What is the difference between the virtual base class and the virtual function?

Virtual base classes are great for preventing multiple instances of derived classes. Virtual functions are member functions of base classes that can also be defined in derived classes.

Conclusion

Virtual functions in C++ promote polymorphism during runtime and are especially helpful in avoiding instances of unexpected multiple associations. Rather than multiple instances, there are multiple associations that allow programs to be run without the exact probable outcomes being determined or declared.

Without these specifications, C++ passes the functions through subclasses by invoking the virtual function on each object of a class. This is especially helpful when there is an enormous list that needs to be run through an identical function with different combinations of variables.

Recommended Readings:

Live masterclass