2

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!

  • In TokenSale, why don't you simply declare a state variable of type MyToken instead of Token? Seems like what you want to achieve, since MyToken is Token anyway. – goodvibration Feb 12 '18 at 17:03
4

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.

0

You would do something like this:

Token token = Token(address)

then, to call a function from the other contract you would write

return token.getSix()
  • Sorry but this isn't working. Solidity probably does not support polymorphism. – tomericco Feb 15 '18 at 15:24

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.