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.


The = Operator

Unlike the << operator, which refuses to output classes that haven't defined their own definition of that function, every class comes with its own =, or assignment, operator. This default operator simply copies every data member from one class instance to the other by using the = operator on each member variable.

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.


Last Update: 2005-12-05