C++

C++ Function Overriding – Detailed FAQ

A feature called “function overriding” enables us to include the same function in a child class that is already present in the parent class. A child class inherits the data members and member functions from the parent class, however you can utilize function overriding to replace a functionality in the child class. It resembles rewriting an outdated function in the child class.

Example of Function Overriding

You need to have the same signature in the child class in order to override a function. The data type and parameter order are referred to as the signature. As there is no parameter in the parent function in this case, no parameter was used in the child function.

#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();
   return 0;
}

Output:

Function of Child Class

Note: When a function is overridden, it is referred to as the overridden function in the parent class and as the overriding function in the child class.

How to call a child class’s overridden function

As we saw above, the child class function (the overriding function) is called when the call to the function (involved in overriding) is made. What if you wish to use an object from a child class to call the overridden function? You can accomplish this by making the child class object in a way that the parent class reference points to it. To further grasp it, let’s look at an example.

#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() {
   /* Reference of base class pointing to
    * the object of child class.
    */
   BaseClass obj = DerivedClass(); 
   obj.disp();
   return 0;
}

Output:

Function of Parent Class

You can do it in the following way if you wish to invoke the Overridden function from the Overriding function:

parent_class_name::function_name

In the child class’s disp() function, the following statement can be added to do this in the example above:

BaseClass::disp();

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button