Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any point in using `override` when overriding a pure virtual function?

For example:

class Base {   virtual void my_function() = 0; };  class Derived : Base {   void my_function() override; }; 

From what I read, the override keyword is used to make sure that we have the correct signature in the function that we are overriding, and it seems to be its only use.

However, in the case of a pure virtual function, the compiler would throw an error if we used an incorrect signature in the Derived class (or Base class, depending on how one see things). So, is there any point in adding override at the end of Derived::my_function() declaration?

like image 676
R2B2 Avatar asked Sep 27 '17 11:09

R2B2


People also ask

Do pure virtual functions have to be overridden?

¶ Δ A pure virtual function is a function that must be overridden in a derived class and need not be defined. A virtual function is declared to be “pure” using the curious =0 syntax.

Is it necessary to override every virtual function?

The virtual keyword can be used when declaring overriding functions in a derived class, but it is unnecessary; overrides of virtual functions are always virtual. Virtual functions in a base class must be defined unless they are declared using the pure-specifier.

Do I have to override virtual C#?

Yes, you need to use the override keyword, otherwise the method will be hidden by the definition in the derived class.

What happens if the pure virtual function is not overridden in the derived class in C++?

3) If we do not override the pure virtual function in derived class, then derived class also becomes abstract class.


2 Answers

However, in the case of a pure virtual function, the compiler would throw an error if we used an incorrect signature in the Derived class

No, this compiles:

class Base {   virtual void my_function() = 0; };  class Derived : Base {   void my_function(int); //                 ^^^ mistake! }; 

While this does not:

class Base {   virtual void my_function() = 0; };  class Derived : Base {   void my_function(int) override; }; 

error: void Derived::my_function(int) marked override, but does not override


The error you're talking about only occurs when instantiating Derived - override allows you to catch the mistake earlier and makes the definition of Derived clearer/more readable.

like image 151
Vittorio Romeo Avatar answered Sep 21 '22 02:09

Vittorio Romeo


Yes, it is a good idea to use override keyword consistently as a defensive practice.

Consider a redesign when the author of the Base decides that my_function should no longer be a pure virtual, and also that it should take a new parameter. With override in place the compiler will catch this problem; without an override your Derived class would continue to compile.

like image 30
Sergey Kalinichenko Avatar answered Sep 23 '22 02:09

Sergey Kalinichenko