Home > Net >  What is the difference of calling methods between in derived function and with new key word in Solid
What is the difference of calling methods between in derived function and with new key word in Solid

Time:01-26

I noticed there are two methods to call the contract's functions in Solidity as follow.

// Base contract
contract A {
    function X() public pure returns (string memory s) {
        s = 'Base contract function X';
    }
}
// Inherited contract
contract B is A {
    function Y() public pure returns (string memory s) {
        s = string.concat(X(), '   Inherited contract function Y');
    }
}
// Contract with new key word
contract C {
    A contractA = new A();
    function Z() public view returns (string memory s2) {
        s = string.concat(contractA.X(), '   Contract C function Z');
    }
}

I don't understand the difference between contract B and C, especially in what case should I use inheritance, or new key word to call a function?

CodePudding user response:

What you shared in the post is a good example of the inheritance and composition. When to use each of this design decisions is a general engineering question and doesn't relate to solidity. Here is one of discussions of this topic.

new keyword is used to create a new instance of the class. Although I am not sure it is possible to instantiate contract in solidity in a such way. I did this by passing an address of the contract:

class Chain {
  Token _token;
  constructor(address _tokenAddress) {
    _token = Token(_tokenAddress);
  }
}  

CodePudding user response:

In the inherited contract, contract B includes contract A and it doesn't deploy an external contract. It means it calls the X() function of itself. In the second case with the new keyword, it deploys the contract A and calls the X() function of the external contract A

  • Related