Learn Solidity: Creating Contracts via “new” Operator

In this post, we will learn how to create or instantiate a new contract using the “new” keyword in Solidity Language.

Advertisements
World is looking for a Certified Blockchain Expert Become one

Notice: This is one of the multi-post series of Learn Solidity - Build Decentralized Application in Ethereum. This is an attempt to teach you all about Solidity - A Programming Language for Ethereum Based Smart Contracts. If you want to take this as a video course please signup using below button.
pragma solidity 0.4.8; 

/*
* @title Example the for Solidity Course
* @author Ethereum Community
*/

// A contract can create a new contract using the new keyword. 
// The full code of the contract being created has to be known in advance, 
// so recursive creation-dependencies are not possible.

// lets define a simple contract D with payable modifier
contract D {
    uint x;
    function D(uint a) payable {
        x = a;
    }
}


contract C {
    // this is how you can create a contract using new keyword
    D d = new D(4); 
    // this above line will be executed as part of C's constructor

    // you can also create a contract which is already defined inside a function like this
    function createD(uint arg) {
        D newD = new D(arg);
    }


    // You can also create a conract and at the same time transfer some ethers to it.
    function createAndEndowD(uint arg, uint amount) {
        // Send ether along with the creation of the contract
        D newD = (new D).value(amount)(arg);
    }
}
Previous: Abstract Contract in Solidity Next: Inheriting Smart Contracts in Solidity