What Is Virtual Function In C++?

What Is Virtual Function In C++?
What Is Virtual Function In C++?

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 end up executing the functions of the base class.

Fundamentally, Virtual functions are used for ensuring that the intended functions are called for objects without being affected by 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.


What is a Virtual Function?

Virtual functions are member functions that users expect or estimate derived classes to redefine. Virtual functions are used for calling functions for objects from derived classes to execute various versions of the function in accordance with the derived class.

This is highly useful when a program can be estimated to call out multiple combinational functions from reference base classes or objects.

For example, if base classes contain functions that are declared to be virtual while a derived class also specifies the same functions, virtual functions allow the functions from derived classes to get invoked for the objects of the derived class even when pointers that refer to base classes are used. 

Let’s assume a base class which we will refer to as ‘Human’ is given a virtual function known as ‘Play’. We will refer to sub-classes as “Alex” and “John” would implement or execute the function ‘Play’ in different manners.

However, with virtual functions, one can execute the ‘Play’ function on every class probability of ‘Human’  and get the ‘Play’ function in return from each specified subclass. This fundamentally allows a list of objects to be processed from the ‘Human’ class that instructs each subclass to play (by calling the function ‘Play’).

Regardless of who it is (Alex or John) and not being affected by what the human plays or how each human plays. Virtual functions allow programs to seamlessly call functions without ever knowing the total possible combinations or the complete sets of class types (human in this instance).

Some programming languages treat every method as virtual by default and do not provide modifiers for changing this behaviour, however, programming languages such as C++ effortlessly allow the functions to be overridden or inherited.

blog banner 1

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();    
 }    
} 

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:

// 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();
}

Output:

Personal Account: 30000
Salary Account: 20000

In this example, the functions called for PrintBalance are similar in nature 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 are overriding the functions passing through the Account base class respectively. If classes are declared that do not offer function implementations of PrintBalance being overridden, default implementations in the Account base class get executed.

This is a great example of the use of virtual function 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 in nature.

The use of virtual function implies that functions are assumed to be overriding base classes and derived classes in C++.

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 also 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 being 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 in order to avoid becoming abstract in nature.

Can you call 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 for situations where 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 any function definitions. This can be done by assigning 0 and declaring it. If there is at least one virtual function, those classes are referred to as abstract classes.

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

Virtual base classes are great for the prevention of multiple instances of derived classes. Virtual functions are member functions of base classes that can be defined in derived classes as well.

What is a virtual function in Java with an example?

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();
}
}

Key Takeaways

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.