C++ Program to Create an Interface
Interfaces are nothing but a way to describe the behavior of a class without committing to the implementation of the class. In C++ programming there is no built-in concept of interfaces. In order to create an interface, we need to create an abstract class which is having only pure virtual methods. In C++, Interfaces are also called pure abstract classes.
Pure Virtual Functions
A Pure Virtual Function is a function where we only declare the function but not the function definition. The implementation for pure virtual methods is done at the derived class by method/function overriding. A function is said to be a pure virtual function if it is defined in the class as follows:
virtual datatype functionName(parameter1, parameter2,…) = 0
An abstract class is a class that is specially designed to be used as a base class. Abstract class must have at least one pure virtual function. It may have variables and normal functions. The derived classes of an abstract class must implement all the pure virtual functions of their base class or else they too become abstract.
Importance of Interfaces
- Any class derived from the pure abstract class (Interface) must implement all of the methods of the base class i.e. Interface.
- Interface pointers can be passed to functions and classes thereby we can call the functions of the derived class from there itself.
Rules While Using Interfaces
- Declare only pure virtual functions. (No definition)
- For pure virtual functions assign only 0.
- Cannot create an instance of the class.
- We can create a pointer to the instance of the derived class with a reference of a base abstract class.
Let’s look into a few sample examples of programs for creating the interface.
Example 1: In the below code, an interface GFG i.e. an abstract class is created with a pure virtual method, and its function is implemented in the child class, and in the main function, we called the returnString() method by following the rules of using interfaces.
Example 2: In the below code, an abstract class websiteName is created with a pure virtual function in it. So it acts as an interface. The functionality of the method getName() is implemented in the two child classes of the base class.
Short form - GFG Full form - GeeksforGeeks