BudiBadu Logo
Samplebadu

Solidity by Example: Inheritance

0.8.x

Object-oriented programming in Solidity with this sample code covering contract inheritance using the is keyword, virtual functions allowing overrides, the override keyword for replacing parent implementations, and super for calling parent contract functions.

Code

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract A {
    // virtual allows the function to be overridden
    function foo() public pure virtual returns (string memory) {
        return "A";
    }
}

contract B {
    function foo() public pure virtual returns (string memory) {
        return "B";
    }
}

// C inherits from both A and B
contract C is A, B {
    // Must override because both parents define foo()
    function foo() public pure override(A, B) returns (string memory) {
        return super.foo(); // Calls B's foo because B is listed last
    }
}

Explanation

Solidity supports multiple inheritance using the is keyword, allowing contracts to inherit state variables and functions from parent contracts. When inheriting from multiple parents, the order matters and should follow the principle of "most base-like to most derived" (linearization). This inheritance model enables code reuse and the creation of modular, composable contract systems.

To allow a function to be overridden by child contracts, it must be marked as virtual. The child contract must then use the override keyword to explicitly indicate it's replacing the parent's implementation. If inheriting from multiple parents that share a function name, you must specify all parents in the override declaration, such as override(A, B). This explicit syntax prevents ambiguity and makes inheritance relationships clear.

The super keyword allows calling functions from parent contracts. In multiple inheritance scenarios, super follows the C3 linearization algorithm to determine which parent function to call, based on the inheritance order. This enables sophisticated patterns like calling all parent constructors or implementing the Template Method pattern where child contracts extend parent behavior.

Code Breakdown

6
virtual keyword allows child contracts to override this function.
18
contract C is A, B establishes multiple inheritance from A and B.
20
override(A, B) explicitly resolves the conflict between parent functions.
21
super.foo() calls B's implementation due to C3 linearization order.