- C++ Abstract Class and Pure Virtual Function
- When to use Pure virtual Function :
- Abstract Class
- Characteristics of Abstract Class
- Example 1: C++ Abstract Class and Pure Virtual Function
- Example 2: C++ Abstract Class and Pure Virtual Function
- Next Tutorial
- What are Pure Virtual Functions in C++? (with Example)
- What is a Pure Virtual Function in C++?
- Pure Virtual Function C++ Example
- Virtual Function vs Pure Virtual Function
- Advantages of Pure Virtual Functions
- Conclusion
C++ Abstract Class and Pure Virtual Function
A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have implementation, we only declare it. A pure virtual function start with virtual keyword and ends with = 0 .
Syntax of Pure virtual function :
When to use Pure virtual Function :
Pure virtual functions are used
- if a function doesn’t have any use in the base class
- but the function must be implemented by all its derived classes
Suppose, we have derived Car , Bike and Cycle classes from the Vehicle class, and we want to calculate the Speed of all these Vehicles.
In this case, we can create a pure virtual function named calculateSpeed() in the Vehicle . Since it’s a pure virtual function, all derived classes Car , Bike and Cycle must include the calculateSpeed() function with implementation.
A pure virtual function doesn’t have the function body and it must end with = 0 . For example,
class Vehicle public: // creating a pure virtual function virtual void calculateSpeed() = 0; >;
Note: The = 0 syntax doesn’t mean we are assigning 0 to the function. It’s just the way we define pure virtual functions.
Abstract Class
Abstract Class is a class which contains atleast one Pure Virtual function in it. Abstract classes are used to provide an Interface for its sub classes. A class that contains a pure virtual function is known as an abstract class.
In the above example, the class Vehicle is an abstract class.
We cannot create objects of an abstract class. However, we can derive classes from them, and use their data members and member functions (except pure virtual functions).
Characteristics of Abstract Class
- Abstract class cannot be instantiated, but pointers and refrences of Abstract class type can be created.
- Abstract class can have normal functions and variables along with a pure virtual function.
- Abstract classes are mainly used for Upcasting, so that its derived classes can use its interface.
- Classes inheriting an Abstract Class must implement all pure virtual functions, or else they will become Abstract too.
Example 1: C++ Abstract Class and Pure Virtual Function
#include using namespace std; // Abstract class class Base public: // pure virtual Function virtual void show() = 0; >; // Derived class class Derived : public Base < public: void show() < cout "Implementation of Abstract class and Pure virtual function."; > >; int main() < Derived obj; obj.show(); return 0; >
Implementation of Abstract class and Pure virtual function.
Example 2: C++ Abstract Class and Pure Virtual Function
// C++ program to calculate the area of a square and a circle #include using namespace std; // Abstract class class Shape protected: float dimension; public: void getDimension() < cin >> dimension; > // pure virtual Function virtual float calculateArea() = 0; >; // Derived class class Square : public Shape < public: float calculateArea() < return dimension * dimension; > >; // Derived class class Circle : public Shape < public: float calculateArea() < return 3.14 * dimension * dimension; > >; int main() < Square square; 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; >
Enter length to calculate the area of a square: 5 Area of square: 25 Enter radius to calculate the area of a circle: 7 Area of circle: 153.86
In this program,
virtual float calculateArea() = 0; inside the Shape class is a pure virtual function.
That’s why we must provide the implementation of calculateArea() in both of our derived classes, or else we will get an error.
Next Tutorial
We hope that this tutorial helped you develop better understanding of the concept of Abstract Class & Pure Virtual Function in C++.
In the next tutorial, you’ll learn about C++ Encapsulation .
What are Pure Virtual Functions in C++? (with Example)
Let’s break our main topic into bits. Look at this equation: Pure Virtual Functions = Pure + Virtual + functions. Following from right, we know about functions, and «Virtual» means virtual keyword which we use to achieve late binding as we implement it in virtual functions. In this article, we will look actually what are pure virtual functions in C++ with examples and advantages.
What is a Pure Virtual Function in C++?
A pure virtual function in C++ is a function that is declared in the base class but you cannot implement it, with a ‘0’ assigned to make them pure. In this way, the base class becomes an abstract class, and it must be inherited by a derived class, which provides an implementation for it.
Basically, they have the following characteristics:
- These functions also must have a prefix before the function’s name called ‘virtual’.
- In the base class, you can declare it, but you cannot implement it.
- ‘0’ must be assigned to the function to make them pure.
- The derived class must provide the implementation code for this function, else this derived class is also termed an ‘abstract class’.
Note that classes having at least one pure virtual function are called Abstract classes. Now we know theoretically, what are important points to keep in mind about the pure virtual functions to define, then let’s just quickly have a look at its syntax as well.
Given below is the way to declare the pure virtual functions in C++ :
virtual function_type function_name() = 0;
The main use of pure virtual functions is to create an abstract class that defines an interface for its derived classes. An abstract class is like a base class for other classes to provide a common interface to implement. This helps us use the polymorphism feature of the programming language.
Pure Virtual Function C++ Example
Since we already understand the declaration part of a pure virtual function, now let’s see how to code it in C++ and how to provide its implementation in the derived class. Given below can be the best example :
//Welcome to FavTutor
#include using namespace std; // here is Abstract class class Shape < public: virtual int cal_Area() = 0; // cal_Area is a pure virtual function >; class Square : public Shape < int a; public: Square(int l) < a = l; > int cal_Area() < return a*a; // returns area of square > >; class Circle : public Shape < int r; public: Circle(int x) < r = x; > int cal_Area() < return 3.14*r*r ; > >; class Rectangle : public Shape < int l; int b; public: Rectangle(int x, int y) < l=x; b=y; > int cal_Area() < return l*b; // returns the product of length and breadth > >; int main() // main function < Shape *shape; Square s(3.4); Rectangle r(5,6); Circle c(7.8); shape =&s; int a1 =shape->cal_Area(); shape = &r; int a2 = shape->cal_Area(); shape = &c; int a3 = shape->cal_Area(); std::cout "The area of square is: " a1 std::endl; std::cout "The area of rectangle is: " a2 std::endl; std::cout "The area of circle is: " a3 std::endl; return 0; >
The area of square is: 11 The area of rectangle is: 30 The area of circle is: 191
After going through the above, you can observe that we define a shape class as a base, then we are deriving classes from it and using the member function of the base class to calculate the area, the important thing to note here is that we are efficiently using the pure virtual function cal_area.
But how? See we are not using multiple functions in every derived class to calculate the area rather we are using just the different implementations of it by defining it once in the base class, I hope this will put you in a state where you have found yourself more powerful as you have this craziest tool to use it in your C++ program now.
Virtual Function vs Pure Virtual Function
The following are the differences between a virtual and a pure virtual function in C++. A virtual function and a pure virtual function are both declared with the word «virtual» at the beginning of the code declaration, but their syntax is different.
Syntax of virtual function:
virtualfunction_type>function_name>() < // code >
Syntax of pure virtual function:
virtualfunction_type>function_name>() = 0;
Look at the below table for a complete list of differences:
Virtual Function | Pure Virtual Function |
In the virtual function, the derived class overrides the function of the base class; it is the case of the function overriding. | In a pure virtual function, the derived call would not call the base class function as it has not defined instead it calls the derived function which implements that same pure virtual function in the derived call. |
Class containing virtual function may or may not be an Abstract class. | If there is any pure virtual function in a class, then it becomes an «Abstract class». |
Virtual function in the base does not enforce to derived for defining or redefining | In pure virtual function, the derived class must redefine the pure virtual class of the base class. Otherwise, that derived class will become abstract as well. |
Advantages of Pure Virtual Functions
Let’s now look at the key advantages of pure virtual functions in C++ one by one:
- Abstraction: Pure virtual functions are a way to separate the interface from the implementation, to make the code easier to maintain.
- Polymorphism: A base class pointer is used to call functions of its derived classes, a key way to use polymorphism in C++.
- Reusability: Since we define a common interface, we reduce the amount of code and make it more reusable.
Overall, they are one way to use the object-oriented programming features of C++ and make the code more modular and maintainable.
Conclusion
Hope this article clears your concepts of pure virtual functions in C++ and more specifically, why it is pure. Now you can also use it in your C++ program too instead of creating multiple different functions in every other derived class, define it only once in the base class and create your own implementations. Happy Learning 🙂