×

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

Factorial Program in C++

C++ Factorial Program: The product of all positive descending integers is the factorial of n. n! denotes the factorial of n. For instance: 5! = 5*4*3*2*1=120 4! = 4*3*2*1=24 In Combinations and Permutations, the...

4 minutes read.

Divide by Zero Exception in C++

We use exception handling method to handle the divide by zero exception. Dividing a number with zero is generally mathematical error. We have to exception handling method to overcome this...

2 minutes read.

Armstrong Number Program in C++

Let's first define Armstrong number before writing the C++ program to check whether the number is Armstrong or not. The sum of the cubes of its digits is equal to the...

2 minutes read.

Desired Capabilities in Selenium Web Driver in C++

A class called Desired Capabilities is used to specify a set of fundamental requirements, such as browser, operating system, and version combinations.to carry out automated testing of a web application...

7 minutes read.

Handling multiple clients on the Server with multithreading using Socket Programming in C or C++

To understand this guide completely, the reader is assumed to be familiar with the foundations of server and client models and socket programming. If one wants to create any scalable...

7 minutes read.

Bitwise Operator vs Logical Operator

Bitwise Operator  Bitwise operators perform operations bit by bit on bits.The value is converted to abinary during operations like addition, subtraction, division, and so on. These operations are carried out at the...

3 minutes read.

Convex hull Algorithm in C++

The intersection of all convex sets containing a certain subset of a Euclidean space, or alternatively, the set of all convex combinations of points in the subset, defines the convex...

4 minutes read.

Counting Frequencies of Array Elements in C++

We have an array of integer items with duplicate values, and our objective is to compute the frequencies of the different elements in the array. Methods: Methods that can be used to...

3 minutes read.

Substring in C++

A substring is a function in c++ that is imported from the string library. An element of a string is called a substring. A substring contains two parameters length and...

2 minutes read.

How is multiset implemented in C++

Similar to sets, multisets are an associative container type where several items may share the same values. Associative containers implement instantly searchable sorted data structures with O(log n) complexity. In a multiset,...

5 minutes read.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute read.

C++ References

C++ References An alias is a reference variable that is another name for a variable already in existence. If a relation is initialized with a variable, it is possible to use...

3 minutes read.

C++ Polymorphism

Polymorphism refers to the fact that something exists in several forms. Polymorphism, in simple terms, is the ability of a message to be presented in several formats. A real-life example...

4 minutes read.

Reverse a String using Stack C/C++

Reverse the given string using stack. To turn "tutorialandexample" into "elpmaxednalairotut," for instance. Here is a straightforward stack-based technique for reversing strings. Algorithm: 1) Make a stack that is empty. 2) Push each character...

3 minutes read.

What are local class and global class in C++

In C++, a class is a fundamental block that achieves object-oriented programming. The class holds its data members and member functions. Objects help to access the data elements and functions....

4 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.

C++ Nested if

C++'s nested if statements enable more complex decision-making when a section of code needs to execute only after a set of conditions is met. The nested if control statement refers...

4 minutes read.

Decimal to Hexadecimal in C++

We need to write a program in C++ that converts a decimal number into an equal hexadecimal number given a decimal value as input i.e. convert a number having a...

2 minutes read.

Difference between Two Sets in C++

The distinction between the two sets is made up of the components that are present in the first set but absent from the second set. The function consistently duplicates the...

3 minutes read.

Constructor Overloading in C++

A Constructor is a class member function that is used to initialize the class's objects. Constructors have no return type and are called automatically when an object is formed. Constructor Characteristics Constructors...

3 minutes read.