Overloading The Assignment operator = (C++)

From Appmethod Topics
Jump to: navigation, search

Go Up to Overloading Operator Functions Overview Index


The assignment operator = ( ) can be overloaded by declaring a nonstatic member function. For example:

class String {
     .
     .
     .
   String& operator = (String& str);
     .
     .
     .
   String (String&);
   ~String();
}

This code, with suitable definitions of String::operator =(), allows string assignments str1 = str2 in the usual sense. Unlike the other operator functions, the assignment operator function cannot be inherited by derived classes. If, for any class X, there is no user-defined operator =, the operator = is defined by default as a member-by-member assignment of the members of class X:

X& X::operator = (const X& source)
{
   // memberwise assignment
}

See Also