Difference between internal and external functions in Solidity
Internal functions
Note: We can also assign an internal quantifier to the variables of the contract.
Code example
Let’s look at the code below:
pragma solidity ^0.5.0;contract ContractBase{//private state variableuint private data;//constructorconstructor() public{data = 80;}//internal functionfunction multiply(uint num1, uint num2) internal pure returns (uint){return num1 * num2;}}//inherited Contractcontract ContractDerived is ContractBase{uint private result;constructor() public {result=0;}function getResult() public returns(uint){result = multiply(55, 7);return result;}}
Code explanation
Here is a line-by-line explanation of the code above:
-
Line 3: We create a contract
ContractBase. -
Lines 15 – 18: We define the internal function
multiplyin theContractBasecontract to multiply two numbers and return its result. -
Line 22: We create a contract
ContractDerivedinherited fromContractBaseto test the internal function. -
Line 33: We call the internal function
multiplyof theContractBasecontract in the derived contractContractDerived.
External functions
Note:
- We can explicitly call the external function using
keyword within the contract. this It is the pointer pointing to the current contract. - We can assign an external quantifier only to functions but not the variable of the contract.
Code example
Let’s look at the code below:
pragma solidity ^0.5.0;contract ContractOne{//private state variableuint private data;//constructorconstructor() public{data = 70;}//external functionfunction multiply(uint num1, uint num2) external pure returns (uint){return num1 * num2;}}//external Contractcontract ExternalContract{uint private result;ContractOne private obj;constructor() public {obj = new ContractOne();}function getResult() public returns(uint){result = obj.multiply(70, 86);return result;}}
Code explanation
Here is a line-by-line explanation of the code above:
-
Line 3: We create a contract
ContractOne. -
Lines 15 – 18: We define the external function
multiplyin theContractOnecontract to multiply two numbers and return its result. -
Line 22: We create an external contract
ExternalContractto test the external function. -
Lines 25: We make a private state variable
objof typeContractOneto use its external functionmultiplyin the external contractExternalContract. -
Line 33: We call the external function
multiplyagainst theobjinExternalContract.
Free Resources