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
overridekeyword is fulfilling the "contract" that thevirtualkeyword started in the base class. - While
virtualis absolutely necessary for runtime polymorphism, theoverridekeyword is more for readability.- It is not always necessary to specify that you are overriding a function.
- However, if you use the
overridekeyword on a function that does not have avirtualcounterpart, the program will not compile.