Redefinition of pure virtual methods in C++
Do you have to declare methods replacing a pure virtual function in a base class? If so, why? Because the base class has declared the methods as pure virtual, and therefore MUST exist in derived class, then is should not be necessary to redeclare them in the derive开发者_JAVA百科d class before you can implement them outside of the class definition. Wouldn't you agree?
Yes you have.
The reason for this is to let the compiler know that the virtual method is being implemented by the derived class since a derived class can also be abstract and have virtual methods. Since compilation units are compiled separately, the compiler would otherwise not know whether a virtual method is implemented by a derived class when compiling another compilation unit that uses the derived calss and thus whether it is an abstract class or not.
You don't have to override the declaration of the base class. If you don't, the derived class is simply abstract as well.
So, the declaration in the derived class serves a definite purpose, and you need it.
The class definition as the name says is the declaration of the class. If you are not declaring derived function (from the pure virtual one) compiler will not find it.
You have to derived the pure virtual functions only if your class will be instantiated. You can have the pure virtual function a class A, a class B that inherits from class A but not have derived functions and then a class C that inherits from class B with reimplementation of derived function. In that case only class C can be instantiated, so why compiler should add declaration of derived class in class B? That's why you have to indicate to compiler which class is reimplementing pure virtual functions.
精彩评论