Introduction to C++ | Interfaces

C++ Interfaces

In C++, an interface is a class that has only pure virtual functions and no data members. It defines a contract that derived classes must follow. Interfaces are used to achieve abstraction and ensure that certain methods are implemented in the derived classes.

What is an Interface?

An interface is essentially an abstract class where:

Syntax of an Interface

Syntax


        class InterfaceName {
        public:
            virtual void functionName() = 0; // Pure virtual function
            virtual ~InterfaceName() {}     // Virtual destructor (optional, but recommended)
        };
                    

Example of Interfaces in C++

Here’s an example of using interfaces in C++:

Code Example


        #include <iostream>
        using namespace std;
        
        // Interface
        class Shape {
        public:
            virtual void draw() = 0; // Pure virtual function
            virtual double calculateArea() = 0; // Pure virtual function
        
            virtual ~Shape() {} // Virtual destructor
        };
        
        // Derived class 1
        class Circle : public Shape {
        private:
            double radius;
        
        public:
            Circle(double r) : radius(r) {}
        
            void draw() override {
                cout << "Drawing Circle" << endl;
            }
        
            double calculateArea() override {
                return 3.14 * radius * radius;
            }
        };
        
        // Derived class 2
        class Rectangle : public Shape {
        private:
            double length, width;
        
        public:
            Rectangle(double l, double w) : length(l), width(w) {}
        
            void draw() override {
                cout << "Drawing Rectangle" << endl;
            }
        
            double calculateArea() override {
                return length * width;
            }
        };
        
        int main() {
            Shape* shape1 = new Circle(5.0);
            Shape* shape2 = new Rectangle(4.0, 6.0);
        
            shape1->draw();
            cout << "Area of Circle: " << shape1->calculateArea() << endl;
        
            shape2->draw();
            cout << "Area of Rectangle: " << shape2->calculateArea() << endl;
        
            // Free memory
            delete shape1;
            delete shape2;
        
            return 0;
        }
                    

Output

Drawing Circle
Area of Circle: 78.5
Drawing Rectangle
Area of Rectangle: 24

Key Points About Interfaces

Advantages of Using Interfaces

Pro Tip:

💡 Pro Tip

Use interfaces to define behaviors that are common across multiple unrelated classes. This ensures a consistent contract while keeping implementations flexible.