×

Pure Virtual Function in C++ With Example Program

What is a Virtual Function?

A virtual function is created inside a class with the keyword virtual. A virtual function does not have any value to be returned. Once a virtual function is created in a class, all its derived classes must include the same virtual function. In a virtual function, we don’t need to write any definition. Instead, we only have to declare it. Moreover, we need to assign 0 during the declaration part. If a class has a virtual function, then the class is called the abstract class.

Syntax

The syntax for virtual function:

Virtual function name;

Example for Virtual Function:

Example:1

//The code is written to demonstrate the use of the virtual class
//We are using the input and output operators in the code, so we have to include the iostream function.
#include<iostream>
using namespace std;
//Creating a class using the class keyword
class Base
{
int x;
public:
	//Creating a virtual function using the virtual keyword.
	virtual void fun() = 0;
	int getX() { return x; }
};


// Creating a derived class. This class inherits from Base and implements fun()
class Derived: public Base
{
	int y;
public:
	//Declaring the virtual function inside the derived class.
	void fun() { cout << "fun() called"; }
};


int main(void)
{
	//Creating an object of the derived class.
	Derived d;
	d.fun();
	return 0;
}

Output:

Pure Virtual Function in C++ With Example Program

Explanation:

The above code is written to demonstrate the use of the virtual function. We have created a base class in which we have created a virtual function. Then we created a derived class that will inherit the properties of the base class. We have declared the virtual function inside the derived class and included it in the cout statement. In the main function, we created an object for the derived class and then called the virtual function.

Example-2

// This code is used to demonstrate the use of the virtual function inside a class
//We have included the iostream header file for using the input and output operators.


#include <iostream>
using namespace std;


// Creating a class using the class keyword
class Shape {
   protected:
    float dimension;


   public:
		 //Creating a function member.
    void getDimension() {
        cin >> dimension;
    }


    // Creating a virtual method
    virtual float calculateArea() = 0;
};


// Inheriting the properties of the shape class inside the square class.
class Square: public Shape {
   public:
		 //using the virtual function created in the parent class.
    float calculateArea() {
        return dimension * dimension;
    }
};


// Inheriting the properties of the shape class inside the square class.
class Circle: public Shape {
   public:
    float calculateArea() {
        return 3.14 * dimension * dimension;
    }
};
//Creating the main function.
int main() {
	//Creating an object for the class square
    Square square;
		//Creating an object for the class circle.
    Circle circle;


    cout << "Enter the length of the square: ";


    square.getDimension();
    cout << "Area of square: " << square.calculateArea() << endl;


    cout << "\nEnter radius of the circle: ";
    circle.getDimension();
    cout << "Area of circle: " << circle.calculateArea() << endl;


    return 0;
}

Output:

Pure Virtual Function in C++ With Example Program

Explanation:

The above code is written to demonstrate the use of the virtual function inside a class. We have created a class shape in which we have created a protected variable dimension. In the public part of the code, we have created a function member get dimension and a virtual function using the virtual keyword inside the same class. As we know that the virtual function will not have any definition, we have given the value 0 to the virtual function. We created a class square and then inherited the properties of the shape class. In the square class, we have declared the virtual function created in the main class, which will return the area of the square. Then we also created another class circle in which we inherited the main class's properties. According to the virtual class properties, we have declared the virtual function in the circle class, which will return the area of the circle. In the main function, we have created the object for the square and circle classes. Then using the object name, we called the virtual function, which we have declared in the derived classes. Using the cout statement, printed the values of the square and the circle area.


Related Topics

Containership in C++

In C++, it is possible to create an object in one class into another class, and that object is a member of another class. This relationship is known as a...

4 minutes read.

C++ Continue in for loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the start...

4 minutes read.

C++ Deque

Definition: Deque or the Doubly ended queue is a data structure or operation performed under queue where insertion and deletion are allowed at both ends. A deque is an ordered collection of...

5 minutes read.

4-Dimensional Array in C/C++

A four-dimensional (4D) array is an array of three-dimensional (3D) arrays, or in other words we can say that a 4- dimensional array is an array of arrays of arrays...

3 minutes read.

C++ Virtual Destructor

In C++, a destructor is a class member function that is used to free up space or remove an object of the class that has gone out of scope. The...

4 minutes read.

Reverse String Word-Wise in C++

What is a reversed String? Reversing the words of a sentence is called reversed string by words. The difference between the reverse a string and the reverse a string word-wise is...

4 minutes read.

How to build a program in C++

Building a program is all about creating the program and executing it successfully. There are some steps  precisely, which must be followed to make the program. Step 1: Get an IDE...

4 minutes read.

Naming Convention in C++

The first and most fundamental step a programmer takes to produce clean code is to name a file or a variable. This naming must be acceptable so that it serves...

5 minutes read.

getline() Function and Character Array in C++

In this article, we will explore about some concepts on getline() function and character array in the most useful language C++. The getline() method in C++ is simply a standard library...

6 minutes read.

Private Inheritance in C++

Private inheritance is an inheritance in object-oriented programming (OOP) languages where a subclass derives from a superclass. Still, the derived class does not inherit the public and protected members of...

7 minutes read.

Ways to Copy a Vector in C++

Vectors in C++ are the same as arrays, along with additional outstanding features than them, like array lists in Java programming language. In Vectors, the size constraint is eliminated, which...

5 minutes read.

User-defined literals in C++

Introduction to User-Defined Literals: User-defined literals, introduced in C++11, are a way to extend the C++ language to allow users to define their literal suffixes and the corresponding behavior. These suffixes...

7 minutes read.

Single dimension array

C++ Array An array is a collection of data (elements) of the same data types. The elements of an array are allocated in contiguous memory allocation. Elements of the array are accessed through...

1 minute read.

C++ Overriding

C++ Function Overriding When the base and derive class both contain the same function name and calling the function through derived object invokes derived class function called function overriding. Function overloading is...

1 minute read.

C++ Aggregation

C++ Aggregation Definition: In C++, aggregation is a process in which one class (as an entity reference) defines another class. It provides another way to reuse the class. It represents...

4 minutes read.

Reverse a Number in C++

In this tutorial, you'll learn how to utilize a C++ program to reverse a number entered by a user at runtime. Because there are various ways to write a C++...

3 minutes read.

Abstract class in C++

In this article, you will get exposure to an abstract class in C++. We will discuss this topic using some practical examples too. To understand the abstract classes, you should...

6 minutes read.

Classes and Objects in C++

When it comes to object-oriented programming, objects are the basic building blocks. Memory is taken up by objects, which contain data and methods or functions that operate on it. On...

3 minutes read.

How the value is passed in C++

Introduction: The call-by-value method of giving arguments to a function duplicates the real value of an argument into the formal parameter of the function. In this instance, modifications to the parameter...

5 minutes read.

C++ Inline function

A C++ function that extends in line when called is known as an inline function. It reduces function call overhead by having the compiler use the function code rather than...

4 minutes read.