CPP Tutorial



INTERFACES IN C++


Interfaces in C++

In C++, there is no direct interface keyword like in some other languages (e.g., Java or C#), but you can create an interface using an abstract class that contains only pure virtual functions.

An interface defines a contract that derived classes must follow by implementing all the pure virtual functions.

How to create an Interface in C++?

  • Make a class with only pure virtual functions.
  • No data members or implemented methods inside the interface.
  • The class becomes abstract and cannot be instantiated.

Example of an Interface:

#include <iostream>
using namespace std;

// Interface declaration
class IAnimal {
  public:
    virtual void makeSound() = 0;  // Pure virtual function
    virtual void move() = 0;       // Pure virtual function
    virtual ~IAnimal() {}           // Virtual destructor for cleanup
};

class Dog : public IAnimal {
  public:
    void makeSound() override {
      cout << "Dog says: Woof Woof!" << endl;
    }
    void move() override {
      cout << "Dog runs" << endl;
    }
};

class Bird : public IAnimal {
  public:
    void makeSound() override {
      cout << "Bird says: Tweet Tweet!" << endl;
    }
    void move() override {
      cout << "Bird flies" << endl;
    }
};

int main() {
  IAnimal* animal1 = new Dog();
  IAnimal* animal2 = new Bird();

  animal1->makeSound();
  animal1->move();

  animal2->makeSound();
  animal2->move();

  delete animal1;
  delete animal2;

  return 0;
}
  

🖨️ Output:

Dog says: Woof Woof!
Dog runs
Bird says: Tweet Tweet!
Bird flies

Summary:

  • Interfaces in C++ are abstract classes with only pure virtual functions.
  • Derived classes must override all the pure virtual functions.
  • Interfaces define a common behavior that different classes can implement.
  • Use pointers or references to interface types for polymorphism.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review