Loading...
Constructors is a special type of function in the program, this common thing we all are seeing so far with other programming languages.But in solidity constructor has some different meaning.
Constructor can be declare inside the smart contract and it is invoked only once while deploying it.
If their is no constructor in contract defined by user then solidity compiler creates default constructor for it.
Constructors can be either public or internal.
constructor (arg,...)<access modifier>{
}
We can pass parameters to constructors via hardcode or runtime.
Let's see simple example
pragma solidity ^0.8.0;
contract Con{
uint public a;
uint public b;
constructor (uint _a,uint _b) public {
a=_a;
b=_b;
}
function getCon() public view returns(uint,uint){
return (a,b);
}
}
While deploying the contract we have to pass the parameters to constructors(for a and b).
_A:"1"
_B:"2"
After deploying above contract call the getCon()function and you will get values that you have passed.
Output:
0:uint256: 1
1:uint256: 2
But this is not the perfect use case of the constructor in the solidity.
Constructors are very useful to make restrictions for calling some functions.
Lets extend above example by giving authority to modify the values of variables only for specified user address.
pragma solidity ^0.8.0;
contract Con{
uint public a;
uint public b;
address private owner=0x5B38Da6a701c568545dCfcB03FcB875f56beddC4;
constructor (uint _a,uint _b)public{
if(msg.sender==owner)
{
a=_a;
b=_b;
}
}
function getCon() public view returns(uint,uint){
return (a,b);
}
}
While deploying i have used the same address which i have mentioned in code and passed values as 1,2.
Output:
0:uint256: 1
1:uint256: 2
It will not going to show any error if you deploy it through different address,at the same time you will not get values that we passed.
Let's see simple example of inheritance using constructors.
pragma solidity ^0.8.0;
contract A {
string public a;
constructor(string memory _a) public {
a = _a;
}
}
contract B is A("This is ContractB") {
}
//you can choose any one from above or below
contract B is A{
constructor(string memory _a) A(_a)public{
}
}
Output:
0:string: This is ContractB
Note: When a derived contract doesn't include arguments for base constructor contract then contract becomes abstract.
That's it for now.:)