The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. |
Home Object-oriented programming The = Operator | ||
See also: Operator Overloading and << | ||
The = Operator
When you create a new object type, you can provide your own definition of = by including a member function called operator =. For the Complex class, this looks like: const Complex& operator = (Complex& b) {real = b.real; imag = b.imag; return *this; } By convention, = is always a member function. It returns the current object. (Remember this from Section 11.2?) This is similar to how << returns the ostream object, because it allows you to string together several = statements: Complex a, b, c;c.real = 1.0; c.imag = 2.0; a = b = c; In the above example, c is copied to b, and then b is copied to a. The result is that all three variables contain the data originally stored in c. While not used as often as stringing together << statements, this is still a useful feature of C++. The purpose of the const in the return type is to prevent assignments such as: (a = b) = c;This is a tricky statement, because you may think it should just assign c to a and b like the earlier example. However, in this case the parentheses actually mean that the result of the statement a = b is being assigned a new value, which would actually assign it to a and bypass b altogether. By making the return type const, we prevent this from happening.
|
||
Home Object-oriented programming The = Operator |