Interfaces in C++

Interfaces

  • Interface describes the behavior of a class and contains only a Virtual Destructor and Pure Virtual Functions.
  • These are the non-instantiable types which contains only function declarations.
  • An object must supply definitions for all of the functions to implement an interface.
  • Interfaces are implemented using Abstract Class.
  • Abstract class provides an appropriate base class from which other classes can inherit and it cannot be used to instantiate objects and serves only as an interface.
  • At least one function is required as Pure Virtual Function for making a class abstract. This function is specified by placing "=0" in its declaration as follows:

  • Class Employee
    {
         public:
              virtual int emp_details() = 0;       //Pure Virtual Function
         private:
              int empid;
              string empname;
              float salary;
    }

  • Interface specifies pure virtual function declarations into a base class.

Example : Program implementing Interface

Following program demonstrates the parent class provides an interface to the base class to implement a function called area():

#include <iostream>
using namespace std;
class Shape  // Base class
{
      public:
          virtual float area() = 0;    // Pure Virtual Function
          float radious(float r)
          {
               ar = r;
          }
          float SetLength(float l)
          {
               length = l;
          }
          float SetBreadth(float b)
          {
               breadth=b;
          }
          float SetSideSquare(float s)
          {
               side=s;
          }
      protected:
          float ar;
          float length;
          float breadth;
          float side;
};
class Circle: public Shape   // Derived class
{
      public:
          float area()
          {
               return (3.14*ar*ar);
          }
};
class Rectangle: public Shape   //Derived class
{
      public:
          float area()
          {
               return (length*breadth);
          }
};
class SideSquare: public Shape //Derived class
{
      public:
           float area()
           {
                return (side*side);
           }
};
int main()
{
    Circle cr;
    cr.radious(3);
    cout << "Area of Circle : " << cr.area() << endl; // Print the area of circle.
    Rectangle rect;
    rect.SetLength(3);
     rect.SetBreadth(6);
    cout << "Area of Rectangle : " << rect.area() << endl;   // Print the area of rectangle.
    SideSquare sq;
    sq.SetSideSquare(2);
    cout << "Area of Square : " << sq.area() << endl;    // Print the area of Square.
    return 0;
}


Output:
Area of Circle : 28.26
Area of Rectangle : 18
Area of Square : 4

In above program, an abstract class defines an interface in terms of area() and three other classes Circle, Rectangle and SideSquare implement the same function but with different algorithm to calculate the area specific to the shape.