Return To CS 110 Home

Colour Theme   Font Size Options
 
   
   
   
Function Overloading

Function Overloading


Video Summary: https://youtu.be/xOVD3MIwES4


As you have seen, when you make a call to a function, you have to specify the datatype for the parameters (the input into the function) and the return (the output out of the function). However, sometimes you might want to accept multiple types of data, such as a sum function that can add two integers, an integer and a float, or two floats.

One way of handling this is to make multiple functions with the same name that take and return different datatypes. The compiler will automatically determine which function it should call based on which function call matches the input. This is called function overloading.

Consider the following example that takes a string input. It checks if there is a decimal and either converts it to an int or a float, then uses overloaded functions to output the type:


Exercise

For this exercise, you will create an overloaded sum function that will add either two integers or two floats together. For the sake of simplicity, you may assume that the inputs will always match (two integers or two floats, not one integer one float).

  1. Take two string inputs
  2. Determine if they are integers or floats
  3. Create an overloaded sum function to add them together
  4. Use the overloaded function to add the two inputs together

Solution