Aren`t constructors used to initialize variable at the time of contract creation? In common patterns section in solidity documentation, payable constructor is used for withdrawal pattern example.

constructor() payable {
  richest = msg.sender;
  mostSent = msg.value;

What is the significance of this cant we hard code the value or initialize it with some other function?

2 Answers 2


payable means that you can transfer ether with the transaction. If the contract is designed that it needs an ether deposit on construction, then you can not hard code this. You have to allow the transaction sender to indeed send this ether to the contract.

  • 1
    But if I am deploying the contract why would i need ether for its creation? Can you suggest a use case? For instance I am creating a dapp and selling some collectibles, while creation of contract it doesnot make sense to to deposit the ether. Thanks Commented Mar 1, 2018 at 10:56
  • 4
    You don't have to, if this is not your usecase. You could have a separate function deposit() payable {..}. But there are usecases where you need this. Example could be an unidirectional payment channel, where you put some ether in escrow on the channel instantiation.
    – ivicaa
    Commented Mar 1, 2018 at 11:01
  • 2
    I'll give you an example. If you make a dapp where a user can send ether and bet on a number between 1-5 where he gets like 4.90x his money back when he's right you would need to preload the contract with Ether. If you don't the contract will throw when a user picks the right number on the first try as there will be no ether in the contract to pay the user.
    – Nico
    Commented Mar 1, 2018 at 11:17

I think this in another way. The significance of writing a constructor() as payable is that the address of sender must be bind-ed as owner and the best possible way is to do this by making constructor as payable.

If you don't have payable then there is no use of owner = msg.sender.

Here, we set the owner to msg.sender, which is a built-in global variable representative of the address that is calling the function.

  • How is this correct? You can also have msg.sender with msg.value = 0
    – Zommuter
    Commented May 5, 2023 at 13:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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