Function Overloading in C++

Function in C++ is a group of program statements with a unique name that perform a specific task. Functions are used to provide modularity to a program.

function overloading in c++
Function Overloading in C++ is the mechanism by which a programmer can specify multiple definitions of the same function(same name) by changing:

  • Number of arguments passed to the function
  • Data type of arguments passed to the function

Essentially Function overloading means same function name but different number or type of arguments with different functionality.  Function overloading is also a type of Static or Compile time Polymorphism.

Overloading is a form of polymorphism. It allows the programmer to write functions to do conceptually the same thing on different types of data without changing the name. This allows consistency in notation, which is good both for reading and for writing code. This also allows the same method name to be reused across multiple implementations.

Example:

int myFunction() { }
int myFunction(int a) { }
float myFunction(double a) { }
int myFunction(int a, double b) { }

Notice that, the return type of all these 4 functions are not same. Overloaded functions may or may not have different return type but it should have different argument(s).

// Error code
int myFunction(int a) { }
double myFunction(int b){ }

The number and type of arguments passed to these two functions are same even though the return type is different. Hence, the compiler will throw error.

Function Overloading in C++ Example Program

Run Online

#include <iostream>
using namespace std;

void display(int);
void display(float);
void display(int, float);

int main() {

    int a = 5;
    float b = 5.5;

    display(a);
    display(b);
    display(a, b);

    return 0;
}
void display(int var) {
    cout << "Integer number: " << var << endl;
}
void display(float var) {
    cout << "Float number: " << var << endl;
}
void display(int var1, float var2) {
    cout << "Integer number: " << var1;
    cout << " and float number:" << var2;
}
Output
Integer number: 5
Float number: 5.5
Integer number: 5 and float number: 5.5
Watch it on YouTube

Leave a Reply

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