Hierarchical Inheritance

Hierarchical Inheritance is another type of inheritance in Solidity that allows a child contract to inherit from multiple parent contracts. In this type of inheritance, there is a single parent contract that acts as a base contract and the child contract inherits from it, while other parent contracts inherit from this base contract.

Example

pragma solidity ^0.8.0;

// Base contract
contract Animal {
    string public animalType;

    constructor(string memory _animalType) {
        animalType = _animalType;
    }

    function speak() public virtual returns (string memory);
}

// Child contract that inherits from the Animal contract
contract Cat is Animal {
    constructor() Animal("Cat") {}

    function speak() public override returns (string memory) {
        return "Meow";
    }
}

// Another child contract that inherits from the Animal contract
contract Dog is Animal {
    constructor() Animal("Dog") {}

    function speak() public override returns (string memory) {
        return "Woof";
    }
}

// Child contract that inherits from both the Cat and Dog contracts
contract CatDog is Cat, Dog {
    constructor() Cat() Dog() {}

    // Override speak function from Animal contract
    function speak() public override(Cat, Dog) returns (string memory) {
        string memory catSpeak = Cat.speak();
        string memory dogSpeak = Dog.speak();
        return string(abi.encodePacked(catSpeak, " ", dogSpeak));
    }
}

In this example, the Animal contract acts as the base contract, while the Cat and Dog contracts inherit from it. The CatDog contract then inherits from both the Cat and Dog contracts, allowing it to access functions and variables from both parent contracts. The speak function is overridden in the CatDog contract to return the combined output of both the Cat and Dog speak functions.

Last updated