1

I was editing and trying out the code from https://solidity-by-example.org/shadowing-inherited-state-variables and got the following output.

pragma solidity >=0.8.0 <0.9.0;
//SPDX-License-Identifier: MIT

contract Parent {
    string public name = "Contract Parent";
}

contract Child is Parent {
    constructor() {
        name = "Contract Child";
    }

    function getName() public view returns (string memory) {
        return name;
    }
    string public childGetName = getName();
}
OUTPUT

childGetName 
"Contract Parent"

getName
"Contract Child"

name
"Contract Child"

I want to know why childGetName is not "Contract Child" since the inherited state variable (name) has been overridden.

Thank you

1 Answer 1

3

It is because the storage variable childGetName gets its value assigned before the constructor code in Child is executed (before name's value changes from "Contract Parent" to "Contract Child"). You could read more about the contract lifecycle here

Before the constructor code is executed, state variables are initialised to their specified value if you initialise them inline, or zero if you do not.

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.