1. Home
C++ Tutorial

Explore C++ Tutorials: Exploring the World of C++ Programming

Discover comprehensive C++ tutorials designed for beginners and advanced programmers alike. Enhance your coding skills with step-by-step guides and practical examples.

  • 77 Lessons
  • 15 Hours
right-top-arrow
27

Abstract Class in C++: A Comprehensive Guide with Examples

Updated on 26/09/2024419 Views

Continuing on my journey of imparting knowledge about different concepts and constructs in the world of programming, in the tutorial, I will take you through the journey of abstract class in C++. By the end of this tutorial, you will have some understanding of C++ abstract base class, CPP abstract class. 

So, let’s begin the tutorial and walk you through abstract classes in C++ with examples, and more! 

What is Abstract Class in C++

An abstract class in C++ means that it is a basis for other classes in C++. It cannot be instantiated directly, this implies that you can not create objects of an abstract class. Contrary to this, it is employed to prescribe characteristics and behaviors that must be provided by child classes. I find this concept rather interesting because with the help of a successful reference, one can set up a clear framework for what a class is expected to do and yet leave it to the class to determine how it should get it done.

C++ Abstract Base Class

A C++ abstract base class is almost similar to other abstract classes. It is a base class where one or more member functions are made as pure virtual functions. A pure virtual function is declared by assigning ‘ 0 ’ to it in its declaration which looks like virtual void show() = 0;

This approach is made to shift any derived class to implement these functions thus signifying that specific behaviors are required to be adjusted by all the subclasses.

Abstract Class in C++ Syntax

To create an abstract class in C++, you use the class keyword followed by the class name and then at least one pure virtual function, however, there can be more than one. Here’s the basic syntax:

class AbstractClass {

public:

    virtual void aPureVirtualFunction() = 0; // Pure virtual function

    void aRegularFunction() {

        // Implementation of a regular function

    }

};

Here, AbstractClass cannot be instantiated, but it can be used as a base class for other classes that provide implementations for the pure virtual functions.

Abstract Class in C++ with Example

Consider the following example, where I illustrate how an abstract class can be utilized in a real-world scenario. Suppose we are developing a graphics application, and we want to define a general form for all shapes.

Example: 

Code: 

#include <iostream>

using namespace std;

// Abstract base class

class Shape {

public:

    // Pure virtual function providing interface framework.

    virtual void draw() = 0;

};

class Circle : public Shape {

public:

    void draw() {

        cout << "Drawing a Circle." << endl;

    }

};

class Square : public Shape {

public:

    void draw() {

        cout << "Drawing a Square." << endl;

    }

};

int main() {

    Shape *s1 = new Circle();

    Shape *s2 = new Square();

    s1->draw();

    s2->draw();

    delete s1;

    delete s2;

    return 0;

}

Output:

Drawing a Circle.
Drawing a Square.

In this example, the Shape class is an abstract class because it contains the pure virtual function draw(). The Square and Circle classes inherit from Shape and implement the draw method.

Abstract Class in C++ Program 

Let's take a deeper look at how an abstract class in C++ can be part of a larger program. Suppose we want to extend our graphics application to include a method for erasing shapes. We can enhance our abstract class with an additional pure virtual function:

Example: 

Code: 

#include <iostream>

using namespace std;

// Abstract base class

class Shape {

public:

    virtual void draw() = 0;

    virtual void erase() = 0; // Additional pure virtual function

};

class Circle : public Shape {

public:

    void draw() {

        cout << "Drawing a Circle." << endl;

    }

    void erase() {

        cout << "Erasing a Circle." << endl;

    }

};

class Square : public Shape {

public:

    void draw() {

        cout << "Drawing a Square." << endl;

    }

    void erase() {

        cout << "Erasing a Square." << endl;

    }

};

int main() {

    Shape *s1 = new Circle();

    Shape *s2 = new Square();

    s1->draw();

    s1->erase();

    s2->draw();

    s2->erase();

    delete s1;

    delete s2;

    return 0;

}

Output:

Drawing a Circle.
Erasing a Circle.
Drawing a Square.
Erasing a Square.

Here, both Circle and Square provide implementations for both the draw and erase methods, adhering to the interface defined by the Shape abstract class.

Important Things to Know about Abstract Class in C++

While using abstract classes in C++, or any other programming language for that matter, there are certain aspects or behaviors that one should be aware of. These concepts prove instrumental in making your code more solid and easily scalable. Here are some important things to know about abstract classes in C++:Here are some important things to know about abstract classes in C++:

1. Instantiation:

You cannot create instances of an abstract class directly. This is because abstract classes are incomplete by design; they have at least one pure virtual function without implementation. Attempting to instantiate an abstract class results in a compilation error. For instance:

class AbstractClass {

public:

    virtual void pureVirtualFunction() = 0; // Pure virtual function

};

int main() {

    // AbstractClass obj; // This will cause a compilation error

    return 0;

}

2. Inheritance and Implementation:

Abstract classes are primarily used as base classes. Any concrete class that derives from an abstract class must implement all its pure virtual functions, or else the derived class will also be considered abstract. This mechanism ensures that all derived classes follow a specified contract. For example:

class AbstractClass {

public:

    virtual void pureVirtualFunction() = 0;

};

class DerivedClass : public AbstractClass {

public:

    void pureVirtualFunction() override {

        // Implementation of the pure virtual function

        std::cout << "Implemented in DerivedClass" << std::endl;

    }

};

3. Member Functions:

While abstract classes cannot have instances, they can still have regular member functions (both static and non-static), member variables, and even constructors and destructors. These members will be part of the derived class unless overridden:

class AbstractClass {

public:

    virtual void pureVirtualFunction() = 0;

    

    void regularFunction() {

        std::cout << "This is a regular function." << std::endl;

    }

    AbstractClass() {

        std::cout << "Constructor of AbstractClass" << std::endl;

    }

    virtual ~AbstractClass() {

        std::cout << "Destructor of AbstractClass" << std::endl;

    }

};

4. Constructors and Destructors:

Constructor and destructor play a serious part in initializing and cleaning up derived classes though you cannot instantiate an abstract class. The constructor of the abstract class is called when a derived class is instantiated, and the destructor ensures that any allocated resources are properly released:The constructor of the abstract class is called when a derived class is instantiated, and the destructor ensures that any allocated resources are properly released:

class AbstractClass {

public:

    AbstractClass() {

        std::cout << "AbstractClass constructor called" << std::endl;

    }

    virtual ~AbstractClass() {

        std::cout << "AbstractClass destructor called" << std::endl;

    }

    virtual void pureVirtualFunction() = 0;

};

class DerivedClass : public AbstractClass {

public:

    DerivedClass() {

        std::cout << "DerivedClass constructor called" << std::endl;

    }

    ~DerivedClass() {

        std::cout << "DerivedClass destructor called" << std::endl;

    }

    void pureVirtualFunction() override {

        std::cout << "Implementation in DerivedClass" << std::endl;

    }

};

5. Multiple Inheritance:

An abstract class can inherit from other abstract or non-abstract classes. This is a powerful feature that allows the combination of multiple functionalities. When using multiple inheritance, a class can inherit from multiple base classes that define a set of required operations by using pure virtual functions:

class Base1 {

public:

    virtual void function1() = 0;

};

class Base2 {

public:

    virtual void function2() = 0;

};

class Derived : public Base1, public Base2 {

public:

    void function1() override {

        std::cout << "Implemented function1 from Base1" << std::endl;

    }

    void function2() override {

        std::cout << "Implemented function2 from Base2" << std::endl;

    }

};

6. Interface-like Behavior:

In many ways, abstract classes in C++ are used to define interfaces, similar to what you might find in other languages like Java or C#. An interface-like abstract class in C++ is a class where all the member functions are pure virtual. This pattern is especially useful in defining a common interface for a set of related classes:

class IShape {

public:

    virtual void draw() = 0;

    virtual void move(double x, double y) = 0;

    virtual ~IShape() {}

};

class Circle : public IShape {

private:

    double radius;

    double centerX, centerY;

public:

    Circle(double r, double x, double y) : radius(r), centerX(x), centerY(y) {}

    void draw() override {

        std::cout << "Drawing a Circle at (" << centerX << ", " << centerY << ") with radius " << radius << std::endl;

    }

    void move(double x, double y) override {

        centerX += x;

        centerY += y;

        std::cout << "Moved Circle to (" << centerX << ", " << centerY << ")" << std::endl;

    }

};

7. Abstract Class vs. Concrete Class:

It's important to distinguish between abstract and concrete classes. A concrete class is a class that can be instantiated, and it implements all its inherited pure virtual functions, unlike an abstract class. Designing with both abstract and concrete classes helps separate the what (interface) from the how (implementation).

Remember, understanding and implementing abstract classes can significantly improve your coding and architectural skills. For more on mastering these concepts, check out upGrad's software engineering courses!

Concluding Remarks

Hence, abstract classes are one of the crucial elements of C++ for achieving a high level of abstraction and design in the software. They make derived classes provide implementations for specific functions hence guaranteeing the users of the classes with a standard interface while at the same time allowing for variation in the actual implementation. In my opinion, you should employ abstract classes into your architecture in order to achieve tactful and comprehensive designs along with modularity.

To explore the fundamental concepts of software engineering in more detail and improve your C++ programming abilities, you may wish to attend upGrad’s software engineering programs.

FAQs

1. What is an abstract class in C++?

By definition, an abstract class in C++ is an unconstructable class and is usually employed as a superclass. It is an abstract class that is used when a class contains at least one pure virtual function.

2. How do you define an abstract class?

The concept of an abstract class can be declared using the syntax virtual ReturnType FunctionName() = 0;.

3. Can you instantiate an abstract class?

No, you cannot instantiate an abstract class directly.

4. What's the purpose of an abstract class?

Abstract classes provide the functionality of enforcing that derived classes contain certain functions along with the fact that they can contain functions on their own.

5. Can abstract classes have non-virtual functions?

Yes, abstract classes can have both virtual and non-virtual member functions.

6. Do abstract classes have constructors?

It is also very important to note that although an abstract class cannot be instantiated, it can however contain constructors as well as destructors that can be implemented in derived classes to instantiate and or perform any necessary cleaning up on created resources.

7. Why is abstract class used in C++?

Abstract classes are used in C++ to define interfaces and enforce a certain structure in derived classes.

8. Can abstract classes inherit from other classes?

Yes, abstract classes can inherit from other abstract or non-abstract classes, allowing for a combination of implemented and abstract functionalities.

Abhimita Debnath

Abhimita Debnath

Abhimita Debnath is one of the students in UpGrad Big Data Engineering program with BITS Pilani. She's a Senior Software Engineer in Infosys. She…Read More

Need Guidance? We're Here to Help!
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...