1

Is there a way to override or skip calling a parent's constructor? For example, I have the following:

contract Ape {
  constructor() {
    // Initialise some stuff in Ape constructor
  }
}

contract Human is Ape {
  constructor() {
    // Initialise some stuff WITHOUT running whatever that is in Ape.constructor
  }
}

Currently, I notice that the parent constructor will always be called. In my case, I'm creating mock contract which inherits a target contract for testing and I don't want anything in the parent contract's constructor to be initialized so that I can test things out.

Is there any way in some languages where the parent constructor will be only called by super()?

In my case, I would like to omit super() so nothing in the parent constructor is called.

3
  • you can't just remove the constructor from your parent contract?
    – Adam Boudj
    Commented Mar 23, 2022 at 18:50
  • @AdamBoudjemaa I can't remove the parent constructor. I'm just trying to extend it into a mock contract for testing. The parent constructor is still needed in actual usage but the initialisation in it is preventing me from testing and that's why I wanted my mock to not run the constructor in its parent.
    – xenon
    Commented Mar 23, 2022 at 18:52
  • 1
    I have never encountered this situation. But knowing that if it was possible, variables would be there, but with the default value. Namely, 0 for uint, "" for string, false for bool, address(0) for address, etc. So you could initialize them with their default values to reproduce the same scenario.
    – Adam Boudj
    Commented Mar 23, 2022 at 19:16

1 Answer 1

1

You can use this statement for only test because is 'craftmanship' solution. Check this example contract:

//SPDX-License-Identifier: MIT
pragma solidity 0.8.0;

contract Parent {
  string _test = "Empty";

  constructor(bool checkInit) {
    if(checkInit)
        init();
  }

  function init() internal {
      _test = "Hello World / Father";
  }
  
}

contract Child is Parent {
  constructor() Parent(true) {
    
  }

  function getName() external view returns(string memory) {
      return _test;
  }
}

I put a boolean into a father constructor and if this boolean is true then the smart contract call the init() method. This functions contains the initializiation of variables for the parent constructor. Otherwise if the checkInit boolean is false, then the parent constructor do nothing. You can set this boolean variable in the child constructor pass him 'true' or 'false' if you want to initialize the variables through the parent constructor or no.

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.