0

I try to understand variable scope in solidity But what that mean in this example new keyword instentiate to a contract Whtat concept use in this logic can someone explain me

pragma solidity ^0.5.0;
contract C {
  uint public data = 30;
  uint internal iData= 10;
  
  function x() public returns (uint) {
     data = 3; // internal access
     return data;
  }
}
contract Caller {
  C c = new C();
  function f() public view returns (uint) {
     return c.data(); //external access
  }
}
contract D is C {
  function y() public returns (uint) {
     iData = 3; // internal access
     return iData;
  }
  function getResult() public view returns(uint){
     uint a = 1; // local variable
     uint b = 2;
     uint result = a + b;
     return storedData; //access the state variable
  }
}

I mean this part of code I not understand why they use this example to explain beginner level variable scope I also finding the use of new keyword in solidity ,not found

contract Caller {
  C c = new C();
  function f() public view returns (uint) {
     return c.data(); //external access
  }
}

Thanks you

3
+50

The new keyword creates a new smart contract (in this case using the contract C code for that contract).

The new contract will have an address (c can be cast to an address) and other external accounts (EOAs) or contracts can interact with it at this address.

In terms of scoping, there is nothing special going on here. c is declared in the contract storage of Caller, so can be referenced in any non-pure function in Caller.

There is some more info at:

https://www.oreilly.com/library/view/solidity-programming-essentials/9781788831383/23e0e5a6-db05-4f9f-9260-8e4ac442ccee.xhtml

https://docs.soliditylang.org/en/v0.8.9/control-structures.html?highlight=new%20keyword#creating-contracts-via-new

1

The C c = new C () creating a new instance of contract C. So you would be able to use the c.data () in another contract to access the contract C variable or function as long as it is public or internal but not private.

Check this out for more info: https://docs.soliditylang.org/en/v0.7.3/contracts.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy