11

Given:

contract A {

    address owner;
    function A() { owner = msg.sender; }

}

contract B is A {

    string greeting;
    function B(string _greeting) { greeting = _greeting; }

}
  1. When I deploy my contract, I want to make sure that owner is initialized. Do I need to call the parent constructor in B's constructor to initialize the value owner in A like so: function B (string _greeting) A(msg.sender) { greeting = _greeting; }, or can I just leave it as is above (it will initialize the values of A automatically, by automatically calling A()?
  2. Does B need its own address, or will it just use A's as its own?
1
  • 2
    Not sure if you're familiar with how SE sites work, but if the answer below told you what you needed to know, go ahead and mark it as accepted. If it didn't, definitely followup and clarify what you're looking for in a comment or edit . :) Commented Jun 28, 2017 at 21:58

2 Answers 2

15

No, you do not need to call the parent constructor yourself unless you need to pass arguments to it (detailed examples here).

As far as addresses go, the solidity file specified above is basically like a class specification. You will decide what actually gets an address at the time of instantiation. Most likely, when you instantiate contract B somehow, you will create only a single contract at a single address which contains the code for all inherited functionality. The only way you would have a separate address for A is if you also separately instantiated an entirely independent copy of A.

Alternatively, if you're referring to the "owner" address variable, it is already set in the base constructor and present in contract storage. You do not need to define the variable again: you can simply use it however you need to.

2

1. Do I need to call the parent constructor in B's constructor to initialize the value owner in A

Unless you are passing arguments to a constructor, you do not need to explicitly call it. Assigning owner = msg.sender will be evaluated when the contract is deployed

2. Does B need its own address, or will it just use A's as its own?

Using Inheritance in Solidity will bundle your code together and deploy it under a single contract

From the solidity docs:

When a contract inherits from multiple contracts, only a single contract is created on the blockchain, and the code from all the base contracts is copied into the created contract.

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.