Function Overloading


Advertisements

When we have multiple functions with the same name but different parameters, then they are said to be overloaded. This technique is used to enhance the readability of the program.

There are two ways to overload a function, i.e. −

  • Having different number of arguments
  • Having different argument types

Function overloading is normally done when we have to perform one single operation with different number or types of arguments.

Function Overloading in C++

The following example shows how function overloading is done in C++, which is an object oriented programming language −

#include <iostream> 
using namespace std;  
void addnum(int,int); 
void addnum(int,int,int); 

int main() {     
   addnum (5,5); 
   addnum (5,2,8); 
   return 0; 
} 

void addnum (int x, int y) {     
   cout<<"Integer number: "<<x+y<<endl; 
} 

void addnum (int x, int y, int z) {     
   cout<<"Float number: "<<x+y+z<<endl; 
}

It will produce the following output −

Integer number: 10 
Float number: 15 

Function Overloading in Erlang

The following example shows how to perform function overloading in Erlang, which is a functional programming language −

-module(helloworld).  
-export([addnum/2,addnum/3,start/0]).   

addnum(X,Y) ->  
   Z = X+Y,  
   io:fwrite("~w~n",[Z]).  
    
addnum(X,Y,Z) ->  
   A = X+Y+Z,  
   io:fwrite("~w~n",[A]).  
  
start() ->
   addnum(5,5),     addnum(5,2,8). 

It will produce the following output −

10 
15 
Advertisements