Overview
TheAddFiveStorage contract is a child contract that inherits from SimpleStorage. It demonstrates contract inheritance and function overriding in Solidity by modifying the behavior of the store() function to automatically add 5 to any stored value.
Contract Details
- License: MIT
- Solidity Version: 0.8.30
- Inherits:
SimpleStorage - Imports:
SimpleStoragefrom./SimpleStorage.sol
State Variables
This contract inherits all state variables fromSimpleStorage, including:
myFavoriteNumber- Auint256variable that stores the favorite numberlistOfPeople- An array ofPersonstructsnameToNumber- A mapping from names to favorite numbers
Functions
store
public
State Mutability: Modifies state
Modifier: override - This function overrides the parent SimpleStorage.store() function
Parameters:
The base number to store. The actual stored value will be this number plus 5.
store() function. Instead of storing the value directly, it adds 5 to the input before storing it in myFavoriteNumber.
Behavior:
- Input:
_favoriteNumber - Stored:
_favoriteNumber + 5
Inherited Functions
SinceAddFiveStorage inherits from SimpleStorage, it also has access to these functions (unless overridden):
retrieve()- Returns the stored favorite numberaddPerson(string memory _name, uint256 _favoriteNumber)- Adds a person to the list
Complete Contract Code
Key Concepts Demonstrated
Inheritance
This contract uses theis keyword to inherit from SimpleStorage:
AddFiveStorage automatically receives all state variables and functions from its parent contract.
Function Overriding
Thestore() function uses the override keyword to replace the parent contract’s implementation:
In Solidity 0.8.30, functions can be overridden even if the parent function is not explicitly marked as
virtual. The override keyword indicates this function replaces the parent implementation.Direct State Variable Access
The overridden function directly accesses the inheritedmyFavoriteNumber state variable:
Usage Examples
Basic Usage
Using with StorageFactory
WhileAddFiveStorage can be used independently, it can also be deployed as part of a factory pattern similar to StorageFactory, demonstrating polymorphism in Solidity.