Virtual Override functions in Solidity

Solidity Programming Language
3 min readFeb 12, 2022

--

Source: https://studygroup.moralis.io/t/assignment-openzeppelin-reading/33816/37

Thanks to Alim !

Virtual

A function that allows an inheriting contract to override its behavior will be marked at virtual

Override

The function that overrides that base function is marked as override

When should you put the virtual keyword on a function?

When you what to allow another contract that is inheriting from the current contract to override its functionality

When should you put the keyword override on a function?

When you want to change the functionality of an inherited contract or implement its specification

You can confuse inheritance with inheritance strategy. We focus firstly inheritance code.

Code I

Contract B inherits from Contract A and its foo2 function calls the Contract A’s foo function.

What do you expect ?

This is fully inheritance business.

CODE II

Please focus on, we call contract A’s foo function with same name in contract B.

When we deploy the contract, you can see that Contract B’s foo function overrides the Contract A’s foo function.

We use the “virtual” keyword in contract A and “override” keyword in contract B. This is big secret !

CODE III

You can override the other function also you can inherit the same function.

The result is the as follows

--

--

Solidity Programming Language

Solidity basics for beginners: Learn the fundamentals of smart contract development and build your first DApp! #Solidity #Foundry #Ethereum #Opcodes #DApps