What is function overloading in Solidity?
What is a function?
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.
What is function overloading?
Object-oriented programming has a function overloading feature, which allows two or more functions to have the same name but distinct parameters.
Function overloading in Solidity
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.
Example
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);}}
Explanation
-
Line 3: We create a contract
samplewhich is used to understand the concept of function overloading. -
Lines 4 to 6: We create a function
getSumthat returns the sum of two numbers. -
Line 7 to 9: We create a function
getSumthat returns the sum of three numbers. Although both functions have the same name, we notice that the firstgetSumfunction 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
callSumWithTwoArgumentsthat returns the firstgetSumfunction where we passed two numbers as the parameter. -
Lines 13 to 15: We create a function
callSumWithThreeArgumentsthat returns the secondgetSumfunction where we passed three numbers as the parameter.