Definition
Constructor is a special function.
Every contract can only have one constructor.
Execution
- Constructor is executed only one time when contract is deployed.
- It cannot be called again after deployment.
- Every contract has at most one constructor.
Core Use
- Initialize state variables, like
owner = msg.sender
. - Do one-time setup logic when contract is created.
- Very important in Ownable Pattern, since it decide the first owner of the contract.
Example
constructor() {
// default constructor, no parameter
}
constructor(address _owner) {
owner = _owner; // assign owner from argument
}
owner = msg.sender; // assign contract deployer as owner
Top comments (0)