7

I really hope this is not a dumb question.

I am trying to call the constructors of the inherited contracts in a structure like this:

contract A{
    uint a;

    constructor (uint _a) public {
        a = _a;
    }
}

contract B is A{
    uint b;

    constructor (uint _a, uint _b) public{
        A(_a);
        b = _b;
    }
}

contract C is B{
    uint c;

    constructor(uint _a, uint _b, uint _c) public {
        B(_a, _b);
        c = _c;
    }
}

If I try to compile it in Remix I get the following error:

TypeError: Exactly one argument expected for explicit type conversion B(_a, _b);

Why can't I call the constructor of B with two variables?

2 Answers 2

8

I believe this exact scenario is covered by the Solidity: Inheritance > Arguments for Base Constructors

Here is the example they give:

pragma solidity ^0.4.22;

contract Base {
    uint x;
    constructor(uint _x) public { x = _x; }
}

contract Derived2 is Base {
    constructor(uint _y) Base(_y * _y) public {}
}

So for you, it would look something like this:

pragma solidity ^0.4.22;

contract A{
    uint a;

    constructor (uint _a) public {
        a = _a;
    }
}

contract B is A{
    uint b;

    constructor (uint _a, uint _b) A(_a) public{
        b = _b;
    }
}

contract C is B{
    uint c;

    constructor(uint _a, uint _b, uint _c) B(_a, _b) public {
        c = _c;
    }
}
13

The accepted answer by @shawn-tabrizi is a good example of how to set up inheritance properly but the reason you got the error is different and I want to share for anyone else that finds this answer for the same error message.

The problem is that you didn't use new before calling the constructor for B. That wouldn't have made the inheritance work but it's the reason for that error message.

3
  • What is the advantage of setting up things in the way that Shawn has over just using new?
    – SDG
    Commented Jul 24, 2020 at 15:12
  • Shawn showed an example with proper inheritance. Adding in new will not make inheritance work. The error is because B(_a, _b) was called without new. Commented Jul 25, 2020 at 17:33
  • 1
    Blessed be your answer :)
    – Dvinubius
    Commented Nov 2, 2021 at 22:05

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.