Ben
Ben

Reputation: 16649

Pointer and Array problem

In C++, I'm having trouble with pointers etc. How can I fix the following problem?

error: no match for 'operator=' in '(stage->Stage::tiles + ((unsigned int)(((unsigned int)t) * 12u))) = (operator new(12u), (, ((Tile*))))'| note: candidates are: Tile& Tile::operator=(const Tile&)|*

stage.h

#include "Tile.h"

class Stage {
    public:
        Tile *tiles;
        int size;
        void init(int size);
};

stage.cpp

void Stage::init(int size) {
    this->size = size;
    this->tiles = new Tile[size];
}

application.cpp

#include "Stage.h"
#include "Tile.h"

bool setTiles( Stage * stage ) {

    for( int t = 0; t < stage->size; t++ ) {
        stage->tiles[t] = new Tile();
    }

    return true;
}

stage.init(1234);
setTiles( &stage );

Also, I don't really know when to use object.attribute and when to use object->attribute?

Upvotes: 1

Views: 197

Answers (4)

Shamim Hafiz - MSFT
Shamim Hafiz - MSFT

Reputation: 22064

stage->tiles[t] = new Tile();

The above is not a valid C++ code, which you are perhaps confusing with the way new is used in other language such as C#. Though new can be used to allocate dynamic memories, but assigning an object to a particular element in the dynamically created array doesn't need the new construct. In fact, the object is already created as soon as you called new Tile[size]. What you may want to do is, create an object of type Tile and assign it to a particular element in tiles.

Tile myTile;

// do something with myTile

this->tiles[0] = myTile;

Upvotes: 1

harper
harper

Reputation: 13690

new Tiles() returns a pointer to a Tiles instance.

Tile *tiles defines an array out Tiles, not pointers.

Start with Tile **tiles instead.

Upvotes: 0

MGZero
MGZero

Reputation: 5963

stage->tiles[t] = new Tile();

You're calling new on something that's not a pointer. True, tiles is a pointer to an array, however, each element of that array is NOT a pointer. In order for that work, you would need an array of pointers, or a pointer to a pointer ,such as:

Tile **tiles;

What you could also do is create a separate pointer object, allocate it, and then copy the data to your array element by using

stage->tiles[i] = *somePointer;

and then deleting the pointer afterwards to free that allocated memory. This will preserve the copy because you invoked the copy constructor.

Upvotes: 6

Thomas Berger
Thomas Berger

Reputation: 1870

You are trying to allocate a pointer with a pointer to an array. Try this one:

class Stage {
    public:
        Tile **tiles;
        void init(int size);
};

Upvotes: 3

Related Questions