Overriding - RJAE5/2143-OOP GitHub Wiki

Overriding

In parallel with the virtual keyword, overriding is used to fulfill the "contract" that the virtual keyword starts. In the derived class, override is used on a method with the same name from the base class directly after the parameter list and preceding the function body. This end of the contract solidifies runtime polymorphism, but is not strictly necessary to achieve it.

Example

class A
{
public:
    // Starting the virtual/override contract
    virtual void show() 
    {std::cout << "Showing from A!" << std::endl;}
};

class B : public A
{
public:
    // Fulfilling the virtual/override contract
    void show() override
    {std::cout << "Showing from B!" << std::endl;}
};

int main()
{
    A a;
    B b;

    a.show();
    b.show();

    return 0;
}

The output of this code snippet is exactly as you would expect, both a and b call their respective show() functions, but this is achieving runtime polymorphism by using the virtual keyword. It is worth noting that the code would still compile and produce the same exact output if we removed the override keyword.

Showing from A!
Showing from B!

Important Notes

  • The override keyword is fulfilling the "contract" that the virtual keyword started in the base class.
  • While virtual is absolutely necessary for runtime polymorphism, the override keyword is more for readability.
    • It is not always necessary to specify that you are overriding a function.
    • However, if you use the override keyword on a function that does not have a virtual counterpart, the program will not compile.

Sources:

  1. https://en.cppreference.com/w/cpp/language/override
  2. https://www.geeksforgeeks.org/override-keyword-c/