5

Parent and child contract are:

contract test{
   uint a ;
   function test() {
       a = 1;
   }
   function val() returns(uint){
       return a;
   }  
}

contract test2 is test{ 
    uint b = a++;
    function show() returns(uint){
        return b; 
    }
}

Every time I call show() I would like to get the new value of b as a is incremented afterwards. I'm not able to implement this using the above code. Is there an alternative for static variable in Solidity? If not, what should be done to get the desired working?

1
  • What is the desired behaviour? So you want a to store internally a count for the number of times that show was called. Also you want to have return that count and increment it, right?
    – Marlo
    Jun 28, 2022 at 23:45

2 Answers 2

3

This returns b then increments a (and fixes the initialization of b):

contract test2 is test{ 
    uint b;
    
    function test2() {
        b = a++;
    }
    
    function show() public returns(uint){
        b = a++;
        return b; 
    }
}
0
0

If the desired behaviour is that your contract stores an internal counter and anytime that the function show is called you retrieve the value of that counter and increment it by one afterwards, then this would be such a contract

contract test2 is test{
    function show() public returns(uint256 b) {
        b = a;
        a += 1;
    } 
}

The variable a is an internal counter variable and lives inside the contracts storage. Even though you inherit test, there is only one storage for the contract. You may add some visibility and mutability to variables. For instance uint256 internal a would not be visible from the outside, uint256 private a would not be visible by test2 (but it still exists in this single storage of the contract) and uint256 public a would be visible from the outside. The variable b does not live in the contract's storage. It is a temporary dummy variable in this implementation.

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.