Followers

Thursday, November 9, 2023

Concept of Abstract Base Class in C++


 

  1. 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:

    cpp
    class 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 function draw. It cannot be instantiated on its own, but Circle and Square are derived classes that must provide an implementation for the draw 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