I got the hint that for classes with member variables which are pointers, I need to pay attention to properly memory-manage them on assignment. The following methods are meant to avoid memory leaks:
class SomeClass {
SomeClass& SomeClass::operator =(SomeClass& from) {
// clone
if (&from != this) {
this->dispose();
this->clone(from);
}
return *this;
}
void SomeClass::clone(const SomeClass& from) {
this->array = from.array;
}
void SomeClass::dispose() {
delete[] this->array;
}
};
Assuming this is correct so far, is it possible to do the following:
Define a superclass Object
which implements operator=
and has abstract methods clone
and dispose
. Any class with pointer members should have Object
as a superclass, so that it inherits operator=
and I am reminded that I need to implement clone
and dispose
.
- How would such a superclass look like?
- Is it a good idea to do this by inheritance?