Table of contents
1.
Introduction
2.
What is a Virtual Function?
3.
Rules for Virtual Functions
4.
Working of Virtual Functions (Concept of VTABLE and VPTR)
5.
Using Virtual Function in C++
5.1.
C++
6.
Limitations of Virtual Functions
7.
Frequently Asked Questions
7.1.
What is a virtual and pure virtual function in C++?
7.2.
What is a virtual function with a real-time example?
7.3.
Why do we need virtual functions?
7.4.
What are pure virtual functions?
7.5.
Can you call it a pure virtual function?
7.6.
What is a virtual base class with an example?
7.7.
How do you create a pure virtual function?
7.8.
What is the difference between the virtual base class and the virtual function?
8.
Conclusion
Last Updated: Sep 6, 2024
Easy

What Is Virtual Function In Cpp?

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

Introduction

Virtual functions are used for tasking compilers with 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 functions in cpp

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

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