Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 726
RFV Avatar asked Jan 05 '23 07:01

RFV


1 Answers

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();
    }
}
like image 105
Rahul Telgote Avatar answered Jan 16 '23 18:01

Rahul Telgote