What is Interface Class?

In C++, an interface class is a class that defines a contract or a set of pure virtual functions without any member variables. It serves as a blueprint for other classes to inherit from and implement the required functionality. An interface class provides a way to achieve abstraction and create a common interface for related classes.

Here’s an example of an interface class in C++:

#include <iostream>

// Interface class
class Shape {
public:
    virtual void draw() const = 0; // Pure virtual function
    virtual double area() const = 0; // Pure virtual function
};

// Concrete class implementing the Shape interface
class Rectangle : public Shape {
public:
    void draw() const override {
        std::cout << "Drawing a rectangle." << std::endl;
    }

    double area() const override {
        return length * width;
    }

    void setDimensions(double len, double wid) {
        length = len;
        width = wid;
    }

private:
    double length;
    double width;
};

// Concrete class implementing the Shape interface
class Circle : public Shape {
public:
    void draw() const override {
        std::cout << "Drawing a circle." << std::endl;
    }

    double area() const override {
        return 3.14159 * radius * radius;
    }

    void setRadius(double rad) {
        radius = rad;
    }

private:
    double radius;
};

int main() {
    Rectangle rect;
    rect.setDimensions(5.0, 3.0);
    rect.draw();
    std::cout << "Area of the rectangle: " << rect.area() << std::endl;

    Circle circle;
    circle.setRadius(2.5);
    circle.draw();
    std::cout << "Area of the circle: " << circle.area() << std::endl;

    return 0;
}

In the example above, the Shape class is an interface class that declares two pure virtual functions: draw() and area(). Any class inheriting from Shape must implement these functions. The Rectangle and Circle classes inherit from Shape and provide their own implementations for the pure virtual functions. The main() function demonstrates the usage of the Shape interface by creating objects of Rectangle and Circle and calling their respective functions.

Note that an interface class in C++ can only contain pure virtual functions and does not have any member variables. It is intended to define a common interface for derived classes and cannot be instantiated directly.

Leave a Reply

Your email address will not be published. Required fields are marked *