Skip to main content

Command Palette

Search for a command to run...

Constructor

Published
2 min readView as Markdown
Constructor

Constructor in Solidity

  1. In Solidity, a constructor is a special function that is executed only once during the creation of a contract. It is used to initialize the state variables of the contract and perform any other setup that is necessary for the contract to function correctly.

  2. The constructor function has the same name as the contract and is defined using the constructor keyword. It can take arguments, which are passed in when the contract is deployed to the blockchain.

    Here's an example of how a constructor can be used:

     contract MyContract {
         uint public myNumber;
         address public myAddress;
    
         constructor(uint number, address addr) {
             myNumber = number;
             myAddress = addr;
         }
    
         // rest of the contract code
     }
    
    1. In this example, the MyContract contract has a constructor that takes two arguments: a uint value and an address.

    2. When the contract is deployed to the blockchain, the constructor is called with the arguments passed in, and the myNumber and myAddress variables are initialized with these values.

    3. It's important to note that the constructor is executed only once during the lifetime of the contract, when the contract is first deployed to the blockchain. After that, the constructor is not executed again, and changes to the state variables must be made through the regular functions of the contract.

    4. The constructor is used to determine who is the owner of the contract.

    5. As is the executed only once when the contract is deployed on the blockchain network.

Also, it's worth noting that a contract can have only one constructor, and it must have the same name as the contract. If a contract does not have a constructor, a default constructor is provided by the Solidity compiler, which initializes all the state variables to their default values.

More from this blog