Function overriding in Solidity is the process by which a child contract provides a new implementation for a function already defined in its parent contract.
Since Solidity 0.6.0, this process is explicit and requires the use of two specific keywords(virtual & override) to prevent accidental overrides and improve code readability.
The Process
In the Parent Contract: Use the virtual keyword. This signals that the function is "open" for modification.
In the Child Contract: Use the override keyword. This signals that you are "intentionally" replacing the parent's logic.
Both virtual & override can be used in the same function in a multi level inheritance
Example:
contract Parent {
// Marked virtual to allow overriding
function message() public virtual pure returns (string memory) {
return "Hello from Parent";
}
}
contract Child is Parent {
// Marked override to redefine logic
// Marked virtual to allow overriding
function message() public virtual override pure returns (string memory) {
return "Hello from Child";
}
}
contract Grandchild is Child {
// Marked override to redefine logic
function message() public override pure returns (string memory) {
return "Hello from Grandchild";
}
}
Constraints:
Visibility - Function visibility must be the same or more restrictive when overriding
State - State mutability can change to be more restrictive (but not less)
Interfaces - Functions in an interface are implicitly virtual. You only need the override keyword in the implementation.
Private - private functions cannot be virtual, so they can never be overridden.
Note:
Modifiers can also be overridden like functions, but starting with Solidity 0.9.0 release this will be deprecated.
Top comments (0)