inheritanceethereumsoliditysmartcontractsopenzeppelin

Inheritance in Solidity


contract MyToken is ERC20, ERC20Permit, ERC20Votes {
    constructor() ERC20("MyToken", "MTK") ERC20Permit("MyToken") {}

   // The following functions are overrides required by Solidity.

    function _afterTokenTransfer(address from, address to, uint256 amount)
        internal
        override(ERC20, ERC20Votes)
    {
        super._afterTokenTransfer(from, to, amount);
    }

    function _mint(address to, uint256 amount)
        internal
        override(ERC20, ERC20Votes)
    {
        super._mint(to, amount);
    }

    function _burn(address account, uint256 amount)
        internal
        override(ERC20, ERC20Votes)
    {
        super._burn(account, amount);
    }
}

Can somebody explain why we need to override these 4 functions from base contract ? It's not possible to call it from super keyword?


Solution

  • I will explain on this

     function _afterTokenTransfer(address from, address to, uint256 amount)
            internal
            override(ERC20, ERC20Votes)
        {
            super._afterTokenTransfer(from, to, amount);
        }
    

    Normally, super._afterTokenTransfer will check parent contracts, find _afterTokenTransfer function and call it. But if your contract is inheriting from multiple contracts, and more than one contract has the same function, it will inherit from the right-most contract first. But since you have this:

     override(ERC20, ERC20Votes)
    

    it will visit both the contract and call _afterTokenTransfer inside each contract. If you did not have this override(ERC20, ERC20Votes)

     function _afterTokenTransfer(address from, address to, uint256 amount)
                internal
                override
            {
                super._afterTokenTransfer(from, to, amount);
            }
    

    since the right-most parent contract is ERC20Votes, super._afterTokenTransfer(from, to, amount) this will call only from ERC20Votes