Function Overloading vs Function Overriding in C++

carnato

Vishal Yadav

Posted on December 25, 2021

Function Overloading vs Function Overriding in C++

Function Overloading:

This can achieve at compile time.

  • It provide multiple definition of the function by changing the signature i.e change the number of parameter, change datatype of parameter .

  • Return type can not play any role.

Example:

// Function Overloading
#include <iostream>
using namespace std;

//overloaded functions
void test(int);
void test(float);
void test(int, float);

int main()
{
    int a = 5;
    float b = 5.5;

    // Overloaded functions with different type and number of //parameters
    test(a);
    test(b);
    test(a, b);

    return 0;
}

// Method 1
void test(int var)
{
    cout << "Integer number: " << var << endl;
}

// Method 2
void test(float var)
{
    cout << "Float number: "<< var << endl;
}

// Method 3
void test(int var1, float var2)
{
    cout << "Integer number: " << var1;
    cout << " and float number:" << var2;
}

Enter fullscreen mode Exit fullscreen mode

Output:

Integer number: 5
Float number: 5.5
Integer number: 5 and float number:5.5
Enter fullscreen mode Exit fullscreen mode

Function Overriding:

  • It can achieved at run time.

  • Basically it is the features of c++ which can allow us to use and redefine a function in child class which is already declare in the base class. with the same signature.

// Function Overriding
#include<iostream>
using namespace std;

class BaseClass
{
public:
    virtual void Display()
    {
        cout << "\nThis is Display() method"
                " of BaseClass";
    }
    void Show()
    {
        cout << "\nThis is Show() method "
            "of BaseClass";
    }
};

class DerivedClass : public BaseClass
{
public:
    // Overriding method - new working of
    // base class's display method
    void Display()
    {
        cout << "\nThis is Display() method"
            " of DerivedClass";
    }
};

// Driver code
int main()
{
    DerivedClass dr;
    BaseClass &bs = dr;
    bs.Display();
    dr.Show();
}
Enter fullscreen mode Exit fullscreen mode

Output:

This is Display() method of DerivedClass
This is Show() method of BaseClass

  • Overriding of function can occur when one class can inherited from the other class.

  • overriding can come into picture when derived class want to added the new job in the predefine function(define in the base class) without changing the signature of the function i.e number of argument, change in datatype of parameter.

💖 💪 🙅 🚩
carnato
Vishal Yadav

Posted on December 25, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related