Sign in to follow this  
hisDudeness

declaring object arrays with new in c++

Recommended Posts

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???

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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).

Share this post


Link to post
Share on other sites
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[i] = temp;
}



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

Please don't tell me I have to write operator overloads for new and/or assignment....?!?

Share this post


Link to post
Share on other sites
Of what type are stackArray and oldCoords?


class MazeStack
{
private:
Mouse *X;

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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this