In multilevel inheritance a contract inherits from a contract that itself inherits from another (A → B → C); in Solidity this is written with the is keyword.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Level 1: base contract
contract A {
uint internal a;
function setA(uint _a) public {
a = _a;
}
function getA() public view returns (uint) {
return a;
}
}
// Level 2: B inherits A
contract B is A {
uint internal b;
function setB(uint _b) public {
b = _b;
}
function getB() public view returns (uint) {
return b;
}
}
// Level 3: C inherits B (and therefore A)
contract C is B {
function sum() public view returns (uint) {
return a + b; // uses variables from A and B
}
}
How it works
B is Agives B all public and internal members of A.C is Bgives C the members of both B and A, so C can readaandbdirectly (they areinternal, which allows access in derived contracts but not from outside).- Only contract C needs to be deployed; its bytecode contains the code of all three levels.
Testing in Remix: deploy C, call setA(10) and setB(20), then sum() returns 30; getA() and getB() return 10 and 20.
To change inherited behaviour, mark the base function virtual and the derived one override.