I am currently working on an ADT called Text and I’m overloading the assignment operator. When I test the operator like so: assignText = alpha everything outputs okay. However, when I do assignText = assignText then two solid bars output instead.
assignText is declared as a Text object.
My overloaded assignment operator is as follows:
void Text::operator= (const Text& other) {
bufferSize = other.getLength();
buffer = new char[bufferSize];
buffer = other.buffer;
}
Where int bufferSize and char *buffer
Any tips or suggestions would be greatly appreciated. If anything else is needed, just let me know.
Other answers already have pointed out various issues with your operator implementation. Here I’ll try to understand what’s happening for you, i.e. why the code behaves as you observe. If
this == &other, i.e. during self assignment, you take the current length as the size of a new buffer. That new buffer isn’t initialized, so at that point it might contain random bytes. The last assignment is a no-op in case of a self-assigment. To sum things up:So what this tells you is that you end up with a buffer of the current object size but with undefined content. In your case that undefined content happens to represent the vertical bars you mention.
To solve this, make sure to fix the assignment operator based on the suggestions from other answers and comments.