Function Overriding in C++

Function Overriding in C++

Hello everyone, in this article we are going to talk about function overriding in C++ programming language. We will make some examples for better understanding.

Let's get started.

We can derive new classes from some other classes. This is one of concepts of inheritance charatestic of Object Oriented Programming. So our classes can inherit some other classes to use their functions instead of redefinition in derived class.

So sometimes we coul want to change the behaviors of inherited function in derived classes. In this case function overriding is coming for help.

Function Overriding is redeclaration of a function which declared in inherited class.

For these examples firstly add below libraries.


#include <iostream>
using namespace std;

Below you can see the basic example of function overriding. From now We will use this classes for showing the function overriding.


class  Person{
    public:
        void greet(){
             cout << "Person Class Greetings" <<endl;
        };
};

class  Employee : public Person{
    public:
        void greet(){
             cout << "Employee Class Greetings" <<endl;
        };
};

In above example we declared a Person class wıth greet() function. Then we derived an Employee class and redeclared the greet function. In main function when we called the greet function of Employee class, overriden function is invoked.

Let's invoke the greet function from derived Employee class.

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    Employee empl;
    empl.greet();
    return a.exec();
}
Program output will be like below

Employee Class Greetings

So we can also use function overriding with pointers. We create a pointer of base class and we assign the derived class to it. When we invoked the function from pointer it will invoke the base class type.


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    Employee empl;
    empl.greet();

    Person *per = &empl;
    per->greet();

    return a.exec();
}
Program output will be like below.

Employee Class Greetings
Person Class Greetings

We can also access the base class over derived class. We can directly invoke the not-overriden method from base class. Below you can see the usage.


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    Employee empl;
    empl.Person::greet();
    return a.exec();
}
Program output will be like below:

Person Class Greetings

That is all in this article.

Burak Hamdi TUFAN


Tags


Share this Post

Send with Whatsapp

Post a Comment

Success! Your comment sent to post. It will be showed after confirmation.
Error! There was an error sending your comment. Check your inputs!

Comments

  • There is no comment. Be the owner of first comment...