What is Virtual Function In C++, its Benefits, Uses & More?

Updated on October 10, 2024

Article Outline

In C++, a virtual function is a member function that is declared within a base class and overridden by a derived class. When a developer refers to a derived class object using a pointer to the base class, we can call a virtual function for that specific task. In this article, we will deep-dive into virtual functions.

Introduction to Virtual Function in C++

In C++ programming language. A virtual function is a member function that is used in a base class or superclass, and this function overridden or derived class.  The base class pointer is used to access a derived class object, and a virtual function is called through that pointer The function that gets executed is determined at runtime based on the type of the object being pointed.

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Rules for Virtual Function

There are some rules for virtual functions in C++ language, which are as follows:

 

  • Virtual functions cannot be static.
  • In C++ programming language, the virtual function can be the friend of another class.
  • To achieve runtime polymorphism, we can access the virtual function in C++ language using a pointer or the reverse of the base class type.
  • The virtual function and prototype should be the same in the base as well as the derived class.
  • Virtual functions are always defined in the base class and overridden in a derived class. It is not mandatory for the derived class to override (or re-define the virtual function). In that base class version of the function is used.
  • A class may have a virtual destructor, but it cannot have a virtual constructor.

Example of Virtual Function in C++

The following program demonstrates the Virtual function in C++ language:

 

Program

#include <iostream> using namespace std; class Calculation { public: virtual void addition() { int a = 20 ; int b = 30 ; cout << “Addition” << ” ” << (a+b) << endl; } }; class Addition: public Calculation { public: void addition() { int a = 50 ; int b = 60 ; cout << “Addition” <<” “<< (a+b) << endl; } }; int main() { Calculation* calc; // pointer of parent class Addition addition; // object of child class calc = &addition; calc -> addition(); // Late Binding occurs }

Output

Addition 110

Compile-Time Polymorphism vs Run-Time Polymorphism

In this section, we will understand the behaviour of virtual functions. Let’s deep dive into the runtime behaviour in the C++ language.

 

The following program demonstrates the Runtime Virtual Function in C++ language:

 

Program

// C++ Programming language #include <iostream> using namespace std; class SuperClass { public: virtual void print() { cout << “This is super class n”; } void show() { cout << “This is super class show methodn”; } }; class DerivedClass : public SuperClass { public: void print() { cout << “This is derived class method n”; } void show() { cout << “This is show derived methodn”; } }; int main() { SuperClass* bptr; DerivedClass d; bptr = &d; // Virtual function, binded at runtime bptr->print(); // Non-virtual function, binded at compile time bptr->show(); return 0; }

Output

This is derived class method This is super class show method

The above program shows the runtime polymorphism through the pointer or reference of the Superclass type. A superclass pointer can point to the objects of the Superclass as well as the objects of the derived class. In the above program, the superclass pointer points to bptr, which contains the address of the object ‘d’ of the Derived class.

Working of Virtual Function in C++

In this section, we will see the working Virtual function in the C++ language. When a class consists of a virtual function, the C++ compiler responds by performing the following two actions. Every new object created of a class with at least one virtual function defined in it consists of a virtual pointer(VPTR).

 

In C++ language, each class with virtual Functions has its own vtable. This table holds pointers to the virtual functions defined by that class. Each object of such a class contains a pointer (vptr) to the vtable of its class. When a virtual function is called, the program uses the vptr to look up the function in the table and call the correct function. When a derived class overrides a virtual function, It updates the corresponding entry in its vtable to point to the derived class’s function.

 

The following program demonstrates the working Virtual function in C++ language:

 

Program

#include <iostream> using namespace std; class SuperClassEx { public: virtual void addition() { int a = 20 ; int b = 30 ; cout << “Addition =”<< (a+b) << endl; } }; class BaseClassEx : public SuperClassEx { public: void addition() override { int a = 30 ; int b = 90 ; cout << “Addition = “<< (a+b) << endl; } }; int main() { SuperClassEx* bptr; BaseClassEx d; bptr = &d; bptr->addition(); return 0; }

Output

Addition = 120

Use of C++ Override Identifier

The ‘override identifier’ explicitly indicates that a member function is intended to override a virtual function in a superclass. This helps the compiler developer catch errors and improves code readability by making the programmer’s intention clear. 

 

The following benefits of ‘override’ identifiers in C++ language:

 

  • Error Detection: If you use ‘override’ and the function doesn’t actually override any superclass function. This identifier helps us to catch mistakes and errors at the compile time.
  • Code Clarity:   The override identifier makes the code more readable and understandable. Another developer can immediately see that the function is intended to override a base class function.

 

The following program demonstrates the override identifier:

 

Program

#include <iostream> class SuperClassEx { public: virtual void show() { std::cout << “Super Class function” << std::endl; } virtual void display() { std::cout << “Super class display function” << std::endl; } }; class BaseClassEx : public SuperClassEx { public: void show() override { std::cout << “BaseClass Example show function” << std::endl; } void display() override { std::cout << “Display Example show function” << std::endl; } }; int main() { SuperClassEx* bptr; BaseClassEx d; bptr = &d; bptr->show(); bptr->display(); return 0; }

Output

BaseClass Example show function Display Example show function

Pure Virtual Function in C++ 

In C++ language. A pure virtual function is a virtual function that has no implementation in the superclass and must be overridden by the derived class. The pure function is just like an abstract keyword in Java language. It cannot be instantiated directly. Pure virtual functions are used to define interfaces in C++.

 

Syntax of Virtual function

 

class Base { public: virtual void show() = 0; // Pure virtual function };

Example of  Pure Virtual Function in C++

 

The following program demonstrates the Pure Virtual Function in C++ language:

 

Program

#include <iostream> using namespace std; class Shape { public: // Pure virtual function virtual void draw() = 0; // Normal member function void display() { cout << “Displaying Shape” << endl; } }; class Circle : public Shape { public: // Override pure virtual function void draw() override { cout << “Drawing Circle” << endl; } }; class Square : public Shape { public: // Override pure virtual function void draw() override { cout << “Drawing Square” << endl; } }; int main() { Circle c; Square s; Shape* shapePtr; shapePtr = &c; shapePtr->draw(); shapePtr->display(); shapePtr = &s; shapePtr->draw(); shapePtr->display(); return 0; }

Output

Drawing Circle Displaying Shape Drawing Square Displaying Shape

Advantages of Virtual Function

Here, we are discussing some common advantages of using virtual functions in C++ language:

 

  • Virtual function dynamic method invocation based on object type.
  • The virtual function adds new functionality through the derived classes in the virtual function.
  • Virtual functions help create abstract classes. Abstract classes are used to create a common interface for different classes.
  • The virtual function provides the ability to create an extensible and flexible source code in C++ language.
  • It allows late binding, which is also known as the run time polymorphism 
  • C++ developers can add or remove features from the existing objects using the virtual function. It reduces the overall flexibility by overriding a virtual function.

Disadvantages of Virtual Function

The virtual function also has some disadvantages, which are described below:

 

  • Virtual function calls can be slower than non-virtual function calls due to the need for dynamic dispatch.
  • Using a Virtual function can introduce complexity. Especially in large codebases or when dealing with multiple levels of inheritance.
  • Improper use of virtual functions or incorrect overriding can lead to unexpected behaviour and bugs in the software program.
  • Debugging code that heavily relies on virtual functions can be more challenging for C++ developers.

Conclusion

In this article, we learned about the Virtual function in the C++ language. It enables runtime polymorphism, allowing derived classes to override superclass functions. This provides flexibility and extensibility in source code. By using virtual functions, you can create more maintainable and scalable code where new functionality can be added via derived classes without altering the existing source code.

FAQs
A virtual function in C++ is a member function declared within a superclass and meant to be overridden in derived classes. A function is declared as virtual, and C++ uses a mechanism called dynamic dispatch to determine at runtime.
Here is the syntax of the virtual function in C++ language.             class Base {             public:             virtual void display() {                   std::cout << "Base class display function" << std::endl;                }             };
In C++ language, constructors cannot be virtual functions. However, destructors can and often should be virtual to ensure proper cleanup of derived class objects.
In C++ language. The virtual function is implemented using the virtual table(vtable) and virtual pointer (vptr). Each class with a virtual function has a vtable containing pointers to the virtual function has vtable that contains pointers to the virtual functions. At the runtime, the correct function is called through the vtable in C++ language.

Updated on October 10, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved