Abstract Class In C++ - C++ Programming Tutorial
C++ Course / Data Structures / Abstract Class In C++

Abstract Class In C++

BLUF: Mastering Abstract Class In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Abstract Class In C++

C++ is renowned for its efficiency. Learn how Abstract Class In C++ enables low-level control and high-performance computing in the tutorial below.

In C++, an abstract class is required to contain at least one pure virtual function. Another approach is to include a function without an implementation. Descendants of the abstract class are obligated to define the pure virtual function; otherwise, the subclass would also become an abstract class.

In C++, abstract classes serve to represent general concepts from which specific classes can be inherited. Instances of the abstract class cannot be created directly. Nevertheless, abstract class types can be pointed to or referenced. When designing an abstract class, it is essential to include at least one pure virtual function. A virtual function with no implementation is defined using the pure specifier syntax (= 0).

Consider the instance of the virtual method. While the main goal of the class is to offer fundamental operations for geometric figures, items categorized as shapes are excessively broad to be particularly useful. Hence, the shape is an ideal contender for an abstract class:

Syntax

It has the following syntax:

Example

Class class_name //abstract class  

{  

//data members                                                          

public:  

//pure virtual function  

/* Other members */  

};

C++ Abstract Class Example

Let's consider a scenario to demonstrate the concept of an abstract class in the C++ programming language.

Example

Example

#include <iostream>

using namespace std;   //using standard namespace

// Abstract base class

class Car {  

public:   //Access Modifier

    // Pure virtual function

    virtual void startEngine() = 0;

    // Concrete function

    void fuelType() {

        cout << "Most cars use Petrol or Diesel." << endl;

    }

};

// Derived class: Mahindra

class BMW : public Car {

public:

    void startEngine() override {

        cout << "Starting engine of BMW..." << endl;

    }

};

// Derived class: Audi

class Audi : public Car {

public:

    void startEngine() override {

        cout << "Starting engine of Audi..." << endl;

    }

};

int main() {   //main function

   

    BMW bmwCar;

    Audi audiCar;

    Car* carPtr;

    carPtr = &bmwCar;

    carPtr->startEngine();  

    carPtr->fuelType(); 

    carPtr = &audiCar;

    carPtr->startEngine(); 

    carPtr->fuelType();

    return 0;

}

Output:

Output

Starting engine of BMW...

Most cars use Petrol or Diesel.

Starting engine of Audi...

Most cars use Petrol or Diesel.

Explanation:

In this instance, we illustrate the idea of abstract classes and dynamic polymorphism. Following this, the abstract superclass Vehicle includes an abstract method initiateEngine and a non-abstract method fuelType. The subclasses Mercedes and Lexus provide customized implementations for the initiateEngine method. Within the main function, a superclass pointer is employed to invoke overridden methods at runtime, effectively displaying polymorphic behavior.

Characteristics of Abstract Class in C++

There are several characteristics of an abstract class in C++. Some of the characteristics are as follows:

  • Although the Abstract class type cannot be created from scratch, it can have pointers and references made to it.
  • A pure virtual function can exist in an abstract class in addition to regular functions and variables. Upcasting is the main usage of abstract classes, which lets derived classes access their interface. Classes that descended from an abstract class must implement all pure virtues.
  • We cannot instantiate an abstract class because it consists of a minimum of one pure virtual function, which stops it from creating an instance of the abstract class.
  • An abstract class can have virtual and concrete methods where we need to define a concrete method as we do in other normal classes, and for a virtual method, we just need to declare them using the keyword 'virtual', and there is no need to define such a method.
  • An abstract class can only be used as a parent class, which can be used for creating the child classes, and these child classes are further used for implementing the pure virtual functions.
  • An abstract class can have data members as other normal classes have. Only the difference is that in an abstract class, we have the data members either private or protected so as to save them from any direct access outside of the class.
  • Restrictions of an Abstract Class in C++

There are several limitations of an abstract class in C++. Some of the limitations are as follows:

  • Must Contain at least one pure virtual function: In C++, a class becomes abstract only when it contains at least one pure virtual function.
  • Can have constructors and destructors: Although they can't be instantiated, abstract classes contain constructors and destructors to support proper initialization and cleanup used through derived classes.
  • Cannot be Instantiated: We cannot make objects directly from an abstract class in C++.
  • Derived classes must override all pure virtual functions: A derived class should provide implementations for all inherited pure virtual functions. Otherwise, it also becomes abstract and cannot be instantiated in C++.
  • Can we make an object of an abstract class?

No, instantiation of an object from an abstract class is not possible due to the nature of abstract classes which cannot be directly instantiated. When defining a pure virtual function, memory allocation is reserved for it without assigning any specific address to it. Consequently, attempting to create an object from an abstract class is prohibited by the compiler. Therefore, we can only define the abstract class without the ability to create instances of it.

How is important Abstraction in Daily Life?

The automated teller machine (ATM) serves as an illustration of abstraction in our daily routines. Despite our frequent utilization of ATMs for activities such as withdrawing cash, transferring money, obtaining mini-statements, and more, we are restricted from accessing the internal workings of the ATM. Safeguarding methods like data abstraction play a crucial role in averting unauthorized entry to sensitive data.

Difference between Abstract Class and Interface in C++

There exist multiple distinctions between abstract classes and interfaces in C++. Some key variances include:

Interface Abstract class
An interface can only inherit from another interface. With the Extended keyword, an abstract class can enforce an interface and inherit from another class.
Use of the implements keyword is required in order to implement an interface. Use the extends keyword to inherit from an abstract class.

Example of an Abstract Class

Let's consider another instance to demonstrate the concept of an abstract class in the C++ programming language.

Example

Example

#include <iostream>

using namespace std;   // Using standard namespace

class Shape {

public:   //access modifier

    // Function to set width

    void width(int w) {

        shape_width = w;

    }

    // Function to set height

    void height(int h) {

        shape_height = h;

    }

    // Function to calculate the area of square

    int areaOfSquare(int s) {

        return s * s;

    }

    // Function to calculate the  area of rectangle

    int areaOfRectangle() {

        return shape_width * shape_height;

    }

protected:

    int shape_width;

    int shape_height;

};

int main() {    //main function

    Shape R;

    R.width(5);

    R.height(10);

    cout << "The area of rectangle is: " << R.areaOfRectangle() << endl;

    cout << "The area of square with side 4 is: " << R.areaOfSquare(4) << endl;

    return 0;

}

Output:

Output

The area of rectangle is: 50

The area of square with side 4 is: 16

Explanation:

In this illustration, we establish a Shape class containing methods for computing the area of a rectangle and a square. Subsequently, the width and height methods are employed to define the dimensions of the rectangle, followed by the utilization of areaOfRectangle to determine its area. For the square, the areaOfSquare method accepts a side length as a parameter and provides the area of the square. Within the main function, both methods are showcased using suitable values.

C++ Abstract Classes MCQs

1) Which of the following options is correct about abstract classes in C++?

  • Any C++ class is called an Abstract class.
  • A class used as a base class with at least one pure virtual function is called an Abstract class.
  • A class used as a base class with at least one virtual function is called an Abstract class.
  • A class from which any class is derived is called an Abstract class.

An

  • utilized as a base class with a minimum of one pure virtual function is referred to as an Abstract class.

2) Which of the following options is correct about abstract classes in C++?

  • Any function in a class is called a Pure virtual function.
  • Any virtual method defined in the parent class is called a Pure Virtual Function.
  • A function having no definition in the parent class is called a Pure Virtual Function.
  • Any virtual function declared in the parent class is called a Pure Virtual Function.

A function lacking a definition in the base class is referred to as a Pure Virtual Function.

3) Identify the correct syntax to define a pure virtual function in C++?

  • virtual return_type f1 = 0;
  • pure virtual return_type f1;
  • virtual return_type f1 pure;
  • virtual return_type f1;

4) Which of the following classes can be used to design a parent or base class?

  • Derived class
  • Base/Parent class
  • Both a & b
  • Abstract class

5) Where do we make use of an abstract class in C++?

  • Derived class only
  • Parent class only
  • Virtual class
  • None of the above

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience