Function Overriding

Overriding occurs when two methods have the same method name and parameters. One of the methods is in the parent class, and the other is in the child class.

Overriding allows a child class to provide the specific implementation of a method that is already present in its parent class.

Make sure to know the difference with Function Overloading.

#include <iostream>
using namespace std;
class BaseClass {
public:
   void disp(){
      cout<<"Function of Parent Class";
   }
};
class DerivedClass: public BaseClass{
public:
   void disp() {
      cout<<"Function of Child Class";
   }
};
int main() {
   DerivedClass obj = DerivedClass();
   obj.disp(); // Prints "Function of Child Class"
   return 0;
}

Danger

However, if you do Polymorphism, you gotta be careful about behavior. Actually, it seems that this just happens because they didn’t use Virtual Function keyboard, and then declared the class as the parent class.

Note

Function overriding doesn’t care about access specifiers. You can override any access specifier. Access specifiers only affect who can call the function.

Can overriden functions have different return types?

A subclass’s override method can return a subclass of the virtual function’s return type (if it’s a pointer or reference).

However, the type for overridden functions must match exactly. For a valid override to happen, only 2 things need to be the same:

  • Same function name
  • Same parameters

The return type must be the same (generally), but you can also have a Covariant Return Type (in which case it must be a pointer or reference).

We saw this in CS247.