How to write constructor in Solidity version 0.4.22 and above.

Hideyoshi Moriya
1 min readMay 19, 2018

Up to Solidity 0.4.21

  • Up to Solidity 0.4.21, constructor can be defined by the same name of its contract name.
  • However, this can possibly cause unintended bugs when contracts are renamed and their constructors are not renamed.
  • In Solidity, “contract” is almost the same as “class” in ordinal programming language.

Example: Contract “Piyo”

  • A constructor name should be defined as the function which has the same name of the contract name “Piyo”.
pragma solidity 0.4.21;

contract Piyo {
string public message;

// Constructor
function Piyo(string _message) public {
message = _message;
}

}

Solidity 0.4.22 and above

  • Use a constructor keyword and create an anonymous function
  • Not function constructor(args) {...} but constructor (args) {...} .

Example: Contract “Piyo”

  • A constructor should be defined by using aconstructor keyword.
pragma solidity 0.4.22;

contract Piyo {
string public message;
// Constructor
constructor (string _message) public {
message = _message;
}

}

Notes

  • In solidity version 0.4.22, a constructor can be defined with both the new and old way.
  • However, one of them can be used. This is possible to cause unintended bugs. In my experiment, a constructor which is called first is used.
  • This issue has been fixed in Solidity 0.4.23.

Support

If you find this article is helpful, it would be greatly appreciated if you could tip Ether to the address below. Thank you!

0x0089d53F703f7E0843953D48133f74cE247184c2

--

--