Can't use array of contracts inside a function in solidity

Viewed 176

Can someone please explain me why this works fine

import "./SimpleStorage.sol";

pragma solidity ^0.6.0;

contract storageFactoryContract {

SimpleStorage[] public asd;

function createSimpleStorageContract() public{
    
     
     SimpleStorage simpleStorage = new SimpleStorage();
}

}

but this doesn't

import "./SimpleStorage.sol";

pragma solidity ^0.6.0;

contract storageFactoryContract {

function createSimpleStorageContract() public{
    
     SimpleStorage[] public asd;

     SimpleStorage simpleStorage = new SimpleStorage();
}

}

The error is:

freecodecamptutorial/FactoryContract.sol:14:26: ParserError: Expected ';' but got 'public' SimpleStorage[] public asd; ^----^

1 Answers

In the second snippet, you're trying to set a visibility modifier for a regular variable. Only state variables (i.e. contract properties) and functions can have visibility modifiers.

Reference type variables (such as a contract) need to also have a data location. Since you're not working with the variable further, you can safely use the memory location. If you were to store it in storage, you might want to use the storage data location.

function createSimpleStorageContract() public {
     // removed the `public` modifier
     // added the `memory` data location
     SimpleStorage[] memory asd;
     SimpleStorage simpleStorage = new SimpleStorage();
}

This will generate two warnings about the unused variables asd and simpleStorage. It's simply because you're assigning the variables but never using them later. In this context, you can safely ignore them.

Note: I'm assuming that the SimpleStorage is a contract without a constructor or with a 0-argument constructor. Otherwise, you might get some different errors, for example wrong argument count.

Related