7

What is the use of the new keyword for creating new smart contracts? Why not just omit this keyword?

3 Answers 3

8

There are two ways you can create contracts

  1. Using 'new' keyword
  2. Using address of the contracts

Using new keyword you instantiate the new instance of the contract and use that newly created contract instance

While in latter option you use the address of the already deployed and instantiated contract. You can check below code for reference:

pragma solidity ^0.5.0;

contract Communication {

    string public user_message;

    function getMessage() public view returns (string memory) {
        return user_message;
    }

    function setMessage(string memory _message) public {
        user_message = _message;
    }
}

contract GreetingsUsingNew {

    function sayHelloUsingNew() public returns (string memory) {
        Communication newObj = new Communication();
        newObj.setMessage("Contract created using New!!!");

        return newObj.getMessage();
    }

}

contract GreetingsUsingAddress {

    function sayHelloUsingAddress(address _addr) public returns (string memory) {
        Communication addObj = Communication(_addr);
        addObj.setMessage("Contract created using an Address!!!");

        return addObj.getMessage();
    }
}
4

You cannot omit the new keyword for creating new contracts.

  • In the case of: token = new Token;

    A new contract is created and the address is passed to token.

  • In the case of: token = existingToken;

    existingToken has to be an existing contract (already created) and token will be passed the current address of existingToken.

2
  • Creating a new contract with the new keyword deploys and creates a new contract instance. Deploying a contract involves checking whether the sender has provided enough gas to complete the deployment. So you will be charged. Also, with this method, you can also send Ethereum in Wei during the creation of the contract.

     NewContract myNewContract = (new NewContract){value: 1000000000000000000}()
    
  • in the second method, you are not deploying a new contract instead, instead, you are referring to an already deployed contract. With this method, you should already know the address beforehand

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.