How to Use Function Overloading in C++

Function overloading is a technique used to assign a same name to multiple functions but these functions are differentiated by the input parameters and output parameters assigned to them. This technique is used to do a multitasking with a same function name. It introduces simplicity and ease of use. For example you want to use a function named math, so to do two different tasks, one function could be int math(), with no input parameters and it will take the input inside it and another math function accepts two values as an input to perform addition e.g. int math(int a, int b); it will simply inquire you for operation and will not ask to enter the value. This was a simple example. Following step by step guide will illustrate use of method overriding in detail.

Instructions

  • 1

    The syntax of declaring, initializing and calling a function remains same, as it was illustrated in a guide step by step how to use functions in C++”.


    The only difference is that functions will have common title but different parameters. Have a look at following functions.


    int temp (char a, char b);


    int temp (char a, char b, char c);


    int temp (int a, int b);


  • 2

    Now when you will implement these functions, slightly change the functionality of them so that you can easily differentiate when checking them. For example:


    int temp (char a, char b) {


    return (int)(a+b);


    }


    Now for the function with input parameters as int:


    int temp (int a, int b){


    int sum=a+b;


    return sum;


    }


    Now if you look on both of the functions above whenever a function named temp will be called with chars as inputs the first one will be called and with int type input parameters, the second function will be called. In the function with char type input parameters we have type cast the sum of both chars to an int.




Leave a Reply

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


− six = 3