Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

Assignment

The assignment operator (=) is, strictly speaking, a binary operator. Its declaration is identical to any other binary operator, with the following exceptions:

  • It must be a nonstatic member function. No operator= can be declared as a nonmember function.

  • It is not inherited by derived classes.

  • A default operator= function can be generated by the compiler for class types if none exists. (For more information about default operator= functions, see Memberwise Assignment and Initialization.)

The following example illustrates how to declare an assignment operator:

// assignment.cpp
class Point
{
public:
   Point &operator=( Point & );  // Right side is the argument.
   int _x, _y;
};

// Define assignment operator.
Point &Point::operator=( Point &ptRHS )
{
   _x = ptRHS._x;
   _y = ptRHS._y;

   return *this;  // Assignment operator returns left side.
}

int main()
{
}

Note that the supplied argument is the right side of the expression. The operator returns the object to preserve the behavior of the assignment operator, which returns the value of the left side after the assignment is complete. This allows writing statements such as:

pt1 = pt2 = pt3;
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.