Search for Courses, Topics

Abstract Classes in C++

Learn about abstract class in C++.

27 Sep 2021-7 mins read
quiz
Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Overview

Abstract classes in C++ refer to the classes that contain at least one pure virtual function and these classes cannot be instantiated. Such classes are mainly used for Upcasting, which means that its derived classes can use its interface.

Scope

  • This article covers the concept of Inheritance and Abstraction in C++
  • It covers the concept of abstract classes in C++

Introduction

When you are writing Object Oriented Code one of your main objectives is to structure code in such a way that it is easy to relate with real life. There are two important concepts you need to be familiar with, they are Inheritance and Abstraction.

Let’s look at these, one by one.

Inheritance

You must have seen some families where all the members of the same family have the same eye color. Ever wondered why? Well, it is because of inheritance. It is a biological concept that tells us that children get (inherit) some of the features (like eye color, hairstyle) from their parents.

Abstract Class in C++ - Inheritance

But what does this has to do with this article? Well, in Object-Oriented Programming we use this concept extensively. We create Base Class(parent class) and Derived Class(Child class). Here also the derived class inherits the features (in this case they are methods and properties) of their base class.

Abstraction

Let’s say you are driving a car. When you increase the speed do you ever think about what is happening inside the engine? Or when you shift gears do you know how the gearbox works. A better question would be do you even need to know?

The same goes for many things we do daily. When we switch on the TV we just press a button from the remote trusting the remote to do its job and we don’t care how it does what it does.

This is called abstraction.

Abstraction takes away the implementation details and gives the user a simple way to interact with things.

Another example would be, when you go to Google, you are presented with a simple box to type your query and a cute little search icon. You don’t need to worry about how Google is giving you all the results.

Another way to frame this would be, with the help of abstraction, a programmer hides all the implementation details that the user does not need to see.

Abstract Class in C++

An abstract class is a class that contains at least one pure virtual function and these classes cannot be instantiated.

Abstract Classes came from the idea of abstraction. Before we dive into technicalities let’s first consider a scenario where you might use this concept.

Abstract Class Example

Let’s say we are making a calculator which returns the perimeter of the shape we put in. Think of what kind of code you would write for such a calculator. You might start with some initial shapes and hardcode the perimeter by making separate functions inside the Shape class.

The class might look something like this –

class Shape {
  public:
    void width(int w) {
        shape_width = w;
    }
    void height(int h) {
      shape_height = h;
    }
    int perimeterOfSquare(int s) {
      return 4 * s;
    }
    int perimeterOfRectange(int l, int b) {
      return 2 * (l + b);
    }
    
  protected:
    int shape_width;
    int shape_height;
};

This will work but OOP suggests that we should try to stay close to real-world logic. So, what we can do is, make a class Shape as a parent class and then make separate classes like Square, Rectangle as child class. This will make the code easier to maintain and if you plan to add anything new in the future then you can add that in the child class. To implement this feature we need to use Abstract Classes. Abstract classes in C++ need to have at least one pure virtual function in a class. The classes that inherit the abstract class must provide a definition for the pure virtual function, else the subclass will itself become an abstract class.

Restrictions on Abstract Classes

There are some restrictions on abstract class in C++.

Abstract classes cannot be used for the following –

  • Variables or member data
  • Argument types
  • Function return types
  • Types of explicit conversions.

The constructors of the abstract class have the ability to call other member functions but if they directly or indirectly call a pure virtual function then the result is undefined.

But wait! What is a pure virtual function anyway?

To understand the pure virtual function, first, let’s understand virtual functions.

A virtual function is a member function that is declared within a base class and is redefined by the derived class.

A pure virtual function (or abstract function) is a virtual function with no definition/logic. It is declared by assigning 0 at the time of declaration.

Let’s take a look at an example that will make things clear.

#include<iostream>
using namespace std;

class Shape {
  public:
    virtual int perimeter() = 0;
    void width(int w) {
      shape_width = w;
    }
    void height(int h) {
      shape_height = h;
    }
  
  protected:
    int shape_width;
    int shape_height;
};

class Rectangle: public Shape {
  public: 
    int perimeter() {
      return (2 * (shape_width + shape_height));
    }
};

class Square: public Shape {
  public: 
    int perimeter() {
      return (4 * shape_width);
    }
};

int main() {
  Rectangle R;
  Square S;

  R.width(10);
  R.height(5);
  S.width(10);

  cout << "Perimeter of Rectangle: " << R.perimeter() << endl;
  cout << "Perimeter of Square: " << S.perimeter() << endl;
  return 0;
}

Output –

Perimeter of Rectangle : 30
Perimeter of Square: 40

In the above code, you can see that the function perimeter() is a pure virtual function, the “virtual” keyword is used and it is assigned a value of 0.

In the derived classes, Rectangle and Shape redefine the pure virtual function.

Characteristics of Abstract Class in C++

  1. Abstract Classes must have a pure virtual function.
virtual int perimeter() = 0;
  1. Abstract Classes cannot be instantiated, but pointers and references of Abstract Class type can be created. You cannot create an object of an abstract class. Here is an example for a pointer to an abstract class.
#include<iostream>
using namespace std;

class Base {
  public:
    virtual void print() = 0;
};

class Derived: public Base {
  public: 
    void print() {
      cout << "This is from the derived class \n";
    }
};

int main(void) {
  Base* basePointer = new Derived();
  basePointer -> print();
  return 0;
}

Output –

This is from the derived class
  1. Abstract Classes are mainly used for Upcasting, which means its derived classes can use its interface.
  2. Classes that inherit the Abstract Class must implement all pure virtual functions. If they do not do so, then those classes will also be treated as abstract classes.

Why Can’t We Make an Abstract Class Object?

Abstract classes in C++ cannot be instantiated because they are “abstract”, it’s like someone is telling you to draw an animal without telling which specific animal. You can only draw if the person asks you to draw a cat, dog, etc. but an animal is abstract.

The same is the case with abstract classes in C++, so we can’t create objects but we can create a pointer of an abstract class.

Conclusion

Through this article you now know:

  • What is Abstract Class in C++?
  • What is Inheritance?
  • What is Abstraction?
  • How to create and work with Abstract Class in C++?
  • What are virtual functions and what is the difference between virtual and pure virtual functions?

That’s all for now folks!

Thanks for reading.

Challenge Time!
quiz Time to test your skills and win rewards! Note: Rewards will be credited after the next product update.