Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024

What Is Virtual Function In Cpp?

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

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 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 by the derived class.

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

For example, suppose base classes contain functions declared to be virtual while a derived class specifies the same functions. In that case, 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 called ‘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 affected by what the human plays or how each human plays. Virtual functions allow programs to seamlessly call functions without 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 behavior. However, programming languages such as C++ effortlessly allow the functions to be overridden or inherited.

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

 

Also see, Four Pillars of OOPS

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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

 

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

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:

Topics covered
1.
Introduction
2.
What is a Virtual Function?
3.
Using Virtual Function in C++
4.
Frequently Asked Questions
4.1.
What is a virtual and pure virtual function in C++?
4.2.
What is a virtual function with a real-time example?
4.3.
Why do we need virtual functions?
4.4.
What are pure virtual functions?
4.5.
Can you call it a pure virtual function?
4.6.
What is a virtual base class with an example?
4.7.
How do you create a pure virtual function?
4.8.
What is the difference between the virtual base class and the virtual function?
5.
Conclusion