I am new in C++. I have a problem with Image Processing. What I am trying to do is to write my class Image, which has as private variables horizontal and vertical sizes of an image and data for each pixel (grayscale, just 2D array of floats). I also wrote basic functions within the class: getPixel,SetPixel, GetSize, GetData (returns 2D array of data).
My question is: I read, that for best performance I have to write a destructor function and overloaded "=" operator at least.
1) Can someone explain why I really need it (as long as this version working more or less).
2) Can you write destructor and "=" operator for me? I guess, it is not difficult for experts, I tried once but with my destructor I got memory errors: Error _BLOCK_TYPE_IS_VALID(pHead->nBlockUse);
Update: Even now, without defining "=" operator, I can use it in my main function. If, say, I had Image img1 of size (1x1) and img2 of size (2x2), I can write img1=img2, and it works!
Update2: After I tried to implement simple destructor (delete [] pix) the error "_BLOCK_TYPE_IS_VALID" appeared
struct Pixel
{
float p;
};
struct size
{
int x;
int y;
};
class Image {
private:
int _x, _y;
Pixel *pix;
public:
Image(int x, int y){
pix = new Pixel[x * y];
_x = x;
_y = y;
}
float getPixel(int i, int j) {
return pix[i * _y + j].p;
}
void setPixel(int i, int j, Pixel val)
{
pix[i * _y + j].p = val.p;
}
size GetSize(){
size a;
a.x = _x;
a.y = _y;
return a;
}
Pixel **GetData(){
Pixel **a=0;
a = new Pixel*[_x];
for (int i = 0; i < _x; i++){
a[i] = new Pixel[_y];
for (int j = 0; j < _y; j++){
a[i][j] = pix[i*_y + j];
}
}
return a;
}
};
UPDDATE 3: I tried to implement everything from rule of three. I added:
~Image()
{
delete[] pix;
}
Image(const Image& that)
{
pix = new Pixel[that._x*that._y];
pix = that.pix;
_x = that._x;
_y = that._y;
}
Image& operator=(const Image& that)
{
if (this != &that)
{
delete[] pix;
pix = new Pixel[that._x*that._y];
pix = that.pix;
_x = that._x;
_y = that._y;
}
return *this;
}
Still got memory error: "_BLOCK_TYPE_IS_VALID..."