Function Overriding in C++

In inheritance, the derived class inherits all the functions from the base class with same behavior. That means that an inherited function will behave in the exact same way in both derived and base classes. But we can redefine the behavior of a particular inherited function in derived class. The feature is called function overriding.

In function overriding we have functions in both base and derived classes with the exact same name and input parameters but with different implementation.

#include <iostream>
using namespace std;

class Animal{
public:
    void speak() {
        cout << "No no..." << endl;
    }
};

class Cat : public Animal {
public:
    void speak() {
        cout << "Meow..." << endl;
    }
};

int main() {
    Animal a1;
    Cat c1;

    cout << "Animal says: ";
    a1.speak();
    
    cout << "Cat says: ";
    c1.speak();

    return 0;
}
$ g++ -o test test.cpp 
$ ./test 
Animal says: No no...
Cat says: Meow...

Here the base class Animal and the derived class Cat both have the function, speak() with different implementation.

In main(), the overridden function is called using a base class object and a derived call object. The version of the function was decided based on the object type.

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

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

0
0
0
0
0
0