why we need interface or pure virtual function in c++

后端 未结 3 2017
小蘑菇
小蘑菇 2021-01-15 06:09

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

3条回答
  •  礼貌的吻别
    2021-01-15 06:42

    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.

提交回复
热议问题