Inheritance
A contract can inherit from one or more other contracts with is. The child gets all non-private state variables, functions, modifiers and events of its parents, and the compiler produces one contract: inheritance copies code at compile time, it doesn't create separate deployed contracts.
contract Ownable { … }
contract Token is Ownable { … } // Token contains Ownable's codeInheritance is how most real contracts are built: you compose battle-tested building blocks such as Ownable, ERC20 and Pausable and add your own logic.
A basic example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Ownable {
address public owner;
constructor() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_;
}
}
contract Greeter is Ownable {
string public greeting = "Hello";
function setGreeting(string calldata g) external onlyOwner { // inherited modifier
greeting = g;
}
}
contract Main {
function main() external {
Greeter g = new Greeter();
console.log("owner is Main?", g.owner() == address(this)); // inherited getter
g.setGreeting("Bonjour");
console.log(g.greeting());
}
}owner is Main? true
Bonjour
Overriding functions: virtual and override
A parent marks a function virtual to allow children to change it; the child marks its version override. Both keywords are mandatory, so overriding is never accidental.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Animal {
function sound() public pure virtual returns (string memory) {
return "...";
}
function describe() public pure returns (string memory) {
return string.concat("It says ", sound()); // calls the most derived version
}
}
contract Dog is Animal {
function sound() public pure override returns (string memory) {
return "Woof";
}
}
contract Puppy is Dog {
// Dog.sound is not virtual, so Puppy cannot override it
}
contract Main {
function main() external {
console.log(new Animal().describe());
console.log(new Dog().describe());
console.log(new Puppy().describe());
}
}It says ...
It says Woof
It says Woof
describe() is defined in Animal, yet for a Dog it uses Dog.sound(): internal calls to a virtual function are dispatched to the most derived override. To let grandchildren override again, write override and virtual.
Calling the parent with super
super.f() calls the parent's version of f. That lets you extend behaviour instead of replacing it:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Account {
mapping(address => uint256) public balance;
function _deposit(address who, uint256 amount) internal virtual {
balance[who] += amount;
console.log("Account: credited", amount);
}
}
contract BonusAccount is Account {
function _deposit(address who, uint256 amount) internal override {
super._deposit(who, amount); // keep the original logic
if (amount >= 100) {
balance[who] += 5;
console.log("BonusAccount: +5 bonus");
}
}
function deposit(uint256 amount) external {
_deposit(msg.sender, amount);
}
}
contract Main {
function main() external {
BonusAccount acc = new BonusAccount();
acc.deposit(50);
acc.deposit(100);
console.log("balance:", acc.balance(address(this)));
}
}Account: credited 50
Account: credited 100
BonusAccount: +5 bonus
balance: 155
Parent constructors
Parent constructors run before the child's, from the most basic parent down. Arguments can be given in the inheritance list or in the child's constructor header:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Named {
string public name;
constructor(string memory name_) {
name = name_;
console.log("Named constructor:", name_);
}
}
contract Capped {
uint256 public cap;
constructor(uint256 cap_) {
cap = cap_;
console.log("Capped constructor:", cap_);
}
}
contract Club is Named("Robotics"), Capped { // fixed argument
constructor(uint256 seats) Capped(seats) { // argument from the child
console.log("Club constructor");
}
}
contract Main {
function main() external {
Club club = new Club(12);
console.log(club.name(), club.cap());
}
}Named constructor: Robotics
Capped constructor: 12
Club constructor
Robotics 12
Multiple inheritance and linearization
Solidity supports multiple inheritance. When two parents define the same function, the child must override it and list both: override(A, B). The order of parents in is matters: write them from most basic to most derived. Solidity computes a single chain (C3 linearization), and super follows that chain:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Base {
function hook() public virtual {
console.log("Base");
}
}
contract Logging is Base {
function hook() public virtual override {
console.log("Logging");
super.hook();
}
}
contract Metrics is Base {
function hook() public virtual override {
console.log("Metrics");
super.hook();
}
}
contract App is Logging, Metrics {
function hook() public override(Logging, Metrics) {
console.log("App");
super.hook();
}
}
contract Main {
function main() external {
new App().hook();
}
}App
Metrics
Logging
Base
The linearized order is App → Metrics → Logging → Base: the right-most parent is "closest" to the child. Each super.hook() moves one step along that chain, so Base runs once.
Test yourself
Which keywords are required to override a function?
overridein the parent andvirtualin the childvirtualin the parent andoverridein the child- Only
override superin the child
When C is A, B is deployed, how many contracts end up on chain?
- Three: A, B and C
- One: C, containing the inherited code
- Two: C and its first parent
- None until
superis called
In contract App is Logging, Metrics, which parent's function does super.hook() in App call first?
- Logging
- Metrics
- Base
- Both at once