How does inheritance work in Solidity, and what do virtual and override do?
A child inherits a parent's functionality with contract Child is Parent. To replace a parent function, the parent function must be marked virtual and the child's version must be marked override.
import "./SimpleStorage.sol";
contract ExtraStorage is SimpleStorage { // inherits everything
function store(uint256 _n) public override { // replaces parent's store
favoriteNumber = _n + 5;
}
}
is makes ExtraStorage a child of SimpleStorage, giving it all the parent's functions and variables for free. To change one inherited function you override it, and Solidity enforces a two-sided handshake: the parent must declare the function virtual (opting in to being overridden), and the child must declare override (opting in to replacing it). Omit either and compilation fails ("missing override specifier" / "trying to override non-virtual function"). This prevents accidental overrides.
Go deeper:
Solidity docs: inheritance —
is,virtual/override, and multiple-inheritance linearization.