5

As per the Solidity 0.4.16 documentation, contracts are similar to the concept of a Class of an object oriented language. That being said, can we create a Contract within a contract.

IF yes, then please explain with a working sample or atleast provide a classification on various kinds of nested contracts that we can create.

IF no, what is stopping us from doing i.e. practical challenges while taking this decision of not having nested contracts in solidity.

Issue raised in similar lines but NOT directly addressing this question: testrpc, contract creating contract not mined?

2 Answers 2

3

Solidity allows for a contract to inherit from other contracts.

Solidity also allows for custom data structs within a contract. These struct types could take the place of a "private class" (Java) contract-within-a-contract for most uses.

And Solidity contracts can create new contracts ("factory" pattern), though the new contracts don't need to have any link back to the "parent". Contracts can call methods on all other contracts, so one contract can treat another one as a "child" or a "library" just in how it uses that contract, but there's no formal relationship between them.

1

Nope, contracts cannot be nested in Solidity. Run the following code snippet in Remix to see for yourself:

// SPDX-License-Identifier: Unlicense
pragma solidity >=0.8.4;

contract Foo {
    uint256 public foo;

    contract Bar {
        uint256 public bar;
    }
}

Compilation fails with the following error:

> from solidity:
ParserError: Function, variable, struct or modifier declaration expected.
 --> contracts/Foo.sol:7:5:
  |
7 |     contract Bar {
  |     ^^^^^^^^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.