0

If I have this contract:

contract HelloWorld{
...
}

and this one

import "./HelloWorld.sol";
contract HelloUniverse is HelloWorld{
...
}

and I deploy it, will it create 2 different contract and 2 different contract addresses or how will it be stored on ethereum blockchain? Thank you.

1 Answer 1

1

It will deploy one contract that includes properties rolled up from HelloWorld. I say "rolled up" to avoid using "inheritance" in a description of inheritance.

This little scribble ...

contract HelloWorld {
  bool isHappy;
  string response = "Hi there!";
  modifier onlyIfHappy {
    require(isHappy);
    _;
  }
}

contract HelloUniverse is HelloWorld {
  function talk() public view onlyIfHappy returns(string memory) {
    return response;
  }
}

... is roughly the same as:

contract HelloUniverse {
  bool isHappy;
  string response = "Hi there!";
  modifier onlyIfHappy {
    require(isHappy);
    _;
  }
  function talk() public view onlyIfHappy returns(string memory) {
    return response;
  }
}

The child contract can redefine an inherited function which is what happens if it has a function with the same signature as an inherited function.

Inheritance is often confused with composition, i.e. the author wants a contract to communicate with another contract.

In that case, deploy HelloWorld (I added a public which we are going to need):

contract HelloWorld {
  bool isHappy;
  string public response = "Hi there!";
  modifier onlyIfHappy {
    require(isHappy);
    _;
  }
}

The caller needs to know about the interface. In the simplest form, both contracts are in the same source file and variable is cast as an instance of the target contract. The caller also needs to know about the target's address. That concern can be handled by passing it into the constructor:

contract HelloUniverse {

  HelloWorld helloWorldContract; // <== Regular type instance storage declaration (like uint x)

  constructor(address helloWorldContractAddress) public {
      helloWorldContract = HelloWorld(helloWorldContractAddress);
  }

  function talk() public view returns(string memory) {
    return helloWorldContract.response();
  }
}

In summary, Ethereum can do it either way.

Hope it helps.

0

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.