Member-only story
Solidity Tutorial : all about Constructors
This article covers constructors, a function in Solidity that runs only once, when the contract is deployed onto the Ethereum network.
Table of Contents
Introduction
How to define a constructor
Public vs Internal Constructors
Constructors’ parameters and inheritance
Payable Constructor
Introduction
Constructors are a common concept in OOP. In many programming languages, when defining classes, you can also define a magic method that will run once, at the time a new instance of the object is created.
In the case of Solidity, the code defined inside the constructor will run only once, at the time the contract is created and deployed in the network.
An important point to mention is the following:
The bytecode deployed on the network does not contain the constructor code, since the constructor code runs only once on deployment.
The constructor code is part of the creation code, not part of the runtime code.
How to define a constructor in Solidity?
You define a constructor in Solidity with the keyword constructor()
followed by parentheses. Note that you do not need to add thefunction
keyword, since it is a special function.
contract Example { constructor() {
// code running when contract deployed...
}}
NB: Prior to version 0.4.22 of Solidity, constructors were defined as functions with the same name as the contract (like in JAVA?). This syntax was deprecated and is not allowed anymore since version 0.5.0