0

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?

Huowuge
  • 41
  • 5

2 Answers2

1

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

Satoshi Naoki
  • 353
  • 2
  • 10
  • I think you are right. However, I deployed the contract C in Remix, I didn't notice there is any message about I had deployed contract A. – Huowuge Jan 26 '23 at 13:43
  • Yeah, you will not get any message about it since it's done something like internally. But you will be able to see the deployed address of contract A once you set the `contractA` as public. `A public contractA = new A();` – Satoshi Naoki Jan 26 '23 at 17:19
0

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);
  }
}  
Gleichmut
  • 5,953
  • 5
  • 24
  • 32