Constructor in Solidity

Constructor in Solidity

A constructor is an instance method that usually has the same name as the contract or use constructor keyword, and can be used to set the values of the variable of contract, either to default or to user-defined values.

Below is one of the example of constructor where we define constructor based upon contract name but this is depreciated now.

pragma solidity ^0.4.0;
contract member{
string name;
uint age;
function member (string _name, uint _age) public{
name=_name;
age=_age;
}
}

With latest version of solidity, constructor defined using constructor keyword as shown below.

pragma solidity ^0.4.0;
contract member{
string name;
uint age;
constructor(string _name, uint _age){
name=_name;
age=_age;
}
}

Constructor can be invoked/used by following ways.

Hard code constructor parameters: Here hard code values passed to contract constructor as shown below.

pragma solidity ^ 0.4.20;

contract member{
string name;
uint age;
constructor (string _name, uint _age) public{
name=_name;
age=_age;
}
}

contract teacher is member ("Vikas",32) {
function getName() public returns(string){
return name;
}
}

Pass parameter values at run time: Here parameter values are passed at run time as shown below.

 

pragma solidity ^ 0.4.20;

contract member{
string name;
uint age;
constructor (string _name, uint _age) public{
name=_name;
age=_age;
}
}

contract teacher is member {
constructor(string _N, uint _a) member(_N, _a) public{}
function getName() public returns(string){
return name;
}
}

 

Also a constructor set as internal causes the contract to be marked as abstract.

No Comments

Post a Reply

Inquire Now
close slider