×

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 know the basic properties of OOPs in C++. If you have already completed the basics, then you can move forward with this article and learn the abstract classes very quickly, but if you have not completed the Basics of OOPs, then it is recommended to complete the basics, else, you might not be able to understand the concept of abstract classes because this concept is associated with inheritance and encapsulation as well; these properties should be known to you.

Let's understand what abstract classes in c++ is.

Definition of an abstract class: A class that consists of at least one virtual function is known as an abstract class. There is a problem, the object of abstract classes cannot be created, but the main and important objective is to provide some necessary traits to the derived classes. We can easily create a base pointer to achieve run time polymorphism. The abstract classes cannot be instantiated. The child of abstract classes must process the body to the existing pure virtual function. Otherwise, the child class can always become the abstract class by itself. If anybody tries to instantiate the object, it will surely throw a compilation error. The objects can only be instantiated by creating a pure virtual function.

What is run time polymorphism?

We all know the word polymorphism, which refers to a concept where the same work can be done in multiple ways, or the action can be performed in many ways. The runtime polymorphism is a concept where the call to the overridden method can be resolved in runtime while executing the program. The overridden method is not resolved during compile time. The particular overridden method is called the superclass, and we use the superclass method's reference variable (the parent class's reference variable points to the children of the existing object class of the parent).

What is pure virtual function?

A function with no definition in the base class is a virtual function. The pure virtual function always ends with zero ( “0”)  in the declaration-derived classes overriding the pure virtual function.

So, let’s talk about abstract classes.

When we want to derive some concrete classes, this requires a broad concept and can be done using abstract classes. We must define at least one pure virtual class to create abstract classes.

Example of virtual function

Class Base_of_function {
   public:
    void print() {
        // Please write your code here for an operation
    }
};


class Derived: public Base_of_function {
   public:
    void print() {
        // Please write your code here for the operation


    }
};

Main function :

int main() {
    Derived the_derived_1;
    Base_of_function * base_first = & the_derived_1;


    // this always calls a function of the Base class, and then it does the execution of the operation
    Base_first ->print();


    return 0;
}

The virtual function :

class Base_first {
   public:
    virtual void print() {
        // Please write your code here for the operation
    }
};

We are creating the virtual function to make sure that the function is overridden.

Why do we avoid the creation of abstract class objects?

When a pure virtual function in Abstract is constructed, we have to reserve the respective slot in the Virtual TABLE for a function, but we know that we cannot put any address in the VTABLE or virtual table slot. As a result, we know there is a positive probability that the VTABLE will remain unfinished as the addresses are empty here, so that those slots will be empty. As per the result, the VTABLE, which resides for the Abstract class, will be missing, so the compiler will permanently restrict the creation of objects for this scenario, and we will encounter some bugs shown by the compiler.

Properties of abstract classes

There are different attributes of abstract classes. Some of them are listed below –

  • Instantiation of abstract classes cannot be done, but there would be a pointer that will maintain the reference to the abstract class.
  • The abstract class will always consist of pure virtual functions, at least, there would be one pure virtual function.
  • The derived classes can always access the interface of the abstract classes. This term is often referred to as upcasting.
  • Implementing all the existing virtual functions is mandatory to inherit the abstract class.

Example of abstract classes in c++

#include <iostream>
#include<bits/stdc++.h>
using namespace std;
 
// Base class
class Shape_of_the_structure {
   public:
      // this is the pure virtual function for providing the framework interface.
      //– A function with no definition in the base class is a pure virtual function. 
      virtual int get_the_Area() = 0;
      void set_the_Width(int w) {
         width_of_the_structure = w;
      }
   
      void set_the_Height(int h) {
         height_of_the_structure = h;
      }
   
   protected:
      int width_of_the_structure;
      int height_of_the_structure;
};
 
// this is the Derived classes, where we are declaring the functions 
class Rectangle: public Shape_of_the_structure {
   public:
      int get_the_Area() { 
         return (width_of_the_structure * height_of_the_structure); 
      }
};


class Triangle: public Shape_of_the_structure {
   public:
      int get_the_Area() { 
         return (width_of_the_structure * height_of_the_structure)/2; 
      }
};
 
int main(void) {
   Rectangle st1;
   Triangle  st2;
 
   st1.set_the_Width(10);
    st1.set_the_Height(15);
   
   //this will be printing the total area of the given structure.
   cout << "now we have computed the Total Triangle area-------\nTotal Rectangle area: " << st1.get_the_Area() << endl;


  st2.set_the_Width(10);
  st2.set_the_Height(15);
   
   //this will be printing the total area of the given structure.
   cout << "now we have computed the Total Triangle area-------\n total triangle area is -- : " <<st2.get_the_Area() << endl; 


   return 0;
}

When we run the following code in IDE or any online compiler, we get the following output -

Output.txt :

now we have computed the Total Triangle area-------
Total Rectangle area: 150
now we have computed the Total Triangle area-------
total triangle area is -- : 75

Explanation of the given code:

From the above code, we can see the interface is get_the_Area. This is the interface defined by the abstract class, and the two other declared classes are used to implement the same type of function, but the logic executed or given is different. We can say it differs in the algorithm. Every shape has a different approach to calculating its area, so we have declared abstract class, but we have declared two different methods for calculating the area. The virtual function helps to implement so.

Till now we have discussed different aspects of abstract classes, but there are some restrictions, so let's understand the limits of an abstract class.

Restrictions of abstract classes:  

  1. The abstract classes cannot be used for any variable or existing member functions, which makes it a little complicated because sometimes we have to deal with member functions too, and adding functionality becomes tough because we cannot use abstract classes and pure virtual functions for them. It is strictly followed that the created abstract class cannot be a member of any function because they are specifically made to be used for base classes.
  2. The abstract classes cannot be used as the return type of any function, we cannot declare them as the type of any explicit conversion, and they cannot be used as the parameter type. We are just allowed to use pointers as a reference to an abstract class.
  3. We are not allowed to create objects of an abstract class. If it is declared, then it will throw an error signal that “ object of an abstract class cannot be created".
  4. Suppose you want to access or call another member's function. In that case, the constructors of abstract classes can do such stuff, the constructors can call the particular functions of different members, but there is a problem if the called function is virtual, no matter whether they are called directly or indirectly, the result will be undefined. So, we need to be sure that the function we call is not the virtual function.

Why can’t the object of abstract classes be created?

If we talk practically, then abstract classes mean someone has instructed you to paint the whole building. Still, they have not mentioned any particular colour, so as you do not know the features, the creation of objects is impossible because the main feature of the object is their features. Without the feature, we cannot differentiate between different objects.


Related Topics

gmtime() function in C/C++

C++ language is used to make high-performance applications that can work efficiently. It is one of the world's most popular languages. It is an object-oriented and high-level programming language, which...

4 minutes read.

Bitmasking in C++

Bitmasking is a technique that is used to access a particular bit within the data bytes. When you apply the iterative approach, this phenomenon is used. A bitmask is described...

6 minutes read.

C++ String Class and its Applications

The String class is available in C++. The character array is represented by the C string. The string class in C++ has a few different attributes. It contains several functions...

4 minutes read.

How to Reverse a String in C++ using While Loop

A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the condition no longer...

6 minutes read.

Constructor Vs Destructor in C++

C++ Constructor A function Object () { [native code] } is a member function that shares the same name as the class. It is called automatically whenever a class object is...

3 minutes read.

C++ Continue

In C++, the continue statement is a useful tool for avoiding specific scenarios without breaking the loop. It is employed inside loops to move directly to the following iteration and...

4 minutes read.

Stack in C++

Stack: The stack is a very popular data structure. It is the form of data structure that follows a particular order called FIFO(First-In-First-Out). In simple words, a stack is an Abstract...

4 minutes read.

External merge sort in C++

External merge sort in C++ External sorting is a concept for a group of sorting algorithms capable of handling large data volumes. External sorting is needed if the information getting sorted...

9 minutes read.

swap() function in C++

Swap() function: swap() function in C++: swap() function is a pre-define function in c++ present in STL( Standard template library ). It is used to swap two numbers. It takes two mandatory...

6 minutes read.

C++ Iterators

What are iterators ? Iterators are among the four foundations of the C++ Standard Template Library, also known as the STL. The memory address of the STL container classes is pointed...

15 minutes read.

C++ Tricks for Competitive Programming

If you are interested in Computer science or Information technology, you must have heard about competitive programming. Competitive programming is a way to improve your problem-solving skills. There are various...

7 minutes read.

Data Hiding in C++

C++ : High-performance apps can be made using the cross-platform language C++. Bjarne Stroustrup created C++ as an addition to the C language. Programmers have extensive control over memory and system...

3 minutes read.

C++ Static

What is the Static keyword? In C++, the keyword static is used to give an element some particular properties. Static elements are only given storage in the static storage region once...

4 minutes read.

How to find the length of the vector in C++

Like dynamic arrays, vectors can automatically adjust their size when an element is added or removed, and the container manages its storage. Because vector items are stored in contiguous storage, iterators...

3 minutes read.

Multilevel Inheritance

C++ Multilevel Inheritance Multilevel inheritance is such an inheritance in which a derived class is created from another derived class. C++ Multilevel Inheritance Example In this example, a base class Student is inherited in...

2 minutes read.

Diamond Pattern in C++ using For Loop

For Loop: A for loop is a repetitive control structure that allows you to create a loop for executing a specific number of times. The syntax of for loop: In C++, a for...

5 minutes read.

Decimal to Binary in C++

What is the meaning of Decimal Numbers? Decimal numbers range from 0 to 9, there are a total of ten digits between 0 and 9. Any number with more than two...

3 minutes read.

How to Sort an Array in C++

What is Sorting? Sorting is a process of arranging elements in sequential order, either numerically or alphabetically. The sorting of a numerical array can be accomplished using a variety of algorithms,...

4 minutes read.

Program to convert infix to postfix expression in C++

Parentheses are frequently employed in mathematical formulas to make their interpretation easier to understand. However, with computers, parenthesis in an expression might lengthen the time it takes to find a...

7 minutes read.

How to Handle Divide by Zero Exception in C++

If you are a programmer or interested in coding then it is obvious that you face some illogical test cases. Suppose, you have written one program that calculates the factorial...

6 minutes read.