Interfaces in C++ (Abstract Classes)
C++ doesn't have a built-in "interface" keyword or construct like some other programming languages (e.g., Java or C#). However, you can create interfaces in C++ using abstract classes and pure virtual functions, similar to what was discussed earlier.
Creating an Interface
An interface defines a contract that classes must adhere to. In C++, this is typically achieved using an abstract class with pure virtual functions. An abstract class that acts as an interface contains declarations of functions without any actual implementation.
Pure Virtual Functions
Pure virtual functions are declared in the abstract class and marked with "= 0". They don't have any implementation in the base class. Derived classes must provide concrete implementations for these functions.
Implementing an Interface
Any class that wants to "implement" the interface must derive from the abstract class and provide definitions for all the pure virtual functions declared in the interface.
Following is a step-by-step example of how to create and use an interface in C++:
Define the Interface (Abstract Class)
In this step, we define an abstract class called Drawable, which serves as our interface. It contains a pure virtual function draw(), which does not have an implementation. This function is a contract that any class implementing the Drawable interface must define.
Create a Class that Implements the Interface
Here, we create a class Circle that implements the Drawable interface. It derives from Drawable and provides an implementation for the draw() function.
Create an Object of the Implementing Class
In the main function, we create an object of the Circle class. We can call the draw() function on this object, even though it is declared as a Drawable. This demonstrates that the Circle class adheres to the Drawable interface contract.
Full SourceCompile and Run
Compile the program and run it. You will see the output:
This output confirms that the draw() function from the Drawable interface was successfully implemented in the Circle class and executed.
Conclusion
Interfaces are implemented using abstract classes and pure virtual functions. An interface defines a contract through an abstract class with pure virtual functions, and any class that implements this interface must provide concrete implementations for those functions. This approach enforces a common set of methods that implementing classes must adhere to, promoting code consistency and polymorphism.