Inheritance in Solidity
virtual invites an override; super reaches the parent.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
// virtual invites an override; super reaches the parent's code.
contract Gate {
event Opened(address by);
function open() public virtual {
emit Opened(msg.sender);
}
}
contract LockedGate is Gate {
bool public unlocked;
function unlock() external {
unlocked = true;
}
function open() public override {
require(unlocked, "locked");
super.open();
}
}
How it works
function open() public virtualmay be replaced.overrideis mandatory spelling on the replacement.super.open()still runs the parent's logging.
Keywords and builtins used here
addressboolcontractemiteventexternalfunctionispublicrequiretrue
The run, in numbers
- Lines
- 24
- Characters to type
- 411
- Tokens
- 73
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 73 seconds.
Step 1 of 4 in Composition, step 17 of 28 in Language basics.