Monday, June 04, 2007

Implementing the Assignment operator for your class in C++

The other day i was reading about the assignment operator in C++ . Here is my small understanding of it . The job of the assignment operator is to overwrite the members of your class , with the new provided members.

Contract of the assignment operator
  • The assignment operator must work properly when an object is assigned to itself.
  • Since assignment is going to overwrite data for data of your object , the resources external to the object need to be free.
  • The assignment operator should return a constant reference to the assigned object.
Let me give you a reference implementation first . Then we can discuss about the contract.

1 const String& String::operator= (const String& other){
2 if(&other != this){
3 delete[] characters;
4 characters = new char[strlen(other.characters)+1];
5 strcpy(characters,other.characters);
}
}

Now lets discuss the implementation step by step .
if(&other != this)

We need to make sure that the object we are assigning is not the same object , other wise we would end up over writing the data members of the same object.

eg String s
s = s // this would not work if the above mentioned line is not there

Now lets move on to second point of the contract . Since the String class we have here is using characters which is something external to it . We need to delete it , re allocate it and then re initialize it .

// delete the characters
delete[] characters

// reallocate the characters
characters = new char[strlen(other.characters)+1];
// re initialize the characters
strcpy(characters,other.characters);

Now the third point is its important that we return a const reference to the object
being assigned . Thats the reason we are returning *this and thats the reason why
function signature reads .

const String& String::operator= (const String& other)

The reason we need this is to prevent users from trreating assignments as lvalue .
Basically

String s;
(a = b ) = s

something like this should be illegal .

No comments: