🎓 A1Learner
🔍
0 of 50 lessons completed

Solidity Inheritance

Inheritance is a way for one contract to reuse another contract's variables and functions. A contract is code stored on a blockchain, which is a shared record that many computers keep.

A child inherits a state variable

A child contract starts with the parent's state. It does not copy the parent's code.

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

contract Vehicle {
    uint256 public wheels = 4;
}

contract Car is Vehicle {
}

A child inherits a function

Functions travel with the state. The child can call a function that only the parent wrote.

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

contract Vehicle {
    uint256 public wheels = 4;

    function wheelCount() public view returns (uint256) {
        return wheels;
    }
}

contract Car is Vehicle {
}

A child adds its own members

Inheritance is a starting point, not a limit. The child adds its own variable next to the inherited ones.

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

contract Vehicle {
    uint256 public wheels = 4;
}

contract Car is Vehicle {
    uint256 public seats = 5;
}

Example

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

contract Vehicle {
    string public kind = "Vehicle";
    uint256 public wheels = 4;

    function start() public pure returns (string memory) {
        return "Started";
    }
}

contract Car is Vehicle {
    uint256 public doors = 4;

    function drive() public pure returns (string memory) {
        return "Driving";
    }
}

Key points

  • Parent contract: the contract whose variables and functions are reused.
  • Child contract: the contract that inherits from the parent.
  • The is keyword: writing Contract B is Contract A makes B the child of A.
  • Inherited members: the child can use the parent's public variables and functions as its own.
  • Own members: the child can also add variables and functions that the parent does not have.
  • Deploying the child: putting the child contract on the blockchain gives you the inherited members and the new ones together.

In this example, Vehicle is the parent and it holds a kind, a wheel count, and a start function. Car is the child, so it inherits all three members without rewriting them. Car then adds its own doors variable and drive function.

Note

the parent contract does not change when a child inherits from it.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Remix IDE

Exercise

Which line makes Car inherit from Vehicle?