In this tutorial, we are going to learn about function overidding in C++
Function overriding occurs when base class and derived class contains same function with same name and parameter. As a result of this, the derived class function hides the base class function. This means the derived class redefines the base class function.
Let’s take an example for better understanding.
#include <iostream> using namespace std; class Animal { public: void eat(){ cout<<"Eating..."; } }; class Cow: public Animal { public: void eat() { cout<<"Eating grass"; } }; int main(void) { Cow c; c.eat(); return 0; }
Output:
Eating grass
In this program, we have two classes, one is Animal acting as base class and other is Cow acting as derived class. You may have noticed that both the classes contains functions with same name and parameters, i.e eat().
Now, when we call this function in main(), the function present in Cow is called.
This overrides the function present in class Animal
To access the overridden function of the base class from the derived class, scope resolution operator :: is used. For example,
If you want to access eat() function of the Animal class, you can use the following statement in the derived class.
Animal::eating();
#include <iostream> using namespace std; class Animal { public: void eat(){ cout<<"Eating..."; } }; class Cow: public Animal { public: void eat() { Animal::eat(); } }; int main(void) { Cow c; c.eat(); return 0; }
Output:
Eating…