Well I like to learn as much code as I can in a day and I just came across the copy constructor. I do not understand when I need to use it. Do I need to use it for every class I make?
I came across it after getting the error: 'class Bitmaps' has pointer data members but does not override 'Bitmaps(const Bitmaps&)' or 'operator=(const Bitmaps&)' [-Weffc++]
So I googled it as usual and came across the copy constructor and assignment vs. copy constructor.
Now after reading the documentation, it tells me that if I have a class already constructed, I can assign another class to it without the copy constructor. If the class is being initialized by another, I need a copy constructor.
Already assigned class:
class Point
{
int x, y;
public:
Point(int X, int Y);
};
Point A(10, 10);
Point B(5, 5);
A = B; //Uses assignment operator?
Unassigned class:
class Point
{
int x, y;
public:
Point(int X, int Y);
};
Point B(5, 5);
Point A = B; //Copy constructor? This currently works fine for me without it :S
Now the code that gives me a problem is defined as so:
class Bitmaps
{
private:
PRGB Pixels; //Pointer to a union.
BITMAPINFO Info; //This has to be initialized in member list with Constructor() : Info(0)?
int width, height, size;
BITMAPFILEHEADER bFileHeader;
protected:
HDC DC;
HBITMAP Image;
public:
~Bitmaps(); //Deletes Pixels aka pointer. Deletes Image and releases DC.
Bitmaps(const char* FilePath);
Bitmaps(int Width, int Height, uint32_t BitsPerPixel = 32);
PRGB GetPixels() {return Pixels}; //I believe this is what requires the copy con?
HDC ReturnDC() {return DC;};
};
//My other class that gives the same error :S
class Pens
{
private:
HDC hDC;
HPEN NewPen;
HPEN OldPen;
public:
Pens(HDC hdc, COLORREF colour);
Pens(HDC hdc, DWORD Style, DWORD Width, COLORREF colour);
~Pens();
void ColourPixel(Point ColourPoint);
void DrawLine(Point Begin, Point End);
void DrawRectangle(Box B);
void DrawEllipse(Point UpperLeftBound, Point LowerRightBound);
void DrawArcAngle(Point CenterPoint, DWORD Radius, float StartAngle, float EndAngle);
void DrawArc(Point UpperLeftBound, Point LowerRightBound, Point ArcStartPoint, Point ArcEndPoint);
void DrawArcTo(Point UpperLeftBound, Point LowerRightBound, Point ArcStartPoint, Point ArcEndPoint);
};
The only problem I can possibly see with my bitmap class is the GetPixels function which returns my internal pointer and that if the returned pointer is deleted, it can mess up my class when the constructor is called. Is a copy constructor going to fix this? Why do I need both the copy constructor and the assignment operator? Why the assignment operator do all the work like it's supposed to (copy my values to the other).
Does this mean I need more constructors for all my classes and two assignment overloads? Finally, do I need to check for self-assignment using if (this != ....)
?