Home › Forums › C Programming › Question on operator overloading… and memory management › Re: Re: Question on operator overloading… and memory management
i figured it out… the book is wrong! I hate when that happens! Basically, there’s no way there would be a memory leak unless there is no operator overload. If it merely calls the default copy constructor, then yes, catTwo’s member variables would be pointing at the same memory as catOne’s in a catTwo = catOne; scenario.
The copy constructor is called when returning by value, but it doesn’t matter because it’s returning itself. So it’s doing a shallow copy of it’s own variables. Thus no memory leak.
It makes a lot more sense to me to return by reference, since there’s no need for the copy constructor to be called. In fact, it makes more sense to me for the function not to return a value at all, since it does the necessary reassignments within the operator= overload… silly silly example in the book, and it didn’t help that the book was wrong at least in its inference.