If your class manages resources (like dynamically allocated arrays), it
should implement the following three things:
- A copy constructor
- An override for the = operator
- A destructor
• The idea is that there are implicit definitions for each of these
elements and it is important to handle them appropriately (and
probably explicitly), especially when the implicit/default behavior is
undesirable.
class MyClass {
public:
int a; double* b;
MyClass() : a(10), b(new double[20]) {}
MyClass(const MyClass& m) : b(new double[20])
{
a = m.a;
for (int i = 0; i < 20; i++)
b[i] = m.b[i];
}
virtual ~MyClass() { delete[] b; }
MyClass& operator=(const MyClass& m) {
a = m.a;
for (int i = 0; i < 20; i++)
b[i] = m.b[i];
return *this;
}
};
Simplified Version:
class MyClass {
public:
int a; double* b;
MyClass() : a(10), b(new double[20]) {}
MyClass(const MyClass& m) : b(new double[20])
{
*this = m; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
virtual ~MyClass() { delete[] b; }
MyClass& operator=(const MyClass& m) {
a = m.a;
for (int i = 0; i < 20; i++)
b[i] = m.b[i];
return *this;
}
};
A word of advice: understand how operator overloading is declared and
used (think about the [] operator of the vector template) but hold off on
overloading operators yourself except for the = operator