Solidity Overriding Functions
Overriding is replacing a parent contract's function with a new version in the child contract. The child keeps the same function name and gives a different answer.
A child replaces a virtual function
The parent allows the change with virtual. The child makes the change with override.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract BasePrice {
function fee() public pure virtual returns (uint256) {
return 10;
}
}
contract MemberPrice is BasePrice {
function fee() public pure override returns (uint256) {
return 7;
}
}
super calls the parent version
Replacing a function does not erase the parent's version. The child can still reach it with super.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract BasePrice {
function fee() public pure virtual returns (uint256) {
return 10;
}
}
contract MemberPrice is BasePrice {
function fee() public pure override returns (uint256) {
return 7;
}
function parentFee() public pure returns (uint256) {
return super.fee();
}
}
An override can build on the parent answer
An override can use the parent's answer as a starting point. Here the child adds a charge on top of it.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract BasePrice {
function fee() public pure virtual returns (uint256) {
return 10;
}
}
contract RushPrice is BasePrice {
function fee() public pure override returns (uint256) {
return super.fee() + 5;
}
}
Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract BaseScore {
function score() public pure virtual returns (uint256) {
return 50;
}
}
contract BonusScore is BaseScore {
function score() public pure override returns (uint256) {
return 80;
}
function baseScore() public pure returns (uint256) {
return super.score();
}
}
Key points
- Virtual: a parent marks a function virtual to allow a child to replace it.
- Override: a child marks its replacement function override.
- Same name: the replacement uses the same name and inputs as the parent function.
- Super: the word super inside a child function means the parent contract.
- A super call: super followed by a function name runs the parent's version of that function.
In this example, BaseScore marks score as virtual and returns 50. BonusScore overrides score and returns 80 instead. BonusScore also has baseScore, which uses super to run the parent's version and return 50.
Note
a function without virtual in the parent cannot be overridden by a child.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Remix IDE
Exercise
A parent function has no virtual keyword. What happens when a child tries to override it?