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 ?

A.Pissicat
  • 3,023
  • 4
  • 38
  • 93
  • 3
    `line` is an array of objects! They are all already constructed. C++ works differently to C# or Java. [A good book or two is a must, I think.](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – StoryTeller - Unslander Monica Sep 26 '17 at 09:19

2 Answers2

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
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?

xaxxon
  • 19,189
  • 5
  • 50
  • 80
  • 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 Sep 26 '17 at 09:28
  • @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. – xaxxon Sep 26 '17 at 09:30