Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In your case, there is nothing wrong with <code>w</code> and <code>h</code> being a const. You can write your constructor in the following way:</p> <pre><code> MyImage(unsigned int** _image,unsigned int _w,unsigned int _h) : w(_w), h(_h) { // No data is allocated in the memory pointed to by image yet // We have to allocate it here. Remember, that copy-ctor is // a constructor, so it operates on newly created instance, // not on an existing one. image = new unsigned int * [h]; for (int i = 0; i &lt; h; i++) { image[i] = new unsigned int [w]; memcpy(image[i], _image[h], w * sizeof(unsigned int)); } } </code></pre> <p>From my image-processing experience, consider storing an image as a single table, row-by-row. You can access (x, y)-th element by calling <code>data[y * w + x];</code> In such case, you can simplify your copy ctor:</p> <pre><code>MyImage::MyImage(unsigned int * source, int newW, int newH) : w(newW), h(newH) { image = new unsigned int[w * h]; memcpy((void *)image, (void *)source, w * h * sizeof(unsigned int)); } </code></pre> <p>The <em>copy constructor</em>, as C++ community understands this term, would look like this:</p> <pre><code>MyImage::MyImage(const MyImage &amp;source) : w(source.w), h(source.h) { image = new unsigned int[w * h]; memcpy((void *)image, (void *)source.image, w * h * sizeof(unsigned int)); } </code></pre> <p>Notice, that the <code>image</code> field does not exist when you call the constructor, so you do not need to free anything.</p> <pre><code> // Your code MyImage(unsigned int** _image,unsigned int _w,unsigned int _h) { // Class is allocated into some part of memory, which might // have been used, so in effect this may be actually true, // because image may contain some rubbish data if (image) { // But this will result mostly likely in Access Violation // error, because you would try to use (free!) some random // data in memory. for (int i = 0;i &lt; w;++i) delete[] image[i]; delete[] image; } // .. copy _image to imge } </code></pre> <p>If you need an assign-like method, which copies contents of some image (either stored in a unsigned int * or in another Image class) to an <em>existing</em> instance of Image, <code>w</code> and <code>h</code> cannot be const.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload