89DEVs

Constructor in Solidity

constructor in solidityA constructor is declared by using the constructor keyword. It is a special function in Solidity. The constructor function is called once, when the contract is deployed to the blockchain. Constructors are commonly used to initialize state variables. 

The constructor is optional but a contract can only have one constructor, if multiple constructors are declared an DeclarationError is raised. A constructor can not be overloaded and if no constructor is defined a default constructor is used for the contract.

A constructor can accept arguments but it is optional. The arguments are passed during the deployment of the contract and can be used to initialize the state variables in the contract.

constructors are magic methods that run only once

initialize state variables

In this example the constructor is used to initialize the state variable exampleStateVariable. It is also possible to pass arguments to the constructor and then use the arguments to initialize the state variables. (see next section) // SPDX-License-Identifier: MIT pragma solidity ^0.8; contract ExampleConstructor { uint public exampleStateVariable; constructor() { // initialize state variable exampleStateVariable = 123; } } Learn more about: state variables in Solidity.

arguments for constructors

Like any other function the constructor can accept arguments. The arguments are passed in when the contract is deployed and can be used to set the state variables. // SPDX-License-Identifier: MIT pragma solidity ^0.8; contract ExampleConstructor { uint public exampleStateVariable; constructor(uint _a) { // set state variable to argument value exampleStateVariable = _a; } } If we have declared a constructor with arguments, we can pass the arguments in the remix IDE before deployment. After deploying the contract we can check the value of the state variable and it is the same value we have set. constructor arguments in remix

payable constructor

A constructor can be marked as payable in Solidity. This is done using the payable keyword and enables the constructor to accept Ether. contract payableConstructor { constructor() payable { // payable constructor } } In the Remix IDE of the deploy button will change to red for any contracts with a payable constructor. payable constructor in remix with red deploy button

        

Summary

Click to jump to section