0

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?
clstaudt
  • 17,395
  • 34
  • 132
  • 209

1 Answers1

2

No! Don't do this.

First, declare your operator=() as

SomeClass& SomeClass::operator =(const SomeClass& from);

Pay attention to const. In the new C++11 standard, there is another form, which allows the move semantic you have shown in your example, but then you declare the assignment operator as

SomeClass& SomeClass::operator =(SomeClass&& from);

Pay attention to &&.

For an in depth discussion of this topic, look for rule of three or in C++11 rule of five

Now to your question, assignment operators aren't inherited. When you don't define an assignment operator in your derived class, the compiler will generate a default one and hide the assignment operator of your base class. So, the assignment operator of your base class will never be seen and never be used by the clients of your derived classes.

For more discussion about assignment operators, see for example What is the copy-and-swap idiom?.

Community
  • 1
  • 1
Olaf Dietsche
  • 66,104
  • 6
  • 91
  • 177