What are Constructors?

A constructor is a function in Solidity that contains initialization logic for state variables. It is invoked only when the smart contract is deployed, and cannot be invoked again.

If not defined explicitly, the compiler creates a default constructor. To declare a constructor, use the constructor keyword followed by the access specifier, which can be public or internal. A contract with an internal constructor is considered abstract and cannot be deployed.

When inheriting a contract, the child contract must provide the parent contract's constructor parameters. If the child contract doesn't, it's marked as abstract and not deployed. If no explicit constructor is defined, the default constructor will be called.

Key Points
  • A contract has a single constructor.
  • Executed once to initialize its state.
  • The final code, including public functions and code accessible through public functions, is deployed to the blockchain.
  • Constructors can be public or internal, and if no constructor is defined, a default constructor is present.
Video : Solidity Constructor
Resource File
Question / Answer

Constructors are very useful in a smart contract, a parameter value can be defined at the run time and can also restrict the method call. Constructor overloading is not supported in Solidity, it only allows one constructor at a time.

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