Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 47 ยท Object-Oriented Solidity

Inheritance and Overriding

Learn Solidity inheritance: is, virtual and override, super, constructor arguments, multiple inheritance linearization and abstract contracts, with a runnable C3 model.

Real contracts are rarely written from scratch. A token is "a contract that keeps balances" plus "a contract with an owner" plus "a contract that can be paused". Solidity lets you build one contract out of others with inheritance: a contract declares that it is another one, and receives all of its (non-private) functions and state variables. This is how libraries such as OpenZeppelin are meant to be used.

This lesson covers is, virtual and override, super, how constructors of base contracts run, what happens with multiple inheritance (including the linearization rule that decides the order), and abstract contracts.

Inheritance vocabulary

is Take everything from a base contract.
virtual A base function that may be replaced.
override A child function that replaces it.
super Call the next version up the chain.
1 / 2

Basic inheritance

SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract Owned {
    address public owner;

    constructor() {
        owner = msg.sender;
    }

    modifier onlyOwner() {
        require(msg.sender == owner, "not owner");
        _;
    }
}

contract Shop is Owned {
    uint256 public price = 1 ether;

    function setPrice(uint256 p) public virtual onlyOwner {
        price = p;
    }
}

Shop inherits owner, the constructor logic and the onlyOwner modifier (see Modifiers and Access Control). Only one contract is deployed in the end: the compiler copies the code of the bases into the derived contract. There are no separate base contract instances on chain.

Visibility controls what is inherited. public, external and internal members are available to children. private members exist in storage but cannot be accessed by name from a child. A child may not declare a state variable with the same name as one in a base (shadowing is an error).

virtual and override

Functions cannot be replaced unless the base says so. Mark the base function virtual, and the child's replacement override:

SOLIDITY
contract Base {
    function greet() public pure virtual returns (string memory) {
        return "base";
    }
}

contract Child is Base {
    function greet() public pure override returns (string memory) {
        return "child";
    }
}

Both keywords are mandatory, and forgetting either is a compile error. This is deliberate: you cannot accidentally replace a function, and a reader sees at once which functions are replaceable. A few more rules:

  • The child must keep the same name and parameter types and return types. It can make the function stricter: external may become public, and the mutability may tighten from non-payable to view to pure, but not the other way.
  • A function that overrides can itself be virtual, so grandchildren may override it again. Add override only (without virtual) to end the chain.
  • Modifiers can also be virtual and overridden.
  • State variables cannot be overridden, but a public state variable can override an external function from an interface or base (the generated getter takes its place).

super

Inside an overriding function, super.greet() calls the next implementation up the chain instead of the base by name. It is how a child adds to behavior instead of replacing it:

SOLIDITY
contract Audited is Shop {
    event PriceChanged(uint256 oldPrice, uint256 newPrice);

    function setPrice(uint256 p) public override {
        uint256 old = price;
        super.setPrice(p);          // runs Shop.setPrice, including onlyOwner
        emit PriceChanged(old, p);
    }
}

Note that Shop.setPrice was declared public virtual. A function declared external cannot be called with super, so use public for functions that children are meant to extend.

Multiple inheritance and linearization

A contract may have several bases:

SOLIDITY
contract A {
    function who() public pure virtual returns (string memory) { return "A"; }
}
contract B is A {
    function who() public pure virtual override returns (string memory) {
        return string.concat("B>", super.who());
    }
}
contract C is A {
    function who() public pure virtual override returns (string memory) {
        return string.concat("C>", super.who());
    }
}
contract D is B, C {
    function who() public pure override(B, C) returns (string memory) {
        return string.concat("D>", super.who());
    }
}

When two bases define the same function, the child must say which ones it overrides: override(B, C). Without that, the compiler refuses, because the intent would be ambiguous.

Now the key question: when D.who() calls super.who(), which contract runs next? Solidity uses the C3 linearization (the same algorithm as Python's method resolution order) to flatten the family tree into one list, with no duplicates. For D is B, C the list, from most derived to most base, is D, C, B, A. Notice that the last base listed is searched first. super always means "the next contract in that list", so D calls C, whose super calls B (not A), whose super calls A. Every contract in the diamond runs exactly once.

That is why the order in the is clause matters. List bases from most base-like to most derived:

SOLIDITY
contract E is A, B { }   // fine: B is already an A, so A comes first
contract F is B, A { }   // error: linearization is impossible

In F, you say that B is more general than A, yet B itself inherits from A. The compiler reports "Linearization of inheritance graph impossible".

Constructors in inheritance

Base constructors run before the derived constructor, in linearization order from the most base to the most derived. If a base constructor takes arguments, supply them either in the inheritance list or in the derived constructor header:

SOLIDITY
contract Named {
    string public name;
    constructor(string memory n) { name = n; }
}

// Option 1: fixed at the inheritance list
contract Fixed is Named("Fixed") { }

// Option 2: passed through the derived constructor
contract Dynamic is Named {
    constructor(string memory n) Named(n) { }
}

If you pass different argument values in two places, or forget to provide them at all, the contract becomes abstract (see below) or does not compile. The order of the base constructor calls written in the constructor header does not change the order in which they actually run; linearization decides that.

Abstract contracts and interfaces

A contract with at least one function lacking a body must be marked abstract, and the unimplemented function must be virtual:

SOLIDITY
abstract contract Pricing {
    function price() public view virtual returns (uint256);

    function priceWithTax() public view returns (uint256) {
        return price() * 120 / 100;
    }
}

contract FixedPricing is Pricing {
    function price() public pure override returns (uint256) { return 100; }
}

An abstract contract cannot be deployed on its own; it is a template that gives children a shared base and forces them to fill in the gaps. This is the "template method" pattern. A child that does not implement every missing function is itself abstract. Interfaces and Libraries covers the fully abstract case.

Inheritance copies powers and risks. If a base has an unprotected initialize or a public function that changes ownership, every child inherits it. When storage layout matters, as in upgradeable contracts, the order of base contracts decides the storage slots, so adding or reordering bases can corrupt existing data. See Proxies and Upgradeable Contracts.

A linearization model you can run

The code below is a stand-in, not the Solidity compiler: it implements C3 linearization in JavaScript, reverses the written base list the way Solidity does, and uses the result to run super chains and constructors. It shows the order for you but it knows nothing about types, storage or the EVM.

JS C3 order and super chains

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The output shows the chain D>C>B>A: each contract runs exactly once, and the last listed base is the first one super visits. E (written from base to derived) works, while F is rejected, just as in the real compiler.

Next, add constructors and an abstract guard. Constructors run from the most base contract to the most derived, which is the linearization list read backwards.

JS Constructor order and abstract contracts

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real: C3 linearization with the base list reversed, super following that list, constructors running base-first and abstract contracts that cannot be deployed. Stand-in: the model uses objects and closures instead of compiled bytecode, and it does not check virtual/override markers, visibility or storage layout.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which keywords are required to replace a function from a base contract?

    The base must allow replacement with virtual, and the child must state its intent with override. Leaving either out is a compile error.
  2. 2. For contract D is B, C where both inherit from A, in what order are contracts searched by super from D?

    Solidity's linearization puts the last-listed base first after the contract itself, giving D, C, B, A. Each contract appears exactly once.
  3. 3. In what order do constructors run in contract Token is Owned, Named?

    Bases are initialized before the derived contract, in linearization order read from the most base side. The order of calls in a constructor header does not change it.
  4. 4. What is true of an abstract contract?

    Abstract contracts can mix implemented and unimplemented (virtual) functions and serve as templates. Only a complete child contract can be deployed.

Summary

  • contract B is A gives B everything non-private in A; only one combined contract is deployed.
  • A replaceable function needs virtual in the base and override in the child. When several bases define it, write override(B, C).
  • With several bases, list them from most general to most specific. The compiler builds one C3 linearization (last base first), and super goes to the next contract in it.
  • Base constructors run first, base to derived; arguments are given in the is list or in the derived constructor header.
  • Abstract contracts can leave functions unimplemented and cannot be deployed; children must fill the gaps.
  • Inheritance copies risk too, and base order affects storage layout in upgradeable systems.

Next: Interfaces and Libraries.