Solidity Multiple Inheritance
Multiple inheritance lets one contract inherit from more than one parent contract. The child gains the functions and state of every parent it lists.
One child gains two parents' functions
Robot inherits from Steps and Words. It can walk and speak.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract Steps {
uint256 public steps;
function walk() public {
steps += 1;
}
}
contract Words {
uint256 public words;
function speak() public {
words += 1;
}
}
contract Robot is Steps, Words {
}A shared function is overridden once
Both parents define greet. The child overrides it once and names both parents.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract GreeterA {
function greet() public pure virtual returns (string memory) {
return "A";
}
}
contract GreeterB {
function greet() public pure virtual returns (string memory) {
return "B";
}
}
contract Greeter is GreeterA, GreeterB {
function greet() public pure override(GreeterA, GreeterB) returns (string memory) {
return string.concat("A", " and ", "B");
}
}The child also inherits both parents' state
Left holds 3 and Right holds 4. Total reads both and adds them.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract Left {
uint256 public left = 3;
}
contract Right {
uint256 public right = 4;
}
contract Total is Left, Right {
function total() public view returns (uint256) {
return left + right;
}
}Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract Named {
string public name;
function setName(string memory newName) public {
name = newName;
}
}
contract Counted {
uint256 public count;
function bump() public {
count += 1;
}
}
contract Pet is Named, Counted {
function describe() public view returns (string memory, uint256) {
return (name, count);
}
}Key points
- Parent list: A child lists each parent after is, with the most-base-like parent first.
- Shared functions: A function defined in several parents must be overridden once in the child.
- Override list: The child marks such a function override(A, B) with every parent that defines it.
- Virtual parents: A parent function must be virtual before a child can replace it.
- State: The child also inherits each parent's state variables.
In this example, Named holds a name and Counted holds a count. Pet inherits from both parents. It gains setName from Named and bump from Counted. describe reads the two inherited values and returns them together.
Note
A child can call a parent function directly when only one parent defines it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Remix IDE
Exercise
Two parents both define greet. How does the child override it?