C++ Abstract Classes and Pure Virtual Functions

A class that cannot be instantiated in C++ is called an abstract class. Usually, it serves as the base class for defining an interface that derived classes must implement. A virtual function that is declared in an abstract class but has no implementation is referred to as a pure virtual function. To provide an implementation for the pure virtual function, derived classes are necessary.

Syntax:

virtual void myFunction() = 0;

Output:

The integer value is: 5
The double value is: 3.14

Example:

#include <iostream>

class Shape {
public:
    virtual void draw() = 0;
    virtual ~Shape() {}
};

class Circle : public Shape {
public:
    void draw() {
        std::cout << "Drawing a circle." << std::endl;
    }
};

class Square : public Shape {
public:
    void draw() {
        std::cout << "Drawing a square." << std::endl;
    }
};

int main() {
    Circle c;
    Square s;

    Shape *shapes[] = {&c, &s};
    for (int i = 0; i < 2; ++i) {
        shapes[i]->draw();
    }

    return 0;
}

Output:

Drawing a circle.
Drawing a square.

We have an abstract class called Shape with the pure virtual function draw in this programme.(). As a result, any class that derives from Shape must implement draw() in order to avoid becoming an abstract class as well.

The following two classes are Circle and Square, both of which derive from Shape. Each one offers a draw implementation.().

We construct instances of the Circle and Square and add them to an array of Shape references in the main() function. The draw() method is then called on each object in the array, invoking the appropriate implementation of draw() for each shape.