DEV Community

Cover image for Day 23 - Hierarchical Inheritance
Vedant Chainani
Vedant Chainani

Posted on • Updated on

Day 23 - Hierarchical Inheritance

GitHub logo Envoy-VC / 30-Days-of-Solidity

30 Days of Solidity step-by-step guide to learn Smart Contract Development.

This is Day 23 of 30 in Solidity Series
Today I Learned About Hierarchical Inheritance in Solidity.

Hierarchical Inheritance

In Hierarchical inheritance, a parent contract has more than one child contracts. It is mostly used when a common functionality is to be used in different places.

Example: In the below example, contract A is inherited by contract B, contract A is inherited by contract C, thus demonstrating Hierarchical Inheritance.

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

// Defining parent contract A
contract A {
    string internal x;

    function getA() external {
        x = "Hierarchical Inheritance";
    }

    uint256 internal sum;

    function setA() external {
        uint256 a = 10;
        uint256 b = 20;
        sum = a + b;
    }
}
Enter fullscreen mode Exit fullscreen mode
// Defining child contract B inheriting parent contract A
contract B is A {
    // Defining external function to return state variable x
    function getAstr() external view returns (string memory) {
        return x;
    }
}
Enter fullscreen mode Exit fullscreen mode
// Defining child contract C inheriting parent contract A
contract C is A {
    // Defining external function to return state variable sum
    function getAValue() external view returns (uint256) {
        return sum;
    }
}
Enter fullscreen mode Exit fullscreen mode
// Defining calling contract
contract caller {
    // Creating object of contract B
    B contractB = new B();

    // Creating object of contract C
    C contractC = new C();

    // Defining public function to
    // return values of state variables
    // x and sum
    function testInheritance() public view returns (string memory, uint256) {
        return (contractB.getAstr(), contractC.getAValue());
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

when we call the testInheritance function, the output is ("Hierarchical Inheritance", 30).


Top comments (0)