Function overriding allows us to define a function at a derived class that is already present in a base class. And that base is said to be overridden. Both derived and base class has the member function with the same name, same return type, and same arguments list.
And the decision made to call the required function is done at the run time. Hence, it is used to achieve the Runtime polymorphism.
Let us understand through an example of function overriding using C++. It involves inheritance in a program given below.
Example of Function Overriding in C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | // C++ program for function overriding #include <iostream> using namespace std; class Animal { public: void display() { cout << "I am Animal" << endl; } }; class Dog: public Animal { public: void display() { cout << "I am a Dog" << endl; } }; int main(void) { Animal anim = Animal(); anim.display(); //parent class object Dog dg = Dog(); dg.display(); // derived class object return 0; } |
Output:
1 2 | I am Animal I am a Dog |