What is the use of the new
keyword for creating new smart contracts? Why not just omit this keyword?
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) andtoken
will be passed the current address ofexistingToken
.
There are two ways you can create contracts
- Using 'new' keyword
- 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();
}
}
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) andtoken
will be passed the current address ofexistingToken
.
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
© 2022 - 2024 — McMap. All rights reserved.