🛠️ C++ Interface – Define Common Behaviors Across Classes!
Interfaces in C++ allow you to define a common set of functions that multiple classes can implement. This helps to enforce consistency and allows you to interact with different classes through a unified interface. 🖥️
🔍 What is an Interface in C++?
In C++, an interface is a class that contains only pure virtual functions. It defines a contract that derived classes must adhere to. Interfaces are often used to achieve polymorphism, allowing objects of different classes to be treated uniformly.
Think of an interface like a contract. You agree to perform certain actions (methods), but the specific details of how you do them are left to the implementing classes. 📜
🔧 Example: C++ Interface
#include <iostream> using namespace std; // Interface: Shape class Shape { public: virtual void draw() = 0; // Pure virtual function virtual double area() = 0; // Pure virtual function }; // Derived class: Circle class Circle : public Shape { private: double radius; public: Circle(double r) : radius(r) {} void draw() override { cout << "Drawing a Circle" << endl; } double area() override { return 3.14 * radius * radius; } }; // Derived class: Rectangle class Rectangle : public Shape { private: double width, height; public: Rectangle(double w, double h) : width(w), height(h) {} void draw() override { cout << "Drawing a Rectangle" << endl; } double area() override { return width * height; } }; int main() { Shape* shape1 = new Circle(5.0); shape1->draw(); cout << "Area of Circle: " << shape1->area() << endl; Shape* shape2 = new Rectangle(4.0, 6.0); shape2->draw(); cout << "Area of Rectangle: " << shape2->area() << endl; delete shape1; delete shape2; return 0; }
💡 Key Concepts of Interfaces
- Interfaces define pure virtual functions that must be implemented by derived classes.
- They provide a way to ensure that different classes implement the same set of functions, enabling uniform interaction.
- Interfaces can be used to achieve polymorphism, allowing you to treat objects of different classes in the same way.
- By using interfaces, you can create extensible and maintainable code that is easy to scale as your program grows.
⚠️ Things to Keep in Mind
- You cannot instantiate an object of an interface class directly, as it only contains pure virtual functions.
- Make sure that all derived classes implement the interface’s methods, or the class will be abstract as well.
🧾 Summary
- Interfaces in C++ allow you to define common behaviors across different classes.
- They help enforce polymorphism and provide a consistent way to interact with objects.
- Interfaces are implemented using pure virtual functions in abstract classes.
- They improve code flexibility and maintainability by standardizing behavior.