Inheritance
Rather than making one extremely long contract, sometimes it makes sense to split your code logic across multiple contracts to organize the code.
One feature of Solidity that makes this more manageable is contract
inheritance.Solidity supports multiple inheritance. Contracts can inherit other contract by using the
iskeyword.Function that is going to be overridden by a child contract must be declared as
virtual.Function that is going to override a parent function must use the keyword
override.Order of inheritance is important.
You have to list the parent contracts in the order from “most base-like” to “most derived”.
contract Doge {
function catchphrase() public returns (string memory) {
return "So Wow CryptoDoge";
}
}
contract BabyDoge is Doge {
function anotherCatchphrase() public returns (string memory) {
return "Such Moon BabyDoge";
}
}BabyDoge inherits from Doge. That means if you compile and deploy BabyDoge, it will have access to both catchphrase()and anotherCatchphrase() (and any other public functions we may define on Doge).
This can be used for logical inheritance (such as with a subclass, a Cat is an Animal). But it can also be used simply for organizing your code by grouping similar logic together into different contracts.
Example when constructor arguments are required
Example
Inherited State Variables
Unlike functions, state variables cannot be overridden by re-declaring it in the child contract.
The only way it can be overridden is by setting it directly in the construction of the child contract.
Last updated