DEV Community

MOYED
MOYED

Posted on

Points to remember about inheritance

Override

Explicit override

When contract inherits from multiple parents, and overrides the same name functions, we need to explicitly override it.

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.9.0;

contract Base1
{
    function foo() virtual public {}
}

contract Base2
{
    function foo() virtual public {}
}

contract Inherited is Base1, Base2
{
    // Derives from multiple bases defining foo(), so we must explicitly
    // override it
    function foo() public override(Base1, Base2) {}
}
Enter fullscreen mode Exit fullscreen mode

State variable override external function

If parameter and return types match getter function of variable.

  • Only functions, modifiers can be overrided.
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.9.0;

contract A
{
    function f() external view virtual returns(uint) { return 5; }
}

contract B is A
{
    uint public override f;
}
Enter fullscreen mode Exit fullscreen mode

Constructor

There’s two ways for child contract to specify arguments of parent constructor.

Directly specify in inheritance list

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;

contract Base {
    uint x;
    constructor(uint _x) { x = _x; }
}

// Either directly specify in the inheritance list...
contract Derived1 is Base(7) {
    constructor() {}
}
Enter fullscreen mode Exit fullscreen mode

Through modifier form

// or through a "modifier" of the derived constructor.
contract Derived2 is Base {
    constructor(uint _y) Base(_y * _y) {}
}
Enter fullscreen mode Exit fullscreen mode

Super

In multiple inheritance, parent contracts are searched from right to left

So, super calls the right-most contract.

Additionally, inheritance must be ordered from most base-like to most derived.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

contract A {
    function foo() public pure virtual returns (string memory) {
        return "A";
    }
}
// Contracts inherit other contracts by using the keyword 'is'.
contract B is A {
    // Override A.foo()
    function foo() public pure virtual override returns (string memory) {
        return "B";
    }
}
contract C is A {
    // Override A.foo()
    function foo() public pure virtual override returns (string memory) {
        return "C";
    }
}
contract D is B, C {
    // D.foo() returns "C"
    // since C is the right most parent contract with function foo()
    function foo() public pure override(B, C) returns (string memory) {
        return super.foo();
    }
}
contract E is C, B {
    // E.foo() returns "B"
    // since B is the right most parent contract with function foo()
    function foo() public pure override(C, B) returns (string memory) {
        return super.foo();
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)