DEV Community

Cover image for Abstract Classes in C++
supernerdd007
supernerdd007

Posted on

Abstract Classes in C++

Image Source

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:

class HP {
    attributes:
    processor
    memory
    graphic power
};
class Dell{
    attributes:
    processor
    memory
    graphic power
};
Enter fullscreen mode Exit fullscreen mode

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.

class Computer {
    attributes:
    processor
    memory
    graphic power
};
class HP : public Computer{
    // block of code
};
class Dell : public Computer{
    // block of code
};
Enter fullscreen mode Exit fullscreen mode

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:

class Shape{
    protected:
    int breadth;
    int length;
    public:
    int areaofsquare (int l){
        return l*l;
    }
    int areaofrectangle(int l, int b){
        return l*b;
    }
};
Enter fullscreen mode Exit fullscreen mode

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.

// 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;
}
Enter fullscreen mode Exit fullscreen mode

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

Characteristics of abstract classes

They must possess at least one pure virtual function

class 3DObjects{
    protected:
    int length;
    int breadth;
    int height;
    public:
    virtual int areaofobject()=0;
    virtual int volumeofobject()=0;
}
Enter fullscreen mode Exit fullscreen mode

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

# 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();
}
Enter fullscreen mode Exit fullscreen mode

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++ on Scaler topics.

Top comments (0)