In one of question answer session, someone asked us how different is to invoke contract function from another contract in solidity from other programming languages and how we can do that.
How to call functions ?
We are writing this blog, in case you have same question and would like to know how we can call function defined in one contract from another contract. This is very common scenario where we do see requirement of function calls in solidity and there are different ways available for that.
Function call options
- Using new keyword (contractA = new contractA())
- Using contract address (contractA =contractA(address))
- Using call function
Before we jump to options, you need to well aware about some basics like whenever you deploy contract to blockchain, it gets deployed on one particular address and once it is deployed you can't change/modify that. In case you see some bug and need to fix that then your updated contract will get deployed on new address instead of same old address.
Using new keyword
In this approach, you create new instance of member contract where setAge() function is defined that you need to invoke from teacher contract. Important thing to note down here is that, you don't use address of member contract where it is deployed to access setAge() function rather create new instance in teacher contract and that will have separate address. This is explained more in detail in video.
Using contract address
In this approach, you access member contract from teacher contract using the address where it is deployed and then access setAge() function defined in that contract. Important thing to note down here is that, you use address of member contract so you need to have that address and need to supply that when you access setAge() function. This is explained more in detail in video.
Using call function
In this approach, you access member contract from teacher contract using the address where it is deployed but with call function. This is least preferred method and should not be used as it is going to be removed from solidity in future. This is explained more in detail in video.