Virtual function in C++ (2023)

Virtual function in C++ (1)

In this blog, we will learn about virtual functions in C++. We will have a proper idea of ​​what is a virtual function in c++, why do we need it, its features and various identifiers in it, its uses and its example with code and explanation followed by pure virtual function with its explanation and code the code description with the operation.

What is a virtual function in C++?

C++ is one of the most used programming languages ​​in the world. The language contains the concept of Object Oriented Programming or OOps. Since it uses oops, it provides the four pillars of oops, namely encapsulation, polymorphism, abstraction, and inheritance. And with all these pillars provides the features and functions of these also one of them is the virtual function.

  • The virtual function in c++ is the same member function defined in the base class as well as a derived class, which means that the member function is redefined in the derived class.
  • So when you call the member function with the help of the base class pointer, it will call the base class function but not the derived class.
  • Therefore, we can say that the member function of the derived class does not override.
  • To override the member function of the derived class, we use a virtual keyword with the member function of the base class.
  • It is mainly used to achieve runtime polymorphism.
  • We just need to add a virtual keyword before the normal function declaration in the base class.
  • It is used to tell the compiler to perform late-binding or dynamic binding on the function.

Dynamic binding or late binding
In late-binding or dynamic binding, the function is resolved at run-time. So, at runtime, the compiler determines the type of the object and then wires the call to the function.

Virtual function rules

  • Virtual function in C++ cannot be present in any class, it must be a member of the same class. That is, the base and derived classes.
  • There is no limitation of being friends of any class, so they can also be friends of another class.
  • We can have a virtual destructor, but we can't have a virtual function constructor in C++.
  • We can access virtual functions in C++ with the help of object pointers.
  • Virtual functions in C++ cannot be static members.
  • They are always written to the base class and overridden in the derived class.
  • The name of the member function must be the same in both the derived class and the base class.
  • We have to write the "virtual" keyword before the function declaration in the base class.

Code example without virtual function in C++

In the following example, we will see the function without using a virtual function and we will see the result and the explanation of it.

  • C++
#include <iostream> using the standard namespace; class A { int x=75; public: void display() { std::cout << "O value of x is: " << x<<std::endl; } }; class B: public A { int y = 10; public: void display() { std::cout << "O value of y is: " <<y<< std::endl; } }; int main() { A *a; Bed and breakfast; a = &b; to->show(); return 0; }

Salida
The output of the above code will be

Code Explanation
In the above code, as you can see, we have two classes called A and B, class A is the base class while class B is the class derived from base class A. We have the same function called show in the base classes and derived and when we create a base class pointer and then call the display function, it will call the display function of the base class, not the derived class.

This indicates that the member function of the derived class is not overridden; in that case we can use the virtual function in C++.

As you can see in the output, we will be getting the value of x which is in the base class, so to get the value we will need a virtual function in C++.

Code example with virtual function in C++

In the following code, we'll look at an example where we're using a virtual function to get a derived class member function using a base class pointer.

  • C++
#include <iostream> using the standard namespace; class A { int x=75; public: void display() { std::cout << "O value of x is: " << x<<std::endl; } }; class B: public A { int y = 10; public: void display() { std::cout << "O value of y is: " <<y<< std::endl; } }; int main() { A *a; Bed and breakfast; a = &b; to->show(); return 0; }

Salida

Explanation of the above code of the virtual function in C++
As you can see in the code above, we write the virtual function with the member function of the base class and not with the member function of the derived class because it is the rule when dealing with virtual functions in C++ that we have to add a virtual keyword. before the member function of the base class.
As you can see in the output of the example above, the result is an invoked derived class. Therefore, the member function of the derived class is overridden.

How virtual functions work in C++

As we already mentioned, the compiler deals with virtual functions, so the compiler executes two functions in priority, that is:

  1. A virtual pointer (VPTR) is inserted as a class data member to point to the VTABLE of the class each time an object of that class is created. A new virtual pointer is added as a data member of this class for each new object produced.
  2. VTABLE, a static array of function pointers, is a member of the class regardless of whether an object is generated or not. The addresses of each virtual function found in that class are stored in the cells of this table.

Virtual function in C++ (2)

Virtual function example in C++

  • C++
#include<iostream>usando namespace std;class base {public: void fun_1() { cout << "base-1\n"; } virtual void fun_2() { cout << "base-2\n"; } virtual void fun_3() { cout << "base-3\n"; } virtual void fun_4() { cout << "base-4\n"; }};class derivada : public base {public: void fun_1() { cout << "derivada-1\n"; } void fun_2() { cout << "derivado-2\n"; } void fun_4(int x) { cout << "derivado-4\n"; }};int principal(){ base *p; obj1 derivado; p = &obj1; p->diversion_1(); p->diversion_2(); p->diversion_3(); p->diversion_4(); vuelve 0;}

Salida

Explanation of the above code.
First, we create a base class so that the base class pointer is created first, and then we initialize it and initialize it with the address of the corresponding derived class. Now, whenever we create an object of the derived class, the class that contains the VTABLE address of the derived class will be connected by a pointer created by the compiler.

And we use a similar concept in the example above for fun1() since it's in the base class so the base class is called for fun2() we have a virtual keyword in the base class so it's called the derived class and the function is replaced, but for fun3() and fun4() we don't have the virtual keyword, so the function is not replaced and therefore the base class is called.

Pure virtual function in C++

The virtual function is used as a placeholder and is not used to perform any tasks. The "do nothing" function is a function that has no definition. As explained above, functions that do nothing are known as pure virtual functions. When we declare a function in the base class without any definition regarding the base class, it is known as a pure virtual function.

Abstract base classes are classes that contain pure virtual functions and cannot be used to declare their own objects. There are some core functions in the base class that create some functions and pass these features to the derived class and we create a pointer to the base class that is used to achieve runtime polymorphism.

Pure virtual function example in C++

Here we will see the example of a pure virtual function in c++.

  • C++
#include <iostream> using the standard namespace; class Base { public: virtual void show() = 0; }; class Derived: public Base { public: void show() { std::cout << "This class is derived from the base class." << standard::endl; } }; int main() { Base *bptr; // Base b; derivative d; bptr = &d; bptr->display(); return 0; }

Salida

Pure Virtual Function Code Explanation in C++
As you can see in the above pure virtual function code example in C++. This is the base class, we create a pure virtual function and this function is derived in the derived class, so the output is shown as "This class is derived from the base class". And this base class is known as abstract base class.

Limitation of virtual functions in C++

  • The virtual function is a bit slower compared to other functions as we are not calling the function directly, we are following the proper mechanism which makes the process a bit slower and cannot be further optimized.
  • It is very difficult to find the error as it is not easy to debug and it is not easy to find the root cause of the error.

Frequently Asked Questions Related to Virtual Functions in C++

1. What do you understand by pure virtual function?
When a virtual function has no implementation and we only have to declare it, it is known as a pure virtual function or abstract function.
2. Can we have a virtual function constructor and destructor in C++?
No, we can't have a virtual function constructor, but we can have a virtual function destructor in C++.
3. Can we call a virtual function inside a non-virtual function?
Yes, we can call a virtual function from within a non-virtual function.

Conclution
In the article we study the virtual functions in c++ with its use, rules and the example showing the code before the use of the virtual function and another with the use of the virtual function with the proper explanation and followed by a pure virtual question with its example and finally the limitation of the virtual function.

Top Articles
Latest Posts
Article information

Author: Frankie Dare

Last Updated: 01/22/2023

Views: 5992

Rating: 4.2 / 5 (53 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Frankie Dare

Birthday: 2000-01-27

Address: Suite 313 45115 Caridad Freeway, Port Barabaraville, MS 66713

Phone: +3769542039359

Job: Sales Manager

Hobby: Baton twirling, Stand-up comedy, Leather crafting, Rugby, tabletop games, Jigsaw puzzles, Air sports

Introduction: My name is Frankie Dare, I am a funny, beautiful, proud, fair, pleasant, cheerful, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.