Question

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 derived class before you can implement them outside of the class definition. Wouldn't you agree?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top