Solidity Constructor in contract with multiple arguments passing the data to inheritance contract hierarchy with examples.

Smart contracts are similar to classes and interfaces in typescript and java programming. Like any programming language, Solidity provides a constructor.

What is a constructor in Solidity?


constructor is an optional function declared in the contract using the constructor keyword. It contains code to change and initialize the state variables.

It is called automatically once the contract is created and starts executing in the blockchain.

How to declare a constructor?

constructor([optional-parameters]) access-modifier {

}

optional-parameters: parameters passed to a constructor. access-modifier: can be public or internal.

Important points:

Solidity Constructor example

Following is a contract example with multiple variations of the constructor declaration.

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;

contract ConstructorTest {
   constructor() public {}
}

An example of initializing a state variable in the constructor

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;

contract ConstructorTest {
    string name;

    constructor() public {
        name = "John";
    }

    function getName() public view returns (string memory) {
        return name;
    }
}