C++ Virtual Function2 min read

Virtual function in C++ is a member function in the base class that we redefined in a derived class. With the use of a virtual function, we ensure that the function is overridden.

A virtual function lets the compiler know to perform dynamic linkage or late binding on the function (that is the called function needs to be resolved at run time).

A keyword ‘virtual‘ is used preceding with the function to be overridden. A virtual function cannot be a static member nor we can have a virtual constructor.

Let us understand through an example, we will first see a program without the use of virtual keywords and next with the use of virtual.


C++ Program Overriding a non-virtual function

Output:

As you can see in the above program that we created a pointer object for the base class and the function is the same in both of the classes which are to be overridden. But even though the object of the base class points to the derived class (a = &d;), when we call it through an object a, we still get the display() function of the base class.

Therefore, here we need a virtual function in order to get access to the member of the derived class which we will see in the program below.


C++ Program Overriding using a virtual function

Output:

As you can see above is the same first program but with a virtual display() function. And now the result is different, the base object a which is pointed to the derived class gives the display() function of the derived class indicating the virtual function of the base class is overridden by the derived class.


MORE

Find the output ab, cd, ef, g for the input a,b,c,d,e,f,g in Javascript and Python

In this tutorial, we will write a program to find a pairs of elements from an array such that for the input [a,b,c,d,e,f,g] we will …
Read More

String Pattern Programs in C

In this tutorial, we will write various C pattern programs for String. Before that, you may go through the following topics in C. for loop …
Read More

Java Program to Find pair of Integers in Array whose sum is given Number

In this tutorial, we will write a program to find a pair of elements from an array whose sum equals a given number in java …
Read More

Program to Print Diamond Alphabet Patterns in C

In this tutorial, we will learn to write a C program to print Diamond patterns using alphabets/characters. However, in this tutorial, we will create a …
Read More

Half Diamond Pattern in C using Alphabets

In this tutorial, we will learn and code the half diamond alphabet patterns in C programming language. However, in this tutorial, we will create a …
Read More

Half Pyramid of Alphabets in C

In this tutorial, we will learn and code alphabet patterns in C programming language specifically the Half pyramid of alphabets in C programming. However, in …
Read More