function overloading code example

Example 1: c++ function overload

/*A function over load in c++ is when you take a function with the same definition but change the input variables.
  This can include multiple functions with the same name see below
  */
#include <iostream>
using namespace std;

int function1(int var1){//example of single variable
	//do somthing
}
int function1(int var1,int var2){//of overload
	//do somthing	
}
int function1(int var1,string var3){//of overload
	//do somthing	
}

int main(){
 
  cout << "Hello World" << endl;
  function1(4);
  function1(3,-90);
  function1(34,"it works");//these should all work even tho they have different input variables
  return 0;
}

Example 2: What's method overloading

Overloading mean same method name and different parameter, 
it can happen in same class. it's a feature that 
allows us to have more than one method with same name.

Example: sort method of Arrays class
Arrays.sort(int[] arr)
Arrays.sort(String[] arr)
....
Method overloading improves the reusability and readability. 
and it's easy to remember 
(one method name instead of remembering multiple method names)

Example 3: method overloading

//https://www.geeksforgeeks.org/overloading-in-java/
// Java program to demonstrate working of method
// overloading in Java. 
  
public class Sum { 
  
    // Overloaded sum(). This sum takes two int parameters 
    public int sum(int x, int y) 
    { 
        return (x + y); 
    } 
  
    // Overloaded sum(). This sum takes three int parameters 
    public int sum(int x, int y, int z) 
    { 
        return (x + y + z); 
    } 
  
    // Overloaded sum(). This sum takes two double parameters 
    public double sum(double x, double y) 
    { 
        return (x + y); 
    } 
  
    // Driver code 
    public static void main(String args[]) 
    { 
        Sum s = new Sum(); 
        System.out.println(s.sum(10, 20)); 
        System.out.println(s.sum(10, 20, 30)); 
        System.out.println(s.sum(10.5, 20.5)); 
    } 
}

Tags: