SolidityIn

Inheritance and interfaces

Lesson 25 of 40 · Practice

Inheritance lets one contract reuse the code of another. You write is after the contract name, and the child gets all the non-private functions and variables of the parent. Solidity supports multiple inheritance, so a contract can inherit from several parents.

A function can be changed in a child only if the parent marks it virtual and the child marks its version override. This is a safety feature that prevents accidental overriding. Call the parent's version with super.

With multiple parents the order matters. List them from the most general to the most specific, or the compiler refuses. Solidity uses a rule called C3 linearization to decide which function runs when several parents define the same one.

An abstract contract has at least one function without a body and cannot be deployed on its own. An interface is stricter: it has only function declarations, no state variables and no constructor, and all its functions are external. Interfaces describe how to talk to a contract without needing its code.

Use interfaces to call other contracts, such as an ERC-20 token, and use inheritance to share logic between your own contracts. Prefer small contracts over deep inheritance trees, which are hard to read and audit. Also remember that a child's constructor must pass arguments to the parent's constructor.

interface IGreeter {
    function greet() external view returns (string memory);
}

abstract contract Base is IGreeter {
    address public owner;
    constructor(address o) { owner = o; }

    function greet() public view virtual returns (string memory) {
        return "Hello from Base";
    }
    function kind() public pure virtual returns (string memory);
}

contract Child is Base {
    constructor() Base(msg.sender) {}

    function greet() public view override returns (string memory) {
        return string.concat(super.greet(), " and Child");
    }
    function kind() public pure override returns (string memory) {
        return "child";
    }
}

contract User {
    function ask(IGreeter g) external view returns (string memory) {
        return g.greet();
    }
}

Try it yourself

Add a second contract Spanish is Base that overrides greet to return a different greeting. In Remix, deploy both and pass each address to User.ask.

Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.

Quick check: Which keyword must a parent function have so that a child can override it?