How to do it...

  1. Inherit contracts using the is keyword. The parent contract has to be imported or copied to the same file before inheriting:
contract A {
...
}

contract B is A {
...
}
  1. When a contract inherits from multiple contracts, only a single contract is created in the blockchain. The other code from all the base contracts is copied into the created contract.
  2. In inheritance, the final function will be invoked while calling it by name. Call the functions in the parent contract by explicitly specifying their names:
pragma solidity ^0.4.23;

contract A {

uint public value;

function changeValue() public {
value = 1;
}
}

contract B is A {

function changeValue() public {
value = 2;
}
}
  1. Access the functions from the base contract using the super keyword:
pragma solidity ^0.4.23;

/**
* First parent contract
*/
contract A {

uint public value;

function changeValue() public {
value = 1;
}
}

/**
* Second parent contract
*/
contract B {

uint public value;

function changeValue() public {
value = 2;
}
}

/**
* Contract which inherits 2 base contracts
*/
contract C is A, B {

function changeValue() public {
value = 3;
super.changeValue();
}
}
  1. Specify the constructor parameters of the base contract during inheritance or by using the constructor of the inheriting contract. It is recommended to use the first way if the constructor argument is a constant value. The second way has to be used if the constructor arguments of the parent depend on those inputs of the derived contract. If both methods are used simultaneously, the second way takes precedence:
pragma solidity ^0.4.23;

/**
* Parent contract
*/
contract A {

uint public value;

constructor(uint _value) public {
value = _value;
}
}

/**
* Constructor parameter is specified during inheritance
*/
contract B is A(1) {

constructor() public {
// ...
}
}

/**
* Constructor parameter is specified in the constructor
*/
contract C is A {

constructor() A(10) public {
// ...
}
}
  1. The inheritance order in which the base classes are given is important. It helps in avoiding the diamond problem. It is recommended to inherit in the order of most basic to most derived.

The diamond problem is an ambiguity that arises when two contracts, B and C, inherit from A and override a method. Contract D inherits from both B and C, and D does not override it. So, which version of the method does D inherit, B or C?
..................Content has been hidden....................

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