Overview
Inheritance allows contracts to inherit properties and functions from parent contracts, enabling code reuse and creating hierarchical contract relationships.Basic Inheritance
Use theis keyword to inherit from a parent contract:
AddFiveStorage.sol
The child contract (
AddFiveStorage) automatically has access to all public and internal functions and state variables from the parent contract (SimpleStorage).Function Overriding
Child contracts can override parent functions to change their behavior.Requirements for Overriding
- Parent function must be marked as
virtual - Child function must use the
overridekeyword
Parent Contract
First, mark the function as virtual in the parent:SimpleStorage.sol
Child Contract
Then override it in the child:AddFiveStorage.sol
The
override keyword explicitly declares that this function is meant to override a parent function. This prevents accidental naming conflicts.How It Works
- SimpleStorage
- AddFiveStorage
store(10) sets myFavoriteNumber to 10.Accessing Parent Functions
You can call the parent’s version of an overridden function usingsuper:
Multiple Inheritance
Solidity supports multiple inheritance. Contracts can inherit from multiple parents:Constructor Inheritance
If the parent contract has a constructor with parameters, the child must pass them:Visibility and Inheritance
| Visibility | Inherited by Child | Accessible from Outside |
|---|---|---|
public | Yes | Yes |
internal | Yes | No |
private | No | No |
external | No* | Yes |
*External functions can be called via
this.functionName() but are not directly inherited.When to Use Inheritance
Good Use Cases
- Creating specialized versions of a contract
- Implementing standard interfaces (ERC20, ERC721)
- Sharing common functionality across multiple contracts
- Building modular, upgradeable systems
Example: Factory Pattern
StorageFactory.sol
Complete Example
Here’s the full working example:SimpleStorage.sol
AddFiveStorage.sol
Key Takeaways
- Use
iskeyword to inherit from parent contracts - Parent functions need
virtualto be overrideable - Child functions need
overrideto override parent functions - Child contracts inherit all public/internal state variables and functions
- Use
superto call parent implementations - Inheritance enables code reuse and polymorphism in Solidity