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:
- Constructor declaration is optional
- The contract contains only one constructor declaration
- Overloading constructor is not supported
- if the constructor is not defined, the default constructor is used.
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;
}
}
Constructor Inheritance
Like classes, Constructors are also used in the inheritance hierarchy Here, Let’s see constructor examples of how to do
- pass data in the contract inheritance hierarchy
- Constructor inheritance Order execution
Let’s declare the base contract
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
contract Parent {
string name;
constructor(string memory _name) {
name = _name;
}
}
Parent or base contractor is defined with constructor arguments.
Now, declare the child contract by extending the parent constructor.
There are two ways data can be passed
One way is passing data with an inheritance contract
contract Child1 is Parent ("child1") {
constructor() {}
}
Another way, calling the parent constructor with data in the child constructor.
contract Child2 is Parent {
constructor(string memory _name) Parent( _name) {
}
}
Next, let’s the order of execution
parent constructor always executed in the declaration inheritance order
contract Child2 is Parent {
}
Order execution is
Parent
child2
One more example,
contract Child2 is Parent3,Parent1,Parent2 {
}
Inheritance Order of execution
Parent3
Parent1
Parent2
Child2
Notes:
if the child contract is not passing the data to the parent constructor, the Child contract is assumed as an abstract contract.