typestar

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

  1. function open() public virtual may be replaced.
  2. override is mandatory spelling on the replacement.
  3. super.open() still runs the parent's logging.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 4 in Composition, step 17 of 28 in Language basics.

← Previous Next →

Inheritance in other languages