Learn how to create constructor in Solidity.

In typical object-oriented programming languages, a constructor is a specific method invoked whenever an object of a class is created. On the other hand, Solidity introduces a constructor declaration within smart contracts, initializing the contract’s state and executing only once upon deployment. The compiler generates a default constructor if a constructor is not explicitly defined.

Characteristics of a constructor

Here are the characteristics associated with a constructor:

  • A contract can have only one constructor.

  • Upon contract creation, the constructor function runs to initialize the contract’s state.

  • There are two types of constructors: internal and public.

  • After the constructor executes, the code is published to the blockchain. This includes public functions and the code accessible through them.

  • An internal constructor designates the contract as abstract.

Creating a constructor

The constructor keyword is used to specify a constructor, followed by an Access_modifier placeholder. It’s an optional function that initializes the contract’s state variables. The syntax is as follows:

Get hands-on with 1200+ tech skills courses.