Function Overriding in C++

In this tutorial, you will learn all about Function Overriding in the C++ programming language. Function overriding is a feature that provides us to have the same function in the child class which is already being in the parent class. A child class obtains the member functions and data member of the parent class, but when we want to override functionality in the child class then we can use function overriding. It is similar to creating a new redaction of an old function, in the child class.

Function Overriding

In another way, Function override is the idea of object-oriented programming language. Assume we have one way in a parent class and we are overriding that way in the child class with a similar signature. A similar number of parameters and return types. We have given our personal implementation to this process specific to the child class. So, we can maintain that the method can perform in two different classes.

Syntax:

public class Bank{
access_modifier:
return_type method_name(){}
};
}
public class Branches : public Bank {
access_modifier:
return_type method_name(){}
};
}

In the above syntax, we have one parent class Bank and one child class Branches. Here child class is derived from the parent class. It means the child can use all the functionality and properties which are present in the parent class.

How Function Overriding works in C++?

If we want to perform function overriding into the program first we require to have some type of relationship between two classes because we can not perform function overriding within a similar class, if we perform then it would be function overloading. So for function overriding we should have inheritance between two classes i.e. Big and small relations.

The main purpose behind this we can give the specific performance to our method which is specific to that class. Function overriding can be performed at runtime because which method will get a call will be resolved at runtime only. also, We can use parent class reference to call methods.

Function Overriding Example

#include <iostream>
using namespace std;
class Parent {
public:
void m1(){
cout<<"This is the parent class method";
}
};
class Child: public Parent
{
public:
void m1()
{
cout<<"This is the child class method ";
}
};
int main(void) {
Child c = Child();
c.m1();
Parent p = Parent();
p.m1();
return 0;
}
Output
This is the child class method This is the parent class method

Conclusion

So function overriding raises the code readability also performs it easy to maintain. We do not require to change the code of parent class or any other secondary child classes it is completely free and easy to use. Learn Function Overloading.

Leave a Comment

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

Scroll to Top