declaring object arrays with new in c++

Started by
3 comments, last by Aardvajk 17 years, 5 months ago
C++ : I have 2 objects, say Mouse and Coordinate: class Coordinate { int x, y; Coordinate(int ex, int why) { x = ex, y = why; }; }; class Mouse { Coordinate locations; // ... }; And so the Mouse object contains an array (the size of which can only be determined at runtime) of Coordinate objects. Inside the Mouse constructor I have:
[source lang=cpp]
Mouse::Mouse(int maxCoords)
{
    locations = new Coordinate[maxCoords];
    // ...
}

I am using Dev-C++ to compile this. I am getting an error in my Mouse constructor, complaining that there is "no matching function for call to Coordinate::Coordinate." I think that the problem may stem from the fact that when I declare the Coordinate array ("locations") inside my Mouse constructor I never initialize the individual Coordinate objects... Regardless of whether my theory is right, how could I fix this???
Well I believe in God, and the only thing that scares me is Keyser Soze.
Advertisement
It's complaining because you have no default constructor for Coordinate. The elements of your array are trying to be initialized by the default constructor but can't since there isn't one.
Aside from that, locations has to be a pointer if you want to be able to assign pointers to it (which is what new returns).
load_bitmap_file,

Thanks for the hint. I added a default constructor and the related errors went away. But now there's a whole new can of worms I can't understand. For simplicity, here is my exact code (it is a program that navigates a mouse through a maze).

Mouse::Mouse(){    col = row = -1;}MazeStack::MazeStack(int maxSteps){	maxMoves = maxSteps;	numCoords = 0;	stackArray = new Mouse[maxMoves];	oldCoords = new Mouse[maxMoves];	top = -1;	// Initialize the oldCoords array so it contains values at every index.	Mouse temp(-1, -1);	for(int i = 0; i < maxMoves; i++)		oldCoords = temp;}


The following code generates the following error:
In constructor MazeStack::MazeStack(int) there is no match for 'operator='...


Please don't tell me I have to write operator overloads for new and/or assignment....?!?
Well I believe in God, and the only thing that scares me is Keyser Soze.
Of what type are stackArray and oldCoords?

class MazeStack{private:    Mouse *X;public:    MazeStack(){ X=new Mouse[10]; } // would compile fine    ~MazeStack(){ delete [] X; }};

This topic is closed to new replies.

Advertisement