Solidity 0.6.0 introduced the keywords virtual
and override
. What do they do?
solidity – Understanding Virtual and Override Keywords in Solidity
keywordoverridesoliditysolidity-0.6.xvirtual
keywordoverridesoliditysolidity-0.6.xvirtual
Solidity 0.6.0 introduced the keywords virtual
and override
. What do they do?
Best Answer
As of Solidity 0.6.0, the keywords
virtual
andoverride
are available natively in Solidity for function overriding. The purpose of these keywords is to be more explicit when overriding a function. Base functions can be overridden by inheriting contracts to change their behavior if they are marked asvirtual
. The overriding function must then use theoverride
keyword in the function header.These keywords simply allow for more explicit behavior when overriding functions. Prior to version 0.6.0 of Solidity, these keywords did not exist and function overriding was done implicitly. These keywords allow developers to explicitly override functions. Additionally, they allow developers to signal their intent for certain functions so that others have a better understanding of the purpose of the function.
There are a few things to note when using these keywords:
For multiple inheritance, the most derived base contracts that define the same function must be specified explicitly after the
override
keyword.Functions with the
private
visibility cannot bevirtual
.Functions without implementation have to be marked
virtual
outside of interfaces. In interfaces, all functions are automatically consideredvirtual
.Examples
Simple Example (From Solidity Docs)
Multiple Inheritance Example (From Solidity Docs)