Solidity 0.6.x – Overriding a Function

solidity-0.6.x

I am trying the function override capability in solidity 0.6.0. However, when I am trying to override a function in the same contract it is giving me an error that the function has been defined twice. Here is the code:

contract derivedContractv2 {

    function add(uint newa, uint newb) virtual public pure returns (uint _newValue) {
        return newa+newb;
    }

    function add(uint newesta, uint newestb) override public pure returns (uint _newestValue) {
        return newesta+newestb;
    }

}

The error generated is as follows:

browser/integratedContract.sol:13:5: DeclarationError: Function with same name and arguments defined twice.
function add(uint newa, uint newb) virtual public pure returns (uint _newValue) {
^ (Relevant source part starts here and spans across multiple lines).
browser/integratedContract.sol:17:5: Other declaration is here:
function add(uint newesta, uint newestb) override public pure returns (uint _newestValue) {
^ (Relevant source part starts here and spans across multiple lines).

and

browser/integratedContract.sol:17:46: TypeError: Function has override specified but does not override anything.
function add(uint newesta, uint newestb) override public pure returns (uint _newestValue) {
^------^

Is there a way in which I can override the function defined within the same contract?

Best Answer

The virtual function must be in a parent contract. The override function must be in a child contract. Now you have both the functions in the same contract.

Related Topic