[Ethereum] Constructor initializing another contract


I have a contract which is creating an instance of another contract. I am confused about deploying the contracts in Truffle. Does the constructor get initialized when deployed?

Best Answer

Constructors are always executed exactly once when a contract is created.

You'll use Truffle to migrate the factory contract, and then use a function in the factory to deploy created contracts. No need to migrate the contract the factory is designed to deploy. If the constructor of the contract to be deployed needs any arguments, then they should be passed in by the factory.

It's not exactly the same question, but this example might clarify the pattern: How to migrate a contract that has a constructor parameter of address type via truffle

You can structure it like this:


import "Created.sol";

contract Factory {

  function createContract() returns(address created) {
    Created c = new Created(msg.sender); // passing an arg to constructor
    return c;



With Truffle, Factory.deployed() will be the contract on the blockchain.



var factory = Factory.deployed();
factory.createContract({from: .. })
.then(function(txn) {
  // you have the transaction hash now

Hope it's helpful.

Related Topic