I am having a real problem completely understand what a copy constructor is and how to write it. I understand the concept of having a function that can create deep copies rather that shallow copies but how to write it im unsure of.
Just for an example im gonna create a class called Graphics, so far all I have in it are two ints rows and columns an a 2d array made up of a class called Pixel (which ive gotten to work.) as well as a static int called graphicsCount.
Now I have my regular constructor that does so:
1 2 3 4 5
Graphics::Graphics(int r = 0, int c = 0)
{
rows = r;
cols = c;
};
But im lost on a copy contructor. All ive been able to make (According to my C++ book.) is something that looks like this:
1 2 3 4
Graphics::Graphics(const Graphics& m)
{
}
But from there im lost. It's prolly simpler than im thinking it is but any help or guidance is appreciated!
I may have made a bit of progress but im unsure if its right. Check or tell me what im doing wrong.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
Graphics::Graphics(const Graphics &m)
{
this -> rows = m.rows; // copies rows into new object
this -> cols = m.cols; // copies cols into new object
this -> array = new Pixel[this -> rows]; //copies first element of the array of pixels?
Pixel = new Pixel[cols]; // copies second element of the array of pixels?
for (int i = 0; i < this -> rows; i++) // Steps thorugh first element?
{
for (int q = 0; q < this -> cols; q++) // steps through second element?
{
this -> array[i][q] = m.array[i][q]; // copies value?
}
}
}