×

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

Palindrome using Do-while loop in C++

What is Palindrome? A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++...

5 minutes read.

Features of OOPS in C++

What is OOPs? The main reason programmers prefer C ++ language over C is because of the support of object-oriented programing in C++. As the name suggests, object-oriented programming or OOPs...

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

C++ Range-based For Loop

In C++ language, the range-based for loop was added, which is far superior than the ordinary For loop. The implementation of a range-based for loop doesn't really need much code. It's a...

4 minutes read.

Returning a Function Pointer from a Function in C/C++

Pointers to functions can be used in the C programming language just like standard data pointers such as "int *," "char *," etc. The following is a basic example of a...

3 minutes read.

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++ 1/2 decimal equal is 0.555555555555555555555 .... An indefinite number of lengths will require the storage...

4 minutes read.

C++ Exception Handling

Exception is an unexpected problem that occurs at program run time. This problem might include condition such as division by zero, running out of memory space, array out of bonds, etc....

2 minutes read.

Preventing Object Copy in C++

C++ is an object-oriented programming language that provides the ability to create objects, define class and pass objects to functions. When passing an object to a function or returning an...

7 minutes read.

RTTI (Run-Time Type Information) in C++

In C++, RTTI or Run-Time Type Information reveals information about the data type of an object at runtime and only works with classes that have at least one virtual function....

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

C++ Date and Time

The date and time formats in C++ will be covered in this article. Because C++ lacks a proper date and time format, we must rely on the c language. The...

7 minutes read.

Destructor

Let’s discover the C++ destructor, virtual and pure virtual destructors, and when destructors are invoked and their rules in this lesson. Destructors : A member function that destroys an object is known as...

5 minutes read.

C++ Interfaces

The C++ programming language provides programmers with a variety of capabilities and functions. It also enables object-oriented programming, which is essential while working on a project. It will be simple...

7 minutes read.

New Operator in C++

Dynamic memory allocation in C++ means manually allocating the memory by the developer duing run-time. The dynamic memory is allocated in the heap section of the RAM, whereas the static...

3 minutes read.

C ++ Program: Alphabet Triangle and Number Triangle

Alphabet Triangle and Number Triangle An alphabet triangle is a triangle that typically looks like a pyramid or other triangles like an isosceles triangle, a right-angled triangle consisting of similar or...

4 minutes read.

Reverse function in C++

The function std::reverse() is included in the standard template library of C++. It takes in a beginning and ending iterator, reversing the order. To use the reverse statement, we need...

2 minutes read.

Armstrong number using for loop in C++

What is For Loop? A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently. The syntax that can be...

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

Program to arrange an array in alternate positive and negative numbers

Let’s say, there is given an array arr, arrange the array in such a way that every positive number is followed by a negative number. If there are extra positive...

4 minutes read.

C++ Memory Management

Memory management is a method of controlling computer memory and allocating memory space to applications to increase overall system performance. What is the purpose of memory management? Because the array contains homogeneous...

4 minutes read.