Introduction to C++ | Interfaces
C++ Interfaces
In C++, an interface is a class that has only pure virtual functions and no data members. It defines a contract that derived classes must follow. Interfaces are used to achieve abstraction and ensure that certain methods are implemented in the derived classes.
What is an Interface?
An interface is essentially an abstract class where:
- All member functions are pure virtual functions (declared with
= 0
). - No implementation is provided in the interface itself.
- It cannot be instantiated directly.
Syntax of an Interface
Syntax
class InterfaceName {
public:
virtual void functionName() = 0; // Pure virtual function
virtual ~InterfaceName() {} // Virtual destructor (optional, but recommended)
};
Example of Interfaces in C++
Here’s an example of using interfaces in C++:
Code Example
#include <iostream>
using namespace std;
// Interface
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
virtual double calculateArea() = 0; // Pure virtual function
virtual ~Shape() {} // Virtual destructor
};
// Derived class 1
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
void draw() override {
cout << "Drawing Circle" << endl;
}
double calculateArea() override {
return 3.14 * radius * radius;
}
};
// Derived class 2
class Rectangle : public Shape {
private:
double length, width;
public:
Rectangle(double l, double w) : length(l), width(w) {}
void draw() override {
cout << "Drawing Rectangle" << endl;
}
double calculateArea() override {
return length * width;
}
};
int main() {
Shape* shape1 = new Circle(5.0);
Shape* shape2 = new Rectangle(4.0, 6.0);
shape1->draw();
cout << "Area of Circle: " << shape1->calculateArea() << endl;
shape2->draw();
cout << "Area of Rectangle: " << shape2->calculateArea() << endl;
// Free memory
delete shape1;
delete shape2;
return 0;
}
Output
Drawing Circle
Area of Circle: 78.5
Drawing Rectangle
Area of Rectangle: 24
Area of Circle: 78.5
Drawing Rectangle
Area of Rectangle: 24
Key Points About Interfaces
- All functions in an interface are pure virtual functions.
- Interfaces cannot contain member variables or function implementations.
- A class can implement multiple interfaces, enabling multiple inheritance.
- Interfaces are commonly used in complex systems to define shared behavior.
- Always include a virtual destructor in interfaces to avoid memory leaks when deleting derived objects through a base pointer.
Advantages of Using Interfaces
- Abstraction: Interfaces separate the definition of behavior from its implementation.
- Flexibility: A class can implement multiple interfaces to inherit behavior from different sources.
- Polymorphism: Interfaces enable runtime polymorphism, allowing dynamic behavior changes.
Pro Tip:
💡 Pro Tip
Use interfaces to define behaviors that are common across multiple unrelated classes. This ensures a consistent contract while keeping implementations flexible.