2

As a matter of fact, there is more than one discussion about what are the call you can safely do in the constructor.

Someone thinks “avoid all external call”, some other says “avoid to use ‘this’ or address(this)” in the constructor, other are concerned about using ‘this’ after a ‘new’, other want to introduce warning and errors for the ‘this’ use and so on.

On GitHub/Ethereum do exist pages and pages about this, but true conclusions lack.

What is the recommended practice in Solidity? Does exist any list/cheat sheet about that?

EDIT: added some examples of such discussions as per smarx suggestion

https://github.com/ethereum/solidity/issues/583

https://github.com/ethereum/solidity/pull/3875

https://github.com/ethereum/solidity/issues/3843

https://github.com/ethereum/solidity/issues/3861

https://github.com/ethereum/solidity/pull/1646#issuecomment-305026348

  • 1
    It would help if you would link to where you read those things. – smarx Dec 12 '18 at 8:02
  • You are right, I’ll do ASAP – Rick Park Dec 12 '18 at 8:03
3

In a Solidity constructor:

  • this is the address of the contract that is being constructed. (even after using new or calling an external function of another contract)

  • msg.sender is the address of whoever or whatever is deploying the contract. (user account or another contract using new)

  • You cannot call external functions on a contract that is being constructed (e.g. this.foo(); inside the constructor function will revert the contract creation transaction)

  • You can call internal functions of the contract that is being constructed. Inside that internal function, this and msg.sender will have the same values they did in the constructor.

In a constructor, you can safely deploy new contracts or call external functions on other contracts that have already been constructed.

Some of the confusion in the discussions you linked is based on this.foo(); in the constructor function silently failing. This is no longer the case.

  • 1
    Thank you. This kind of operative answer is very useful here. May be we can add something about the needing to use () on modifiers without arguments used in constructor? Is it still needed? – Rick Park Dec 12 '18 at 9:05
  • @RickPark You don't need to add () to a modifier with 0 arguments when using it on the constructor or on a function. However, you can if you want to. It's optional now – Jesse Busman Dec 12 '18 at 9:11
  • I refer to this: github.com/ethereum/solidity/pull/3853 – Rick Park Dec 12 '18 at 9:17
  • @RickPark Yes, the () for a base constructor call without arguments is also optional, just like modifiers. The base constructor will be executed the same way in both cases, with or without the () – Jesse Busman Dec 12 '18 at 9:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.