C++ Interfaces Tutorial
An interface in C++ is a class that contains only pure virtual functions. It defines a contract that must be implemented by derived classes. Interfaces provide a way to achieve polymorphism and ensure that certain methods are implemented in all derived classes.
What is an Interface?
In C++, an interface is a class that only contains pure virtual functions. It cannot be instantiated and must be implemented by other classes. Interfaces are a way to specify the behavior of objects without defining the exact implementation.
#include <iostream>
using namespace std;
class Drawable {
public:
virtual void draw() = 0; // Pure virtual function
};
class Circle : public Drawable {
public:
void draw() override {
cout << "Drawing Circle" << endl;
}
};
int main() {
Drawable* drawable = new Circle();
drawable->draw(); // Outputs: Drawing Circle
delete drawable;
return 0;
}
Interface Syntax
In C++, an interface is implemented by declaring a class with pure virtual functions, indicated by `= 0` at the end of the function declaration. The derived class must then implement these functions.
class Printer {
public:
virtual void print() = 0; // Pure virtual function
};
class LaserPrinter : public Printer {
public:
void print() override {
cout << "Printing using Laser Printer" << endl;
}
};
int main() {
Printer* printer = new LaserPrinter();
printer->print(); // Outputs: Printing using Laser Printer
delete printer;
return 0;
}
Benefits of Using Interfaces
- Defines a contract that must be followed by any class that implements the interface.
- Enables polymorphism, allowing objects of different classes to be treated as objects of the same type.
- Increases code flexibility by decoupling interface from implementation.