Constructor
A constructor is a special type of function that is automatically called when the contract is created. Constructors are typically used to set up initial state variables and any other setup that needs to happen when the contract is first deployed.
The code defined inside the constructor will run only once, at the time the contract is created.
In this example, the constructor takes in a uint and sets it to the contract's x state variable.
Deployment
After the constructor has executed, the final bytecode of the contract is stored on the blockchain.
The deployed bytecode does not contain the constructor code, or internal functions only called from the constructor.
The bytecode includes all public and external functions and all functions that are reachable from there through function calls.
The constructor code is part of the creation code, not part of the runtime code.
Inheritance
If a base contract has arguments, derived contracts need to specify all of them. This can be done in two ways:
1. Directly in the inheritance declaration
2. Through the derived constructor
This way can be used if the constructor arguments of the base contract depend on those of the derived contract.
Payable Constructor
Constructors can accept Ether. In this case, they should be declared with the keyword “payable”.
If you try to add ether when deploying a contract defined with a non payable constructor, it will throw you an exception and revert.
The difference between a payable and non payable constructor is also reflected in the creation code.
If the constructor is non-payable, the creation code contains 8 low-levels instructions (in EVM assembly), that check if some ethers has been sent to the contract once it has been deployed. If it is the case, the check fails and the contract reverts.
Last updated