1

so I'm working with two contracts in one remix file and I'm slightly confused.

I know this works (I've seen it used before)

NonFungibleToken public nft;
  function setNFTAddress(address addr) onlyOwner{
        nft = NonFungibleToken(addr);
    }

But can someone explain to me the syntax behind using

nft = NonFungibleToken(addr);

specifically the

NonFungibleToken(addr);

part. Why does passing in the address to NonfungibleToken work? Wouldn't this just call the default function in NonFungibleToken? Another way to phrase this is: Why are there "()" after nonfungibletoken?

Maybe I'm confused on what

NonFungibleToken public nft;

is actually doing.

2 Answers 2

3

It's a type conversion (cast). From https://solidity.readthedocs.io/en/develop/types.html#explicit-conversions:

If the compiler does not allow implicit conversion but you know what you are doing, an explicit type conversion is sometimes possible. Note that this may give you some unexpected behaviour so be sure to test to ensure that the result is what you want! Take the following example where you are converting a negative int8 to a uint:

int8 y = -3;
uint x = uint(y);

In this case, you're casting an address to a contract of type NonFungibleToken so you can then call the defined functions for that contract.

FYI, you can do this instead (and call it from a client the same way):

NonFungibleToken public nft;

function setNFTAddress(NonFungibleToken _nft) onlyOwner{
    nft = _nft;
}
1
1

From solidity documentation:

contract OwnedToken {
    // TokenCreator is a contract type that is defined below.
    // It is fine to reference it as long as it is not used
    // to create a new contract.
    TokenCreator creator;
    ...

    function OwnedToken(bytes32 _name) public {
        // We do an explicit type conversion from `address`
        // to `TokenCreator` and assume that the type of
        // the calling contract is TokenCreator, there is
        // no real way to check that.
        creator = TokenCreator(msg.sender);
        ...
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.