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.

Mikko Ohtamaa
  • 22,269
  • 6
  • 62
  • 127
user1938620
  • 681
  • 1
  • 6
  • 12

2 Answers2

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.

Amin Bashiri
  • 107
  • 2
Rob Hitchens
  • 55,151
  • 11
  • 89
  • 145
26

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(&quot;Guybrush Threepwood&quot;)  {
     // Child construction code goes here
}

}

Mikko Ohtamaa
  • 22,269
  • 6
  • 62
  • 127