Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure virtual and override function (c++)

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!

like image 338
Silouane Avatar asked Apr 09 '14 09:04

Silouane


2 Answers

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.

  • cppreference.com
like image 90
Sambuca Avatar answered Sep 20 '22 03:09

Sambuca


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.

like image 35
Roman Avatar answered Sep 21 '22 03:09

Roman