This is my problem.
I created an array of objects
and want to give it to another object
Arrays in C++ have different syntaxes. In this case, you're creating an array of pointers (think of (Location*) as a type "ptr to Location", you're making an array of 10 location pointers). If you're really just wanting an array of Location objects, you can do it in either of these ways:
Code:
// Explicit construction on the heap (using new)
Location* loc = new Location[10];
// Implicit construction on the stack
Location loc[10];
Code:
Ant *a[1];
a[0] = new Ant(50, 50, loc);
This is the class header
Again in this case, you're mixing the two. "[1]" really has no effect in C++ in declarations because a single variable is technically an array of size 1 (it does make it a pointer, but that will just confuse you more since you then have a pointer to pointer). The preferred syntax here is:
Code:
Ant* a = new Ant(50, 50, loc);
Code:
class Ant
{
public:
Ant(int px, int py, Location** pl);
private:
Location *l;
};
this the constructor
Code:
Ant::Ant(int px, int py, Location** pl)
{
x= px;
y= py;
cout << pl[0]->getX();
*l = pl;
cout << l[0]->getX();
}
But i dont know how to save the array in the variable of the object.
pls someone help
First, "Location**" is a pointer to pointer of Location. This is generally used to pass an array of pointers (think 2 dimensional array here) to an object, or for mutability (so the called function can manipulate the actual pointer itself, not just what it points to). You're trying to pass an array of Location objects to your ctor so you'd do that like this:
Code:
class Ant{
Location* l;
/* ... */
public:
Ant(int px, int py, Location* pl);
/* ... */
};
Ant::Ant(int px, int py, Location* pl):x(px),y(py){
std::cout << pl[0].getX();
l = pl;
std::cout << l[0].getX();
}
There is a '[]' syntax but I'd avoid it, using pointers is much clearer and most proficient C++ programmers avoid brackets, especially in function declarations.
When using a pointer to represent an array, the '[]' operator will return an object of TYPE that is the nth in the array. Dereferencing of the pointer is implicit in the operator, so 'pl[0]' is the first 'Location' object in the array, not a pointer to it, so you use a dot rather than the arrow syntax.
You should try getting a book to read or reading through some online guides, these seem like rather fundamental mistakes, try
C++ Language Tutorial.
Second... Keep in mind that you're declaring Location *loc[10]; on the stack, so as soon as that function exits, it's destroyed...
That's not technically true. That's a 2-dimensional array (Location**), the array of pointers is stored on the stack but the objects themselves would need to be explicitly constructed with new:
Code:
loc[0] = new Location(...);
Though this is often a mistake since it will almost certainly lead to a memory leak if care isn't taken.