solidity – Understanding Virtual and Override Keywords in Solidity

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 and override 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 as virtual. The overriding function must then use the override 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 be virtual.

  • Functions without implementation have to be marked virtual outside of interfaces. In interfaces, all functions are automatically considered virtual.

Examples

Simple Example (From Solidity Docs)

pragma solidity >=0.5.0 <0.7.0;

contract Base {
    function foo() virtual public {}
}

contract Middle is Base {}

contract Inherited is Middle {
    function foo() public override {}
}

Multiple Inheritance Example (From Solidity Docs)

pragma solidity >=0.5.0 <0.7.0;

contract Base1 {
    function foo() virtual public {}
}

contract Base2 {
    function foo() virtual public {}
}

contract Inherited is Base1, Base2 {
    // Derives from multiple bases defining foo(), so we must explicitly
    // override it
    function foo() public override(Base1, Base2) {}
}
Related Topic