DEV Community

Loading Blocks
Loading Blocks

Posted on

Solidity Constructor

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

  1. Initialize state variables, like owner = msg.sender.
  2. Do one-time setup logic when contract is created.
  3. 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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)