C++ Function Overloading

October 27, 2015 Posted by WithU Technologies
There are situations when we need to create multiple functions with same name.

we can do that by using different parameters for different functions with same name and that is known as the function overloading.

As shown below:

#include <iostream>
#include <stdlib.h>
using namespace std;

void show(int a){    //Integer parameter is used with same function name

      cout<<"This is an integer: "<<a<<endl;   //Output integer value

}

void show(float b){   //Float parameter is used with same function name

      cout<<"This is a float: "<<b<<endl;  //Output float value

}

void show(int a, float b){   //Both integer and float parameter used with same function name

      float r;        //as we have one float value to add with, thus we show the answer in float for a perfect answer

      r = a+b;        // We add integer value and float value

    cout<<r;        //Output float value

}

int main(){

      int x = 10;       //initialise x as an integer to match function definition

      float y = 12.23;   // initialise y as float to match the function definition

      show(x);           //Calls the integer function

      show(y);           // Calls the float function

    show(x,y);         // Calls the summation of integer and float function

}

/*

This is an integer: 10

This is an float: 12.23

22.23

*/

·         Here we start the program with our first function named show and the return type is void for a reason which we reveal later. We use integer for our first parameter.

·         Then our second function with the same name and void data type. But this time with the float parameter.

·         Then we declare our third function with both the integer and float value respectively separated by comma.

·         Apart from the above two functions which will only show the respective integer and float value separately, it adds the integer and float value and then output the result in float value to make it perfect.

The function must defer from data types or the number of arguments in the parameter list.

Void as Return Type: We cannot overload function declarations that only differ only by return type. And thus we keep it void without using any return value.