C++ Program to Create an Interface
Interfaces are a feature of Java that allows us to define an abstract type that defines the behaviour of a class. In C++, there is no concept of interfaces, but we can create an interface-like structure using pure abstract classes. In this article, we will learn how to create interface-like structure in C++.
Implementation of Interface in C++
To create an interface, first we need to understand the rules that governs the behaviour of interface:
- Interface only contains the declaration of the methods not definition.
- Interface methods must be declared public.
- Any class can implement/inherit any interface.
- The implementing class must provide the definition of the methods.
- Instance of interface cannot be created.
All of these rules can be followed by C++ pure abstract class that only contains the pure virtual functions. Following are the rules that governs the behaviour of pure abstract class:
- All methods of pure abstract class are only declared but not defined (pure virtual methods).
- Its methods can be defined either public, protected or private.
- Any class can inherit pure abstract class.
- The implementing class must provide the definition of the methods otherwise it will become abstract class.
- Instance of pure virtual class cannot be created.
As we can see, we can almost perfectly simulate the Java Interfaces with C++ Pure Abstract Classes.
Example
#include <bits/stdc++.h>
using namespace std;
// Interface equivalent pure abstract class
class I {
public:
virtual string getName() = 0;
};
// Class B which inherits I
class B : public I {
public:
string getName() {
return "GFG";
}
};
// Class C which inherits I
class C : public I {
public:
string getName() {
return "GeeksforGeeks";
}
};
int main() {
B obj1;
C obj2;
I *ptr;
// Assigning the address of obj1 to ptr
ptr = &obj1;
cout << ptr->getName() << endl;
// Assigning the address of obj2 to ptr
ptr = &obj2;
cout << ptr->getName();
return 0;
}
Output
GFG GeeksforGeeks
Explanation: The class I
acts as an interface, declaring the pure virtual function getName()
which must be implemented by any class that inherits from it. Classes B
and C
inherit from I and provide their own specific implementations of the getName()
function, returning different strings.