Chronicle
Chronicle

Reputation: 1645

Creating an array of a struct

I am trying to make an array of structs, but I am getting the error no matching function for call to 'Cell::Cell()'.

Cell is the name of my struct. Here is some of my code:

struct Cell{
    int number;

    Cell(int n){
        number = n;
    }
};

class MyClass{
    public:
        int nCells;

        void inject(){
            std::cout << "Enter number:";
            string in;
            std::cin >> in;
            int amount = in.size()/3;

            Cell cells [amount]; // <-- error

            int index = 0;
            int t = in.size();
            while (t >= 3){
                cells[index] = new Cell(atoi(in.substr(t-3,3).c_str());
                t -= 3;
                index++;
            }
        }

        MyClass(int n){
            nCells = n;
        }
};

Cell cells [amount]; is giving me the error. I am new to classes, but I know how to make arrays of primitive types. int cells [amount]; would work, for instance.

But how am I supposed to make an array of type Cell ?

Upvotes: 0

Views: 107

Answers (3)

Netwave
Netwave

Reputation: 42678

By doing Cell cells [amount]; you are calling the Cell constructor, but in this case you don't have a default constructor for Cell, so you must use pointers instead, you are using them in the while stuff.

Just change

Cell cells [amount];

for

Cell* cells [amount];

Upvotes: 0

Sebastian Hoffmann
Sebastian Hoffmann

Reputation: 11482

Cell doesnt have a default constructor (as soon as you specify another constructor the compiler will not create a default constructor anymore). However the definition Cell cells[amount] will automatically default initialize every element.

I think the best way in this particular situation is simply to implement a default constructor:

struct Cell{
    int number;

    Cell() : number(0)
    {
    }

    Cell(int n) : number(n)
    {
    }
};

Also notice as amount is not known at compile time, Cell cells[amount] is basically illegal. However some compilers have extensions to allow this. But its better if you heap allocate it:

Cell* cells = new Cell[amount];

Dont forget to destroy it however.

Upvotes: 4

BЈовић
BЈовић

Reputation: 64203

If you know how long the array is, you can use c++11 initialization. This will do :

int main()
{
    Cell c[3]{ Cell(1), Cell(2), Cell(3) };
}

By the way this

Cell cells [amount];

is using VLAs, and that is not supported by c++ (only as extension for some compilers).

In c++, much better would be to use std::vector :

#include <vector>


struct Cell{
    int number;

    Cell(int n){
        number = n;
    }
};

int main()
{
    int n = 5;

    std::vector< Cell > c;

    for ( int i =0; i < n; ++ i )
    {
        c.emplace_back( Cell( i ) );
    }
}

Upvotes: 2

Related Questions