Abstract Base Class: An abstract base class is a class that cannot be instantiated and is meant to be subclassed. It usually contains one or more pure virtual functions, which are declared with the
virtual
keyword and set to 0, indicating that they must be overridden in derived classes. Abstract base classes are used to define a common interface that derived classes must implement.Here's an example:
cppclass Shape { public: virtual void draw() = 0; // Pure virtual function }; class Circle : public Shape { public: void draw() override { // Implement the drawing logic for a circle } }; class Square : public Shape { public: void draw() override { // Implement the drawing logic for a square } };In this example,
Shape
is an abstract base class with a pure virtual functiondraw
. It cannot be instantiated on its own, butCircle
andSquare
are derived classes that must provide an implementation for thedraw
function.
By using virtual functions and base classes, C++ allows us to create a hierarchy of classes with polymorphic behavior, making it easier to work with different types of objects in a unified way.
No comments:
Post a Comment