Menu

Function Overloading In C++

  • Function overloading is the process of defining functions that two or more functions can have the same name, but with different parameters.
  • The secret to overloading is that each redefinition of the function must use,
    1. Different types of arguments
    2. Different number of parameters

Different types of arguments

     void display(int a);
     void display(float b);
     void display(char c);

Finding the best match

  • The actual arguments are comparing with the formal arguments (This process is called argument matching or process of disambiguation).
  • The compiler finds the best match through the following steps:
    1. Search for an exact match
    2. A match through the promotion
    3. A match through standard conversion rules
    4. A match through the user-defined conversion

Search for an exact match

  • If the type of actual and formal argument is exactly the same, the compiler invokes that function.
     void display(int a); //function1
     void display(float b); //function2
     void display(char c); //function3
     .....
     display(2);

     it invoke the function function 1

A match through the promotion

  • If an exact match is not found, an attempt is made for finding an exact match through promotion.
     void display(int a); //function 1
     void display(int b); //function 2
     void display(char c); //function 3
     ......
     display(2.3);

     matches the function 1 through promotion.

A match through standard conversion rules

  • If the above two steps fail, an attempt is made to achieve a match through a standard conversion of the actual argument.
     void display(char c);//function 1
     void display(float b);//function 2
     display(214);//It will matches the function 2 and int 214 will converted into float.

A match through the user-defined conversion

  • If the above all steps fail the compiler will try the user-defined conversion to find a unique match.