Does `initialize` function need to be marked as 'virtual'

// contracts/MyContract.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";

contract BaseContract is Initializable {
    uint256 public y;

    function initialize() public initializer {
        y = 42;
    }
}

contract MyContract is BaseContract {
    uint256 public x;

    function initialize(uint256 _x) public initializer {
        BaseContract.initialize(); // Do not forget this call!
        x = _x;
    }
}

Does initialize() need virtual in BaseContract,and override in MyContract?

1 Like

Hi @pageone,

You don’t need to do that as the signatures are different. The BaseContract initialize has no parameters, whilst in the derived contract it takes a uint256.

But Remix reports an err

1 Like

Hi @pageone,

I just tried on Remix and compiled with Solidity 0.6.12 but didn’t get any warnings.

// contracts/MyContract.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

import "https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/v3.4.0/contracts/proxy/Initializable.sol";

contract BaseContract is Initializable {
    uint256 public y;

    function initialize() public initializer {
        y = 42;
    }
}

contract MyContract is BaseContract {
    uint256 public x;

    function initialize(uint256 _x) public initializer {
        BaseContract.initialize(); // Do not forget this call!
        x = _x;
    }
}

Please note, OpenZeppelin Upgrades Plugins support Truffle and Hardhat.

Sorry,I see,If the both initialize have no parameters,I need add virtual?

1 Like

Hi @pageone,

If you are overriding a function in a contract (has the same signature) then you need to use virtual and override.

A post was split to a new topic: Unable to update lock within the stale threshold