What is the difference between creating a new solidity contract with and without the `new` keyword?
Asked Answered
T

3

7

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

Teide answered 21/3, 2017 at 12:10 Comment(0)
T
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.

Teide answered 23/3, 2017 at 4:22 Comment(0)
B
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();
    }
}
Biology answered 9/4, 2019 at 18:46 Comment(0)
T
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.

Teide answered 23/3, 2017 at 4:22 Comment(0)
T
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

Turin answered 19/8, 2022 at 19:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.