12

I'm trying to inherit from a contract. I'm expecting the child contract to have the same constructor as the parent (or be overwritten)

pragma solidity ^0.4.2;

contract parent{
    string public name;
    function parent(string _name){
        name=_name;
    }
}

contract child is parent{}

If I try

contract child2 is parent{
    function child2(string _name){
        name=_name;
    }
}

Then the string entered at construction, that should go into name, doesn't get stored.

What's going on? How do constructors work with inheritance?
Thanks in advance.

19

The trick is in the definition of the interface for child's constructor.

pragma solidity ^0.4.2;

contract parent {

    bytes32 public name;

    function parent(bytes32 _name){
        name=_name;
    }
}


contract child is parent {

    function child(bytes32 _name) parent(_name) {}

}

An explanation of this syntax here: http://solidity.readthedocs.io/en/develop/contracts.html#arguments-for-base-constructors

Hope it helps.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.