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

后端 未结 3 2020
小蘑菇
小蘑菇 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:26

    Pure virtual functions is your way of telling the users of your class that they cannot use the class on its own, without inheriting from it.

    Obviously, you can do what you describe, and the system is going to compile and work as expected. However, an pure virtual function is not a construct for the compiler; it is for humans who read your code. It is with this construct that you tell the readers of your code that they must inherit from your class, because the class is not designed to be instantiated on its own.

    You use pure virtual functions in situations when there is no reasonable default implementation for a function. This tells people who implement your class that they must provide certain functionality, and the compiler helps them in detecting situations when they forgot to provide an implementation.

    If, on the other hand, you provide a default implementation for a virtual function that should be implemented by a subclass, and then the users of your class library forget to provide an implementation, the problem would not be detected until run-time.

提交回复
热议问题