When creating a Solidity smart contract, we can declare a special function called a constructor. A constructor contains the initialization logic of state variables.
In other object-oriented programming languages, a constructor is invoked whenever an object of a class is instantiated. A constructor can be invoked only when the smart contract is deployed in Solidity. After it’s deployed, there is no way to invoke the constructor again.
If a constructor is not defined explicitly, the compiler will create a default
constructor.
To declare a constructor, we use the constructor
keyword followed by the access specifier. Inside the {}
brackets, we add the initialization logic.
A constructor’s access specifier can be public
or internal
. A contract with an internal constructor is marked as abstract
and cannot be deployed.
constructor() <access-specifier> {// code}
In the previous version of Solidity (^0.4.*), in order to declare a constructor, we defined a function with the same name as the constructor. But we don’t use it anymore because it’s deprecated.
Let’s see an example of a constructor in Solidity.
pragma solidity ^0.5.0;contract Example {// declare a state variableuint _a;// create a constructor to initialize _aconstructor (uint a) public {_a = a;}// getter function to get value of _afunction getA() public view returns(uint){return _a;}}
Example
._a
._a
.getA
to retrieve the value of _a
.While inheriting a contract, if the parent contract has a constructor with some parameters, the child contract needs to provide those same parameters. If the child contract doesn’t pass the required parameters to the parent contract’s constructor, it will be marked as abstract
and will not be deployed.
If no explicit constructor is defined in the parent contract, its default constructor will be called.
constructor () <parent-contractName>() <access-specifier>{// code}
Let’s see an example of constructor inheritance.
pragma solidity ^0.5.0;contract ParentContract {// declare a state variableuint _a;// create a constructorconstructor (uint a) internal {_a = a;}// getter function to get value of _afunction getA() public view returns(uint){return _a;}}// inherit ParentContractcontract ChildContract is ParentContract {// declare a state variableuint _b;// create a constructor and call parent constructorconstructor (uint a, uint b) ParentContract(a) public {_b = b;}// getter function to get value of _bfunction getB() public view returns(uint){return _b;}}
ParentContract
._a
._a
.getA()
to retrieve the value of _a
.ChildContract
from ParentContract
._b
._b
. We also call the constructor of the parent contract and pass the required parameter.getB()
to retrieve the value of _b
.RELATED TAGS
CONTRIBUTOR