A function is a logically ordered chunk of code that performs a specific purpose. Functions improve the modularity and reusability of a program. Depending on the programming language, a function is also known as a subroutine, process, routine, method, or subprogram.
Object-oriented programming has a function overloading feature, which allows two or more functions to have the same name but distinct parameters.
In Solidity, we can have many definitions for similar function names within the same scope. The kinds and number of arguments in the argument list must differ in the definition of the function. Function declarations that differ only in return type cannot be overloaded.
Let’s look at the code below:
pragma solidity ^0.5.12;contract sample {function getSum(uint a, uint b) public pure returns(uint){return a + b;}function getSum(uint a, uint b, uint c) public pure returns(uint){return a + b + c;}function callSumWithTwoArguments() public pure returns(uint){return getSum(4,9);}function callSumWithThreeArguments() public pure returns(uint){return getSum(1,4,7);}}
Line 3: We create a contract sample
which is used to understand the concept of function overloading.
Lines 4 to 6: We create a function getSum
that returns the sum of two numbers.
Line 7 to 9: We create a function getSum
that returns the sum of three numbers.
Although both functions have the same name, we notice that the first getSum
function returns the sum of two numbers while the second returns the sum of three numbers. Both functions take different parameters.
Lines 10 to 12: We create a function callSumWithTwoArguments
that returns the first getSum
function where we passed two numbers as the parameter.
Lines 13 to 15: We create a function callSumWithThreeArguments
that returns the second getSum
function where we passed three numbers as the parameter.