2
votes

Need help with two related Solidity questions.

  1. Question 1. Say, I have a contract calling another one:

    contract B {
      function f1() {
         ...
      }
    }
    
    contract A {
      B b;
    
      function f() {
        b.f1();
      }
    }
    

Will msg.sender for f1 be same as for f()? Of will it be an address of a contract A?

  1. Question 2. Say, I have contracts A and B. I want to have

    contract A {
      B b;
    
      A(address addr) { 
        b = B(addr); 
      }
    }
    

In other language, I would use B b = null; in declaration, to avoid double initialization, but it does not work in Solidity. So how do I declare a member variable and then initialize it by address?

1
Thanks, Adam. But to the second question: when I declare B b;, a default constructor should be called, right? And so I pay for it... - Steve Brown
No, constructors are only called once and there is only one constructor per contract (From github.com/ethereum/solidity/blob/develop/docs/…: "When a contract is created, its constructor (a function with the same name as the contract) is executed once. A constructor is optional. Only one constructor is allowed, and this means overloading is not supported."). Contract variables will be initialized to internal byte representation for 0. See github.com/ethereum/solidity/blob/develop/docs/…. - Adam Kipnis

1 Answers

3
votes

Will msg.sender for f1 be same as for f()? Of will it be an address of a contract A?

msg.sender will be the address of contract A. If you want to reference the original caller, use tx.origin.

So how do I declare a member variable and then initialize it by address?

You don't need to worry about initialization when you declare the member variable. All variables in Solidity have default values. You can follow something like this:

contract B {
    address sender;

    function B(address addr) {
        sender = addr;
    }
}

contract A {
    B b;

    function A(){
        b = B(msg.sender);
    }
}