Question

I looked over the internet for an answer to my questions but couldn't find any, so here I am.

Is it correct to specify override to my function that derived from a pure virtual:

class baseClass
{
    public:
        virtual void myFunction() = 0;
}

class derivedClass : public baseClass
{
    public:
        virtual void myFunction() override;
}

Is this correct?

And my second question is: Do I have to specify virtual in the derivedClass for my function even though no class will inherite from my derived class (it will be final)?

Thank you a lot for your answers!

Was it helpful?

Solution

Is this correct?

Yes. Override ensures that the function is virtual and overriding a virtual function from the base class. The program is ill-formed (a compile-time error is generated) if this is not true.

Do I have to specify virtual in the derivedClass for my function even though no class will inherite from my derived class (it will be final)?

No you don't. But even if you leave away the virtual specifier it remains virtual. Because it has been declared virtual in your BaseClass.

If some member function vf is declared as virtual in a class Base, and some class Derived, which is derived, directly or indirectly, from Base, has a declaration for member function with the same

  • name
  • parameter type list (but not the return type)
  • cv-qualifiers
  • ref-qualifiers

Then this function in the class Derived is also virtual (whether or not the keyword virtual is used in its declaration) and overrides Base::vf (whether or not the word override is used in its declaration). Base::vf does not need to be visible (can be declared private, or inherited using private inheritance) to be overridden.

OTHER TIPS

Also, please remember that you should define a virtual destructor (can be empty one) in baseClass, in order to guarantee a proper resource deallocation in the derived classes.

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