2

When I create the child class object and try to access value of msg.sender from parent class it always comes 0. Can anyone please help me in this? Below is the sample code:

contract Test1 is Test2 {

    constructor() Test2() {}
}

contract Test2 
{
    address testVal;
    constructor() 
            {testVal= msg.sender;    } 

   function getMSGSender() view returns ( address) {
     return testVal;
   }
}
4

A little clean-up.

  1. You need Test2 defined before Test1 inherits from it, so the order is reversed.
  2. Add public to functions to avoid warning about default visibility.
  3. Constructor in Test1 has nothing else to do, so removed. Since it inherits from Test2, the Test2 constructor will run. In case it is not clear, Test1 will have a state variable called testVal and the function getMSGSender() and there is no need to deploy Test2.

-

pragma solidity 0.4.24;

contract Test2 
{
    address testVal;

    constructor() public {
        testVal= msg.sender;
    } 

   function getMSGSender() public view returns ( address) {
     return testVal;
   }
}

contract Test1 is Test2 {

}

You can call Test1.getMSGSender() and get the expected result.

You didn't mention what you're using to test the contract. Here it is in Remix to show it working without worrying about client-side concerns.

enter image description here

As an aside, you could address public testVal; and that would give you a "free" getter (function testVal() public view returns(address)...) that does exactly what your function does. I left it as is to help focus on one issue at a time.

A more succinct version:

pragma solidity 0.4.24;

contract Test2 
{
    address public testVal;

    constructor() public {
        testVal= msg.sender;
    } 

}

contract Test1 is Test2 {}

Hope it helps.

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.