## DEV Community is a community of 892,765 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Vedant Chainani

Posted on • Updated on

# Day 23 - Hierarchical Inheritance

## 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;
}
}
``````
``````// 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;
}
}
``````
``````// 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;
}
}
``````
``````// 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());
}
}
``````

Output:

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