Abstract Classes in C++
Tags: cpp, computerscience, programming, abstractclass
Published: 2022-03-13 18:12:25

[Image Source](https://www.freepik.com/)

## Overview
Most of the time it happens that the user cannot implement all the functions in the base class because of a lack of information regarding its implementation. Such classes are called abstract classes.

## Scope of article
This article deals with the concept of inheritance and abstraction in C++
Also covers the concept of abstract class in C++ 
## Prerequisite

- Basic understanding of C/C++
- Understanding of conditional statements 

## Introduction 

Before we move forward to understand the abstract, lets develop some basic understanding regarding concepts like inheritance and abstraction.

### Inheritance

A class can derive features from another class. It is considered the most important concept in object-oriented programming.

Consider a scenario where a student got confused while purchasing a laptop. On attributes like processor, memory, graphic power, etc, he narrows it down to Dell and HP.

Then attributes of them would be:
```CPP
class HP {
    attributes:
    processor
    memory
    graphic power
};
class Dell{
    attributes:
    processor
    memory
    graphic power
};
```

However, this results in duplication of code along with it increase chances of error and data redundancy. 

So to avoid the above issues, we use the concept of inheritance where we can declare a base class “Computer” and inherit other classes from it.

```CPP
class Computer {
    attributes:
    processor
    memory
    graphic power
};
class HP : public Computer{
    // block of code
};
class Dell : public Computer{
    // block of code
};
```

### Abstraction
Data abstraction in simple words refers to the concept where the user is provided with essential information while hiding its implementation part. It only shows only limited information to the outside world.

We are all familiar with ATMs. Most of us has used it for performing some operations like cash withdrawal, retrieving statement, updating passbook, etc. But has anyone given a thought about the internal functioning of ATMs?

Similarly, programmers used data abstraction where it hides implementation details from the user and only provides essential information to make user life easier like happens in google search.

## Abstract class in C++
An abstract class contains at least one pure virtual function. The classes which inherit from an abstract class must define the pure virtual function.

Before we move further, let's understand the concept of abstract with the help of an example.

### Abstract class example
Suppose in your school project you are advised to device a calculator which returns the area of shape one put in. One would prefer to hardcode the same by making a separate function for calculating the area of different shapes within the same class.

Then class would look like this:

```CPP
class Shape{
    protected:
    int breadth;
    int length;
    public:
    int areaofsquare (int l){
        return l*l;
    }
    int areaofrectangle(int l, int b){
        return l*b;
    }
};
```

Though the given code will work perfectly, OOPs suggest one to remain close to real-world logic. Previously we have seen the example of HP and Dell which leads to duplication of code. Thus to avoid such situations it is advisable to make class Shape as parent class and make separate classes like rectangle, square, etc as an inherited class.

This practice makes code easy to maintain and if one plans to implement a new feature in the future then that can be done in child classes. To implement this one needs an abstract class.

As we have seen earlier that abstract class consists of at least one pure virtual function. The class which inherits the abstract class here classes of the square, rectangle, etc must define a virtual function, otherwise, child classes themselves become abstract classes.

Before we move forward and look into characteristics in abstract classes, it is better to develop some understanding related to virtual functions and pure virtual functions.

### Virtual functions
A virtual function is a member function that is declared in base class i.e. Shape class and is redefined in inherited classes like classes of the square, rectangle.

**Features of virtual functions**
- Virtual functions are mainly to achieve runtime polymorphism.
- These functions are defined in the base class using the ‘virtual’ keyword.
- These functions cannot be declared as static and their prototype should be the same in both the classes ie base and derived class.

### Pure virtual functions
They are nothing but virtual functions with no definition or logic, we only define them. They are declared to 0 at the time of declaration.

```CPP
// virtual function
class Shape{
    protected:
    int breadth;
    int length;
    public:
    virtual int areasquare(){
        printf("virtual function to calculate area of square");
    }
};
 
// pure virtual function
class Shape {
    protected:
    int breadth;
    int length;
    public:
    virtual int areasquare()=0;
}
```

Here it can be seen the difference in implementation of both virtual and pure virtual functions. 

Before we move forward and look at the characteristics of the abstract class, let us first understand the difference between virtual and pure virtual functions.

|                                    Virtual function                                    |                                                                    Pure virtual function                                                                    |
|:--------------------------------------------------------------------------------------:|:-----------------------------------------------------------------------------------------------------------------------------------------------------------:|
|      Member function of base<br>function which can be defined<br>in derived class      | It is also member function of the base class whose<br>only declaration is provided in the base class.<br>However, it must be redefined in the derived class |
|    Classes having virtual function<br>can be initiated i.e their objects can be made   |                                    Classes having pure virtual function<br>becomes abstract thus they cannot be initiated                                   |
| Syntax:-<br>virtual <func_type> <name>{<br>//write code here for virtual function<br>} |                                                         Syntax:-<br>virtual <func_type> name () =0;                                                         |
|         It is not mandatory to define virtual<br>functions in the derived class        |                 It becomes mandatory to redefine<br>pure virtual function in derived class otherwise<br>derived class also becomes abstract                 |

### Characteristics of abstract classes

They must possess at least one pure virtual function

```CPP
class 3DObjects{
    protected:
    int length;
    int breadth;
    int height;
    public:
    virtual int areaofobject()=0;
    virtual int volumeofobject()=0;
}
```

Abstract classes cannot be instantiated i.e user cannot create objects of abstract classes. However, pointers and references of abstract classes can be created.

```CPP
# include <iostream>
using namespace std;
 
class baseclass{
    protected:
    int x;
    public:
    virtual void printcommand()=0;
};
 
class derivedclass: public baseclass{
    private:
    int y;
    public:
    void printcommand(){
        cout<<" call from derived class" <<endl;
    }
};
 
int main (){
    baseclass* pointer_of_base = new drivedclass();
    pointer_of_base -> printcommand();
}
```

Classes that are inheriting from abstract classes must redefine all pure virtual functions.

### Why objects of abstract class cannot be made?
As classes are abstract it seems like they can attain multiple forms. Consider an example where you are asked to draw an animal however the instructor has not specified which animal to draw, then would lead to chaos. One can draw an animal if the instructor has specifically asked you to draw a cat, dog, elephant, etc.

Similar is the case with abstract class in C++, thus it is advisable not to create objects of the abstract class.

## Conclusion

In this article, we have looked into concepts of inheritance, abstraction, and dive into concepts of virtual and pure virtual functions and their comparison.
Along with we have extensively covered the concept of abstract classes in C++, how they are defined and some of their characteristics.

To further enhance your knowledge on abstract classes, the intuition behind how it works, and its usage in various competitive platforms like CodeChef with beautiful schematics, one may want to have a look at this curated article published on the [Abstract Classes in C++](https://www.scaler.com/topics/abstract-class-in-cpp/) on Scaler topics.