Day 22 - Multi-level Inheritance

envoy_

Vedant Chainani

Posted on June 19, 2022

Day 22 - Multi-level 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 22 of 30 in Solidity Series
Today I Learned About Multi-level Inheritance in Solidity.

Multi-level Inheritance

It is very similar to single inheritance, but the difference is that it has levels of the relationship between the parent and the child. The child contract derived from a parent also acts as a parent for the contract which is derived from it.

Example: In the below example, contract A is inherited by contract B, contract B is inherited by contract C, to demonstrate Multi-level Inheritance.

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

// Defining parent contract A
contract A {
    string internal x;
    string a = "Multi";
    string b = "Level";

    // Defining external function to return concatenated string
    function getA() external {
        x = string(abi.encodePacked(a, b));
    }
}

// Defining child contract B inheriting parent contract A
contract B is A {
    string public y;
    string c = "Inheritance";

    // Defining external function to return concatenated string
    function getB() external payable returns (string memory) {
        y = string(abi.encodePacked(x, c));
    }
}

// Defining child contract C inheriting parent contract A
contract C is B {
    function getC() external view returns (string memory) {
        return y;
    }
}

// Defining calling contract
contract caller {
    // Creating object of child C
    C cc = new C();

    // Defining public function to return final concatenated string
    function testInheritance() public returns (string memory) {
        cc.getA();
        cc.getB();
        return cc.getC();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

when we call the testInheritance function, the output is "MultiLevelInheritance".


💖 💪 🙅 🚩
envoy_
Vedant Chainani

Posted on June 19, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Day 30 - Polymorphism
100daysofcode Day 30 - Polymorphism

August 3, 2022

Day 28 - Abstract Contract and Interface
100daysofcode Day 28 - Abstract Contract and Interface

July 31, 2022

Day 27 - Libraries
100daysofcode Day 27 - Libraries

July 30, 2022

Day 26 - Events and Hashing
100daysofcode Day 26 - Events and Hashing

July 29, 2022

Day 25 - Fallback and receive Functions
100daysofcode Day 25 - Fallback and receive Functions

June 22, 2022