0

Are private variables in solidity inherited ?

Please I need a bit of clarification here from most text I have read about inheritance in solidity they state clearly that private variables of parent contracts are not inherited by child contracts but I think this is false. I think the private variables are inherited by child contracts but are not accessible to the child contract directly. Lets consider the contracts below:

contract A {

    uint256 private num;

    function setNum(uint256 _num) public {
        num = _num;
    }

    function getNum() public view returns(uint256) {
        return num;
    }

}

contract B is A {

    function getSlot(uint256 _slotNum) public view returns(uint256 _num) {
        bytes32 slot;
        assembly {
            slot := sload(_slotNum)
        }
        _num = abi.decode(abi.encode(slot), (uint256));
    }
}

from the contracts above contract B inherits the setNum and getNum functions from the contract A and does not inherit the private state variable num right ? But if I call B.setNum(34) then B.getNum() will return 34 (this means the contract B has a uint variable that is being set). Also if I call B.getSlot(0) it returns 34 which confirms that contract B actually inherits num variable from contract A.

2
  • I think you answered the question by yourself and you can access the storage slot as you did with assembly. At the end/deployment it is 1 contract deployed at 1 address and has 1 storage :)
    – Majd TL
    Commented Jun 8 at 10:39
  • I get you but I just want to confirm that child contracts do actually inherit private variables of parent contracts. @MajdTL Commented Jun 8 at 10:47

1 Answer 1

0

You were able to call B.setNum(34) and B.getNum() because setNum and getNum() are public functions defined in contract A, therefore they're inherited by contract B.

But, the value of num (i.e., the private variable defined in contract A) gets changed because of the calling of corresponding public setter function i.e., setNum() in contract B. And, you can get the value of num inside contract B, by calling the corresponding public getter function i.e., getNum().

So, contract B isn't directly accessing or modifying the value of num.

As @MajdTL has mentioned in the comment that when the child contract gets deployed, then the parent contract also gets deployed at the same address and shares the same storage. Therefore, you're able to read the corresponding storage variables of the parent contract inside the child contract, by accessing the corresponding storage slots, the way you did using assembly.

1
  • 1
    Wow thank you I totally get it now. Commented Jun 9 at 7:21

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.