C++ Interfaces

Share on facebook
Share on twitter
Share on linkedin
Share on twitter
Share on tumblr

In this C++ tutorial, let us see C++ interfaces with an example program.

Introduction to C++ Interfaces

The behaviour or abilities of class in C++ are defined by the interfaces, without assigning to a particular implementation of that class.

The C++ interfaces are implemented using abstract classes. A class is made abstract by declaring at least one of its functions as a pure virtual function. A pure virtual function is defined by setting “= 0” in its declaration.

Declaration Syntax

It can be declared 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 is to offer a relevant base class from which other classes can inherit. Abstract classes cannot be used to instantiate objects and acts only as interfaces. If any chance of attempting to instantiate objects can cause a compilation error.

C++ Program for Interfaces

#include <iostream> 
using namespace std; 
// Base class
class Shape {
   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;
}; 
// Derived classes
class Rectangle: public Shape {
   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;
}

Output

Total Rectangle area: 35
Total Triangle area: 17

 

Leave a Comment

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