C++ – Usage of the word “override” in C++ and it’s virtual functions

abstractionc

I know that the following function is a virtual function and needs to be overridden when extended by another class:

virtual int getAge()=0;

What i don't understand is the following syntax I have seen in places:

double getAge(int id) override;

Is this also a virtual function? I thought the word "override" is only used when overriding an extended virtual function.

Best Answer

C++ has a rule about overridden functions: they don't have to be explicitly declared as virtual. Consider your example without override: double getAge(int id);. If there is a base class function declared virtual, named getAge, and takes the same parameters as the derived class function, then the derived class function will implicitly be virtual and it will be an override for that function.

However, what happens if you make a mistake? Let's say that you mistype the derived function name as gtAge. Well, if there isn't an override-able base class function... then that will declare a non-virtual function which overrides nothing. It remains a perfectly valid function declaration. The user made a mistake, but the compiler had no way to know. Even adding the virtual keyword doesn't solve this, as it's perfectly valid to add new virtual functions to a derived class.

Now, in your specific case, compilation will still fail. You declared the base class function as pure-virtual, so a derived class which doesn't override it cannot be instantiated. But even then, the error won't point directly at the line causing the problem; it won't point at the gtAge. Instead you'll get a "cannot instantiate due to no overridden getAge" error; the user will have to figure out where the derived class failed to override this function.

But if the base class function was not pure-virtual, then you're completely out of luck. You'll get highly unexpected behavior and it will take a while to figure out where you went wrong.

Enter override. This tells the compiler that you specifically intend this declaration to override a base class virtual function. So if the compiler doesn't find a matching function in a base class, the compiler will error out immediately, telling you exactly where you went wrong.


You may be getting confused by the fact that double getAge(int id) actually returns a different type from what it overrides. This is actually (unfortunately, in my opinion) perfectly valid. Overridden return types can be any type which is convertible to the return type of the base class function being overridden.