Reputation: 3265
I have a class Pixel
and a class Image
with a function used to update a pixel line. I want to initialize the pixel line. My problem is to initialize the array. Actually I have this :
bool UpdateLine(Pixel line[], int nb)
{
bool noError = true;
line = new Pixel[nb];
for (int r = 0; r < nb; r++)
{
line[r] = new Pixel(); // -> line causing troubles
// do some stuff with my pixel
[...]
}
return noError;
}
When I try this I have :
no viable overloaded '='
How can I initialize each elements for my array ?
Upvotes: 0
Views: 162
Reputation: 409136
You actually have two problems.
The first, regarding your error, is because new Pixel()
results in a pointer to a Pixel
object. In C++ you don't need new
to create objects (do you come from a Java or C# background perhaps?). The initial allocation of the array creates the objects for you.
The second problem is that you assign to the pointer variable line
, but line
is a local variable inside the function. All modification to it will be lost once the function returns, and you will have a memory leak. You need to pass line
by reference.
In the future when dealing with collections of a single type of data, I suggest you use std::vector
instead. You still need to pass the vector by reference though, if you want to add elements to it.
Upvotes: 4
Reputation: 19751
line[r] = new Pixel(); // -> line causing troubles
line[r]
is a Pixel object, not a pointer, so you can't assign a pointer to it.
Why aren't you using a std::vector?
Upvotes: 2