Junior — Middle
Can you explain what is meant by interfaces in programming?
sobes.tech AI
Answer from AI
In programming, an interface is an abstract type that defines a set of methods (and sometimes properties) that a class must implement. Interfaces do not contain implementations, but only describe which functions should be available.
In C++, an interface is usually implemented through abstract classes with purely virtual methods:
class IShape {
public:
virtual double area() const = 0; // pure virtual function
virtual ~IShape() {}
};
class Circle : public IShape {
double radius;
public:
Circle(double r) : radius(r) {}
double area() const override {
return 3.1415 * radius * radius;
}
};
Thus, an interface sets a contract that all classes implementing it must adhere to. This allows writing code that works with objects through the interface without knowing the specific implementation.