Constructor in Solidity smart contracts

Ledger Nano X - The secure hardware wallet

A constructor in Solidity is a special function that is used to initialize state variables in a contract. The constructor is called when an contract is first created and can be used to set initial values.

  • Constructors are an optional function
  • In case, no constructor is defined, a default constructor is present in the contract
  • The constructor is executed one time when the contract is first created and does not run again
  • A constructor can be either public or internal.

When to use a constructor

When a contract is created on the block chain you can use the constructor to set state variables. For example when deploying your contract you can set:  

  • Contract Owner – you can set the owner address at creation time
  • Max amount – set the maximum amount of a token
  • True or false values
  • Any parameter that you want to save
  • etc.

If you do not implement a function to change the state variable it will remain as long as the block chain is running. So using a constructor is a way to set a state variable that you do not want to change.

How to create a constructor in Solidity

A constructor is declared using the constructor keyword. These functions can be public or internal. If a constructor is not specified the contract will assume the default constructor which is equivalent to constructor() public {}. The constructor is executed when the contract is created on the blockchain.

pragma solidity ^0.8.0;

contract A {
    uint public a;

    //when creating this contract _a is passed in a a parameter
    //and sets the variable a
    constructor(uint _a) internal {
        a = _a;
    }
}

Try it in Remix

A constructor specified as internal causes the contract to be marked as abstract. Contracts identified as abstract occurs when at least one of their functions lacks an implementation. Abstract contracts are used as a base contract. An abstract contract contains both implemented as well as abstract functions.

As an example a constructor can be used to set the owner of a contract. For more information read the docs. See the example below:

uint public x;
uint public y;
address public owner;
uint public createdAt;

//use the constructor below to set variables at time of deployment
//pass in a value for x and y into the constructor to set the state variable
//the owner of the contract is the msg.sender (the contract creator)
//the createdAt state variable will contain the block time stamp at when the constructor was created
Constructor (uint _x, uint _y) public {
            x=_x;
            y=_y;
            owner = msg.sender;
            createdAt = block.timestamp;

Try it in Remix

Click here for more information about how to use the Ethereum test network and how to obtain test ETH.

Next Review – State Variables in Solidity smart contracts

Leave a Reply