why we need interface ( pure virtual function or abstract class) in c++? Instead of having abstract class, Can we have a base class with virtual function defined in it, and
Pure virtual functions are for when there's no sensible way to implement the function in the base class. For example:
class Shape {
public:
virtual float area() const = 0;
};
You can write derived classes like Circle
and Rectangle
that implement area()
using the specific formulas for those kinds of shapes. But how would you implement area()
in Shape
itself, if it weren't pure virtual? How do you compute the area of a shape without even knowing what kind of shape it is?
If your function can be implemented (in a useful way) in the base class, then go ahead and implement it. Not all base classes need to be abstract. But some of them just inherently are abstract, like Shape
.