In C++, an abstract class is a class that cannot be instantiated directly and is designed to be used as a base class for other classes. It contains at least one pure virtual function, which is a virtual function that has no implementation in the abstract class.
An abstract class is created using the abstract
keyword before the class name or by declaring at least one pure virtual function in the class. When a class contains at least one pure virtual function, it becomes an abstract class and cannot be instantiated.
The purpose of an abstract class is to provide a common interface for a set of related classes. The derived classes must implement the pure virtual function(s) of the abstract class to provide their own implementation. This ensures that the derived classes have a common interface, while allowing them to provide their own implementation of the abstract functionality.
An example of an abstract class in C++ is shown below:
class Shape {
public:
virtual void draw() = 0; // pure virtual function
};
In this example, the Shape
class is an abstract class because it contains a pure virtual function draw()
. This class provides a common interface for all shapes, but it does not provide any implementation of the draw()
function. The derived classes, such as Circle
or Square
, must implement the draw()
function to provide their own implementation of drawing a shape.
Comments
Post a Comment