solidity – Casting Between Contract Classes in Solidity

contract-developmentsolidity

I wonder how do you cast between classes in solidity.

For example, if I have these classes:

contract Token {
    function getFive() public returns (uint) {
        return 5;
    }
}

contract MyToken is Token {
    function getSix() public returns (uint) {
        return 6;
    }
}

And I have this variable in other contract:

contract TokenSale {
    Token token;

    function TokenSale(address tokenAddress) {
        token = Token(tokenAddress);
    }
}

contract MyTokenSale is TokenSale {
    function MyTokenSale(address tokenAddress) TokenSale(tokenAddress) {
        // Here I want to call to MyToken's getSix funciton
    }
}

How can I downcast the token variable in MyTokenSale to call getSix function, assuming I can't change TokenSale's code?

As an OOP language, I'm sure that Solidity allows you to do it somehow, but for some reason I couldn't find it in the docs.

Thanks!

Best Answer

This is the syntax you would use:

MyToken myToken = MyToken(address(token));

You have to do it like this because Solidity isn't actually an OOP language, it just has some features that make it feel kinda like it is.

Related Topic