Declare an Interface in C++



The C++ interfaces are implemented using abstract classes and these abstract classes should not be confused with data abstraction which is a concept of keeping implementation details separate from associated data.

A class is made abstract by declaring at least one of its functions as a pure virtual function. A pure virtual function is specified by placing "= 0" in its declaration as follows :

class Box {
   public:
      // pure virtual function
      virtual double getVolume() = 0;
   private:
      double length; // Length of a box
      double breadth; // Breadth of a box
      double height; // Height of a box
};

The purpose of an abstract class (often referred to as an ABC) is to provide an appropriate base class from which other classes can inherit. Abstract classes cannot be used to instantiate objects and serve only as an interface. Attempting to instantiate an object of an abstract class causes a compilation error.

Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of the virtual functions, which means that it supports the interface declared by the ABC. Failure to override a pure virtual function in a derived class, then attempting to instantiate objects of that class, is a compilation error.

Classes that can be used to instantiate objects are called concrete classes.

Example

Consider the following example where parent class provides an interface to the base class to implement a function called getArea() :

#include <iostream>
using namespace std;
class Shape { // Base class
   public:
      // pure virtual function providing interface framework.
      virtual int getArea() = 0;
      void setWidth(int w) {
         width = w;
      }

      void setHeight(int h) {
         height = h;
      }

   protected:
      int width;
      int height;
};

class Rectangle: public Shape { // Derived classes
   public:
      int getArea() {
         return (width * height);
      }
};

class Triangle: public Shape {
   public:
      int getArea() {
         return (width * height)/2;
      }
};

int main(void) {
   Rectangle Rect;
   Triangle Tri;

   Rect.setWidth(5);
   Rect.setHeight(7);

   // Print the area of the object.
   cout << "Total Rectangle area: " << Rect.getArea() << endl;

   Tri.setWidth(5);
   Tri.setHeight(7);

   // Print the area of the object.
   cout << "Total Triangle area: " << Tri.getArea() << endl;
   return 0;
}

The above code produces the following result:

Total Rectangle area: 35
Total Triangle area: 17

You can see how an abstract class defined an interface in terms of getArea() and two other classes implemented the same function but with a different algorithm to calculate the area specific to the shape.

Design Strategy

An object-oriented system might use an abstract base class to provide a common and standardized interface appropriate for all the external applications. Then, through inheritance from that abstract base class, derived classes are formed that operate similarly.

The capabilities (i.e., the public functions) offered by the external applications are provided as pure virtual functions in the abstract base class. The implementations of these pure virtual functions are provided in the derived classes that correspond to the specific types of the application.

This architecture also allows new applications to be added to a system easily, even after the system has been defined.

In C++, interfaces are declared using abstract classes. These abstract classes contain at least one pure virtual function. An interface provides a way to achieve abstraction and multiple inheritance.

To create an interface in C++, we define a class with only pure virtual functions and a virtual destructor. This allows derived classes to implement the interface methods.

The following is the list of ways to declare an interface in C++ :

Basic Interface Implementation

This is a simple implementation of an interface where a class defines one pure virtual function and a class.

Syntax

Following is the syntax for the basic interface Implementation:

class Interface {
public:
    virtual void show() = 0;
    virtual ~Interface() {}
};

Example

In this example, we define an abstract class (Printable) with a pure virtual function print(). The derived class 'Document' implements print() to display "Printing Document...". In main() function, a Document object is created, and the print() method is called.

#include <iostream>
using namespace std;
class Printable {
public:
    virtual void print() = 0;
    virtual ~Printable() {}
};
class Document : public Printable {
public:
    void print() override {
        cout << "Printing Document..." << endl;
    }
};
int main() {
    Document d;
    d.print();
    return 0;
}

Following is the output to the above program:

Printing Document...

Interface with Multiple Functions

If an interface is having more than one pure virtual function to demonstrate multiple behaviors is called as Interface with Multiple Functions.

Syntax

Following is the syntax of the interface with Multiple Functions:

class Interface {
public:
    virtual void start() = 0;
    virtual void stop() = 0;
    virtual ~Interface() {}
};

Example

In this example, an abstract class(machine) defines pure virtual functions start() and stop(). The class(Engine) implements these functions to print messages. To demonstrate this functionality, an object(Engine) starts and stops using main() function.

#include <iostream>
using namespace std;
class Machine {
public:
    virtual void start() = 0;
    virtual void stop() = 0;
    virtual ~Machine() {}
};
class Engine : public Machine {
public:
    void start() override {
        cout << "Engine started." << endl;
    }
    void stop() override {
        cout << "Engine stopped." << endl;
    }
};
int main() {
    Engine e;
    e.start();
    e.stop();
    return 0;
}

The above program generates the following output:

Engine started.
Engine stopped.

Using Interface with Pointers

The interfaces with pointers allow a base class pointer to refer objects of derived classes. This enables dynamic method calls at runtime, ensuring flexibility and supporting polymorphism in programs.

Syntax

Following is the syntax using Interface with Pointers:

Interface* ptr = new DerivedClass();
ptr->method();

Example

In this example, we define an abstract class(Shape) with a pure virtual function. In main() function, a Shape pointer is used to create a Circle object by calling it by draw() method, and then it will delete the object.

#include <iostream>
using namespace std;
class Shape {
public:
    virtual void draw() = 0;
    virtual ~Shape() {}
};
class Circle : public Shape {
public:
    void draw() override {
        cout << "Drawing Circle" << endl;
    }
};
int main() {
    Shape* shape = new Circle();
    shape->draw();
    delete shape;
    return 0;
}

The above code produces the following result :

Drawing Circle

Multiple Interfaces in a Single Class

Multiple interfaces in a single class means a class can inherit and implement methods from more than one abstract base class (interface). This allows the class to combine functionalities from different interfaces while providing its own implementations.

Syntax

Following is the syntax to the multiple interfaces in a single class -

class Derived : public Interface1, public Interface2 {
    void method1() override;
    void method2() override;
};

Example

In this program , we demonstrate a multiple inheritance by creating two interfaces(Flyable and Swimmable) with pure virtual functions. The Duck class implements both by providing functionality. In the main() function, a Duck object showcases these actions by calling its fly() and swim() methods.

#include <iostream>
using namespace std;
class Flyable {
public:
    virtual void fly() = 0;
    virtual ~Flyable() {}
};
class Swimmable {
public:
    virtual void swim() = 0;
    virtual ~Swimmable() {}
};
class Duck : public Flyable, public Swimmable {
public:
    void fly() override {
        cout << "Duck flying" << endl;
    }
    void swim() override {
        cout << "Duck swimming" << endl;
    }
};
int main() {
    Duck d;
    d.fly();
    d.swim();
    return 0;
}

The above program executes the following output :

Duck flying
Duck swimming
Revathi Satya Kondra
Revathi Satya Kondra

Technical Content Writer, Tutorialspoint

Updated on: 2025-04-17T17:58:16+05:30

424 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements