1

Suppose we replace every expression balances[user] with a call myBalance(user) where

mapping(address => uint256) balances;

function myBalance(address user) returns (uint256) virtual internal {
    return balances[user];
}

and do not inherit from this contract.

Will this increase gas usage?

And what if I do inherit, will it increase gas usage for this base (parent) contract?

I am interested about Solidity 0.5.10 and above.

2

No.

It's a compile-time concern. It wasn't always required but it has been added to the compiler to make the developer's intent more clear - the compiler will throw an error if you try to override a function that is not marked virtual.

If you do override the function, the only version of the function that matters is the highest-order function that overrode the lower-order function that was inherited. At runtime, all that matters is the bytecode for the version that won. It's bytecode goes in the runtime bytecode that gets deployed.

To say it another way, the compiler is resolving a contest between versions of the function to include the final contract, and the virtual modifier is explicitly saying a given function is a candidate for replacement as a form of developer-error detection. The virtual modifier has no meaning at runtime.

Hope it helps.

1
  • And it is worth mentioning that this is indeed a different mechanism than the one implemented in "real" object-oriented languages, where a V-Table is used in order to determine the exact function to execute during runtime, and subsequently, an additional cost (of reading the V-Table pointer) applies during runtime. Dec 10 '20 at 7:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.