Function Overriding

Override keyword

C++11 override modifier informs the compiler that the new function should match a virtual method it saw in an ancestor class

  • It’s a safety feature, so you don’t accidentally introduce a new method if you mistype the signature of the method you want to override

For instance,

class base
{
  public:
    virtual int foo(float x) = 0; 
};
 
 
class derived: public base
{
   public:
     int foo(float x) override { ... } // OK
}
 
class derived2: public base
{
   public:
     int foo(int x) override { ... } // ERROR
};

In derived2 the compiler will issue an error for “changing the type”. Without override, at most the compiler would give a warning for “you are hiding virtual method by same name”.

What is the purpose of the override keyword? To make sure that we are indeed overriding.

It has no effect on the executable that is created. However, can be helpful for catching bugs.

class Text {
	...
	bool isHeavy(); // missing a const! won't override Book's virtual isHeavy because the signatures do not match.
}

Specifying override will have have the compiler warn you if the signature does not match a superclass’ virtual method.

Where to declare override keyword??

You need to put it in the .h file. If you put it in the .cc file, it complains with this error:

Expression.cc:77:40: error: virt-specifiers in ‘set’ not allowed outside a class definition
   77 | void BinOp::set(string var, int value) override {
      |                                        ^~~~~~~~
make: *** [<builtin>: Expression.o] Error 1 

However, I am confused because shouldn’t it say outside a class declaration instead of class definition? Declaration vs. Definition

I think for the compiler, they use those two words interchangeably.

https://stackoverflow.com/questions/52627553/override-not-allowed-outside-a-class-definition