Suppose a C++ class has multiple member functions with the same name, but different parameters (with changes in type, sequence, or number), and the programmer can use them to perform the same kind of operations. It refers to function overloading. In this case, two functions may have the same identifier (name), and if the number of arguments passed to the functions or the types of arguments differ, overloading is possible in C++ programs. In other words, it is the ability to create multiple functions with the same name and slightly different implementations. The appropriate function gets invoked depending on the context (type, sequence, and number of the value passed).



In the case of C++ programs, function overloading is as follows:

Example:

int overloaded(){ }
int overloaded(int g){ }
int overloaded(float g){ }
int overloaded(int g, double s){ }
int overloaded(float s, int g, double k){ }

Here the function name overloaded is used as overloading functions with the change in argument type and number.

Example:

#include <iostream>
using namespace std;

long add(long, long);
float add(float, float);
int main()
{
    long a, b, c;
    float e, f, g;
    cout << "Enter two integers\n";
    cin >> a >> b;
    c = add(a, b);
    cout << "Sum of integers: " << c << endl;
    cout << "Enter two floating point numbers\n";
    cin >> e >> f;
    g = add(e, f);
    cout << "Sum of floats: " << g << endl;
}

long add(long c, long g)
{
    long sum;
    sum = c + g;
    return sum;
}

float add(float c, float g)
{
    float sum;
    sum = c + g;
    return sum;
}
Rules for Overloading Operators:
  • Only existing operators can be overloaded.
  • Programmers cannot change the basic meaning of an operator.
  • Overloaded operators will always follow the syntax rules of the original operators.
  • Programmers cannot use the friend function to overload certain operators.


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram