Foivos Allayiotis
Foivos Allayiotis

Reputation: 109

2D array initialization from a constructor of another class C++

I am trying to create a 2D array of objects in a class and then initializing each cell using a constructor from another class, but i'm getting an error and don't know how to fix it. Here are the classes:

Tile:

class Tile
{
public:
    enum Type
    {
        Sea, Ship, Hit, Miss    
    };
    Tile() {}
    Tile (int X, int Y, Type c)
    {
        this->X = X;
        this->Y = Y;
        this->cell = cell;
    }
    void setType(Type c)
    {
        this->cell = c;
    }
    Type getType()
    {
        return cell;
    }
    void draw(bool hidden)
    {
        if (hidden == false)
            switch (this->getType())
            {
                case Sea:
                    cout<<" ~ ";
                    break;

                case Ship:
                    cout<<" s ";
                    break;

                case Hit:
                    cout<<" X ";
                    break;

                case Miss:
                    cout<<" o ";
                    break;

            }
        else
            switch (this->getType())
            {
                case Hit:
                    cout<<" X ";
                    break;

                case Miss:
                    cout<<" o ";
                    break;

                default:
                    cout<<" ~ ";
                    break;
            }
    }
private:
    Type cell;
    int X,Y;
};

Class Board:

class Board
{
private:
    Tile B[row][col];
    int R, C;
public: 
    Board (Tile B[][col])
    {
        for (R = 0; R < row; R++)
            for (C = 0; C < col; C++)
                B[R][C] = new Tile(R, C, Tile::Sea);
    }
};

The error i am getting is inside the constructor of the Board class. I believe it could be done using a vector but i am forced to use an array.

Upvotes: 2

Views: 96

Answers (2)

bipll
bipll

Reputation: 11940

Not really an answer (which was probably given above) but a few observations comments form is too narrow to contain.

I. Tile' constructor should really read

Tile(Int x, int y, Tile c): X(x), Y(y), cell(c) {}

II. And draw only needs one switch:

void draw(bool hidden) {
    switch(type) {
        case Hit:
            cout<<" X ";
            break;
        case Miss:
            cout<<" o ";
            break;
        case Ship:
             if(!hidden) {
                 cout<<" s ";
                 break;
             }
        case Sea:
            cout<<" ~ ";
            break;
    }
}

Upvotes: 0

Leo Chapiro
Leo Chapiro

Reputation: 13984

The error here is that new Tile(R, C, Tile::Sea) returns a pointer and NOT an instance itself:

//B[R][C] = new Tile(R, C, Tile::Sea);

Tile * tile = new Tile(R, C, Tile::Sea);
B[R][C] = *tile;

Surely you can simple do it like @CoryKramer suggests as well:

B[R][C] = Tile(R, C, Tile::Sea);

Upvotes: 2

Related Questions