What is a C++ abstract class?

By definition, an abstract class in C++ is a class that has at least one pure virtual function (i.e., a function that has no definition). The classes inheriting the abstract class must provide a definition for the pure virtual function; otherwise, the subclass would become an abstract class itself.

Abstract classes are essential to providing an abstraction to the code to make it reusable and extendable. For example, a Vehicle parent class with Truck and Motorbike inheriting from it is an abstraction that easily allows more vehicles to be added. However, even though all vehicles have wheels, not all vehicles have the same number of wheels – this is where a pure virtual function is needed.

Consider an example of a Shape base class with sub-classes (Triangle and Rectangle)​ that inherit the Shape class.

svg viewer

Now, suppose we need a function to return the area of a shape. The function will be declared in the Shape class; however, it cannot be defined there as the formula for the area is different for each shape. A non-specific shape does not have an area, but rectangles and triangles do. Therefore​, the pure virtual function for calculating​ area will be implemented differently by each sub-class.

The following code snippet implements the abstract Shape class along with its sub-classes:

#include <iostream>
using namespace std;
class Shape {
public:
virtual int Area() = 0; // Pure virtual function is declared as follows.
// Function to set width.
void setWidth(int w) {
width = w;
}
// Function to set height.
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
// A rectangle is a shape; it inherits shape.
class Rectangle: public Shape {
public:
// The implementation for Area is specific to a rectangle.
int Area() {
return (width * height);
}
};
// A triangle is a shape too; it inherits shape.
class Triangle: public Shape {
public:
// Triangle uses the same Area function but implements it to
// return the area of a triangle.
int Area() {
return (width * height)/2;
}
};
int main() {
Rectangle R;
Triangle T;
R.setWidth(5);
R.setHeight(10);
T.setWidth(20);
T.setHeight(8);
cout << "The area of the rectangle is: " << R.Area() << endl;
cout << "The area of the triangle is: " << T.Area() << endl;
}

Note: The return type of the virtual function must be consistent throughout all of its implementing classes.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved