34

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.

2 Answers 2

41

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.

28

Solidity 0.5+ has a different syntax for calling parent constructors.

// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;


contract Parent {

    public string name;

    constructor(string _name) {
        name = _name;
    }
}

contract Child is Parent {

    constructor() Parent("Guybrush Threepwood")  {
         // Child construction code goes here
    }
}

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.