0

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 ?

1

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Or enjoy the beauty/power of modern C++ and just return the vector by value
My code has been automatically generated from C# by a piece of software, I am not yet very comfortable with the C++. I will use vector instead array. Thank you for your answer.
Just for sure, bool UpdateLine(std::vector<Pixel>* line, int nb) will be better ?
@A.Pissicat I would use std::vector<Pixel>& instead.
2
    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?

2 Comments

I'll use vector instead, this part has been automatically generated from C#, I had not thought of replacing it with a vector
@A.Pissicat most times when you're looking at dynamically sizing an array in C++, you should be using a std::vector instead. Create the vector inside your function and return it by value. No need to pass in an empty one to the function.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.