4

I have an error accessing a public variable between contracts. It works if I change x.myname to x.myname() but I do not understand why that works. Can anyone explain why the () are needed?

Here is the code which fails -

pragma solidity ^0.4.18;
contract MyAddr {
uint public myname=1;
function getName() view  public returns (uint name) {
name = myname;
}
}
contract MyAddr2 {
MyAddr private x;
string private myname1;
  function getStateVar() view public returns (uint stateVar) {
       stateVar = x.myname;
   }
}

contract MyAddr3 {
}

MyAddr.sol:12:20: Error: Type function () view external returns 
(uint256) is not implicitly convertible to expected type uint256.
    stateVar = x.myname;
               ^------^


x.myname to x.myname() does work.
5

When you create a public state variable, the public part is that a corresponding getter—a function that returns the state variable's value—with the same name as the variable is created. So the way to access the value from outside the contract is to call that function.

See https://programtheblockchain.com/posts/2018/01/02/making-smart-contracts-with-public-variables/, https://solidity.readthedocs.io/en/develop/contracts.html#visibility-and-getters, and http://solidity.readthedocs.io/en/develop/contracts.html#getter-functions.

| improve this answer | |

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.