Method overriding is redefining the same method of the Parent Class in the Child class.
Let us understand with the below example.
So, we have the LivingBeing class that has a breathe() method.
class LivingBeing
{
public:
void breathe() {
cout << "Breathes oxygen from Air.";
}
};
So, the breathe() method has a print statement,
cout << "Breathes oxygen from Air";
That says, all Living Beings should Breathe oxygen from Air.
Now, let us create a Fish class and since Fish is also a LivingBeing. It should inherit the LivingBeing class.
But the only issue is, the breathe() method won't be valid for Fish. As a Fish breathe oxygen from water.
And this is where Method Overriding comes into picture.
Let us understand with the below example.
#include <iostream>
using namespace std;
class LivingBeing
{
public:
void breathe() {
cout << "Breathes oxygen from air.";
}
};
class Fish : public LivingBeing
{
public:
void breathe()
{
cout << "Breathes oxygen from Water";
}
};
int main() {
Fish fish;
fish.breathe();
return 0;
}
And all we have done is, created the LivingBeing being class with the breathe() method.
class LivingBeing
{
public:
void breathe() {
cout << "Breathes oxygen from air.";
}
};Then we have created the Fish class, inheriting the LivingBeing class.
class Fish : public LivingBeing
{
public:
void breathe()
{
cout << "Breathes oxygen from Water";
}
};So, by Inheritance, the Fish class should get the breathe() method/behaviour of the LivingBeing class.
And since we don't want the breathe() method/behaviour of the LivingBeing class. We have redefined or overridden the breathe() method in our Fish class using the override keyword.
void breathe()
{
cout << "Breathes oxygen from Water";
}So, with fish object of Fish class,
Fish fish;
Now if you see the output.
Breathes oxygen from Water
We are able to call the breathe() method defined in the Fish class itself.
fish1.breathe();
And ignored the breathe() method defined in the parent class LivingBeing.