Constructor

The constructor is a function that is executed when a contract is created. It cannot be called explicitly and is invoked only once during its lifetime. Every contract can have exactly one constructor and if no constructor is declared, the contract will use the default constructor.

  1. Create a constructor in solidity using the constructor keyword:
contract A {
constructor() {
// Constructor
}
}
  1.  Then, write some logic that should get executed during contract creation inside the constructor:
contract A {
address owner;

constructor() {
owner = msg.sender;
}
}
  1.  Now, decorate the constructor as either public (default) or internal. A constructor set as internal causes the contract to be marked as abstract:
contract C {
uint n;

constructor(uint _n) internal {
n = _n;
}
}
  1. If there is no constructor specified, the contract will execute the default constructor:

contract X {
// Default constructor
constructor() public { }
}
  1.  Now, we can specify the base contract constructor parameters, if any, while inheriting. This can be done in two ways, during inheritance or as part of the constructor function:
contract A {
uint someValue;
constructor(uint _value) public {
someValue = _value;
}
}

contract B is A(10) {
// Base contract argument during inheritance
}

contract C is A {
constructor(uint _anotherValue) First(_anotherValue) public {
// Base contract argument in constructor
}
}

Creating a constructor with the same name as the contract is now deprecated. Starting from solidity version 0.4.22, the constructor keyword is available for creating a constructor.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.223.10