• Articles
  • Tutorials
  • Interview Questions

Abstract Class in C++ with Examples

Abstract Class in C++ with Examples

In this blog, we will discuss everything about the concept of an abstract class in C++. First, we will discuss the meaning of an abstract class and then the pure virtual function in C++. Afterward, we will see the practical implementation of the abstract class in C++ and the limitations of this type of class, along with the real-life applications of abstraction. 

Table of Contents

Check out our YouTube video on C programming language for absolute beginners!

Video Thumbnail

What is an Abstract Class in C++?

An abstract class in C++ refers to a class with at least one pure virtual function inside it. This means the abstract class must have at least one function that is only declared and not defined inside this class. In other words, an abstract class doesn’t know what to implement in the method, but it knows that the method will exist in its derived class. It is important to note that an abstract class is designed to be used as a base class, meaning that there must be an inherited class containing the definition of the pure virtual function declared inside the base class. If the derived or inherited class does not define the pure virtual function, the compiler will not give an error, but the inherited class will also become an abstract class like the base class.

The syntax of an abstract class in C++ is as follows:

class className 
{
public:
virtual return_type fun_name()=0;
};

An abstract class can also be defined using the keyword ‘struct’. The difference is that struct members are public by default, whereas class members are private. 

The syntax for an abstract class with struct will be as follows:

struct className
{
    virtual return_type fun_name()=0;
}

We cannot create an object. We can still create a constructor for the abstract class. To call the constructor, we use constructor chaining. The basic purpose of using abstract classes is to maintain a uniform interface inside all derived classes. This means if there are two classes inheriting from an abstract class, both classes should provide the implementation of a pure virtual function; otherwise, they will become abstract. It ensures that the necessary function is implemented in every class.

Enroll in Intellipaat’s C Programming Certification Course to become an expert.

What is a Pure Virtual Function?

As discussed in the above section, a pure virtual function does not have a definition in the class it has been declared in. In other words, it is a virtual function without a definition. It is a “do nothing” function. It only provides the template in the base class, and its implementation is provided in the derived class. A pure virtual function cannot be global or static. It helps us achieve polymorphism in our programs, and this concept comes under run-time polymorphism. The syntax for a pure virtual function is as follows:

virtual return_type fun_name()=0;

Here, return_type is the type of data that the function will return, i.e., int, float, etc., and void if it does not return anything. ‘virtual’ is a keyword, and =0 is a pure specifier. The following example shows the simple implementation of a pure virtual function:

#include <iostream>
using namespace std;
//The abstract class
class parent
{
    public:
    // Pure virtual function
    virtual void print() = 0;
};
class child: public parent
{
    public:
    void print(){
        cout << "Inside Child Class\n";
    }
};
int main()
{
    // Pointer and Reference and basic derived class usage
    child c1;
    c1.print();
   parent *p1;
    child c2;
    p1 = &c2;
    p1->print();
    return 0;
}

We have created object ‘c1’ of the derived class and accessed the print() function through that object. Then, we created the pointer ‘p1’ to the parent class, which stores the address of the object of the child class. This pointer then refers to the print() method and implements this method. The output of this program will look like the following:

Inside Child Class

Inside Child Class

Check out these C++ Interview Questions and Answers to ace your CPP programming interview.

Get 100% Hike!

Master Most in Demand Skills Now!

Example of an Abstract Class in C++

An abstract class can contain more than one pure virtual function, and all the classes that derive it must define those pure virtual functions inside them. For example, consider that we have a class named Shape, and it is inherited by the classes, i.e., Circle and Square. Both of these shapes have a perimeter and an area. If we create the two pure virtual functions for area and perimeter, then both the Circle and Square classes must implement these functions inside their bodies. The code for this will be as follows:

// C++ program to calculate the area and perimeter of a square and a circle

#include <iostream>
using namespace std;
// Abstract class
class Shape {
   public:
    float x;
   public:
    void getDimensions() {
        cin >> x;
    }
    // pure virtual Functions
    virtual float area() = 0;
    virtual float perimeter()=0;
};
// Derived class
class Square : public Shape {
   public:
    float area() {
        return x * x;
    }
    float perimeter(){
        return 4*x;
    }
};
// Derived class
class Circle : public Shape {
   public:
    float area() {
        return 3.14 * x * x;
    }
    float perimeter(){
        return 2*3.14*x;
    }
};
int main() {
    Square square;
    Circle circle;
    cout << "Enter the length of the square: ";
    square.getDimensions();
    cout << "Area of Square: " << square.area() << endl;
    cout<<"Perimeter of Square: "<<square.perimeter()<<endl;
    cout << "\nEnter the radius of the circle: ";
    circle.getDimensions();
    cout << "Area of circle: " << circle.area() << endl;
    cout<<"Perimeter of Circle: "<<square.perimeter()<<endl;
    return 0;
}

Here, we are calculating the area and perimeter of a square and a circle. Both the derived classes provide the implementation of pure virtual functions, i.e., area() and perimeter(). It should be noted that if we skip defining even one of these pure virtual functions in one class, the program will raise an error. This program will give the following output:

Enter the length of the square: 4

Area of Square: 16

Perimeter of Square: 16

Enter the radius of the circle: 3

Area of circle: 28.26

Perimeter of Circle: 16

Check out these Top 20 C++ Project Ideas to create a project and become an expert in C++. 

Restrictions of an Abstract Class

When you pass parameters by “copy” in C++, the function receives a copy of the provided argument. This means that the object is duplicated, and the function works with its independent copy of the data. In the context of abstract classes, passing an object of an abstract class type by copy is problematic because abstract classes cannot be instantiated.

Since abstract classes often have pure virtual functions, they are incomplete and cannot be instantiated on their own. Therefore, creating a copy of an abstract class object would be attempting to duplicate an incomplete object, which is not allowed in C++. The compiler would raise an error if you try to pass an abstract class object by copy.

To work with abstract classes, it is common to pass parameters by reference or pointer. This way, you are dealing with the original object (or a reference to it) rather than trying to make copies of incomplete objects. Using references or pointers allows you to work with the polymorphic behavior of abstract classes, enabling the invocation of overridden functions in derived classes through the base class reference or pointer.

Abstract classes can contain both pure virtual functions and concrete (implemented) methods. However, if a class contains at least one pure virtual function, it becomes an abstract class, and objects of such classes cannot be instantiated.

Check out these frequently asked C++ programs to enhance your knowledge.

Real-Life Applications of Abstraction

Abstraction is like hiding data. In real life, we see a lot of examples where unnecessary data is hidden from the outside world, for example, a TV remote. We press different buttons for different outcomes, but we are not aware of the inner mechanism of that remote. Similarly, there are a lot of gadgets that we use, and we don’t know what happens behind the operations that they perform. This is done to protect important data from unauthorized access.

Conclusion

In C++, the need for an abstract type of class arises to provide a common interface with declared but undefined methods, allowing derived classes to implement their own versions of these methods. This concept ensures a consistent structure across different classes while allowing for customization in individual implementations. This type of class is important for promoting modularity, code organization, and polymorphism in object-oriented programming.

Course Schedule

Name Date Details
Python Course 14 Dec 2024(Sat-Sun) Weekend Batch View Details
21 Dec 2024(Sat-Sun) Weekend Batch
28 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration.