Function Overloading in C++

Function Overloading in C++

Function overloading in C++ is define as the process of having two or more function having the same name, but having different parameters. In function overloading. The function is defined by using either various types of arguments or a various number of arguments.

In function oerloading two functions have the same name if only having different number and type of arguments to be passed.

Example of function Overloading in C++

// same name having different arguments
int num() { }
int num(int a) { }
float num(double a) { }
int num(int a, double b) { }

Program of function overloading

#include <iostream>
using namespace std;
 
void print(int i) {
  cout << " First is int " << i << endl;
}
void print(double  f) {
  cout << " Second is float " << f << endl;
}
void print(char const *c) {
  cout << " Third is char* " << c << endl;
}
 
int main() {
  print(5);
  print(5.10);
  print("Five");
  return 0;
}

Output

First is int 5 
Second is float 5.1 
Third is char* Five

 

How Function Overloading works?

Firstly check the Function name  Parameter are exactly match or not. If there are not found the exact match then char and shortare fromoted to int and float is promoted to the double

And If no match found then C++ tries to find a match through the standard conversion. If it is not executed thenERROR

 

Read more, Types of function in C++

 

Share this post

Leave a Reply

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