x = expression; |
operator=(x, expression); |
For example:
MatrixNxN P(4), Q(4), R(4); R = P * Q; // Illegal, unless you define // the operator function |
It is very common to make copies of variable, and in most cases, variables of user-defined type can be copied by copying ALL fields defined inside the user-defined type (class) from one class variable to another class variable of the same type
class MatrixNxN { public: float *A; int N; /* ----------------------- Constructor(int) ----------------------- */ MatrixNxN(int n) { A = new float[n*n]; N = n; } } |
int main(int argc, char *argv[]) { int N = 4; MatrixNxN M(N), Q(N); // Define 2 matrices Q = M; // Copy M to Q.... Q.A[0] = 1234; // Modify Q, will M be modified ??? } |
class MatrixNxN { public: float *A; int N; /* ----------------------- Constructor(int) ----------------------- */ MatrixNxN(int n) { A = new float[n*n]; N = n; } void operator=(MatrixNxN & M) { int i, j; if ( M.N != N ) { cout << "**Unequal size matrices cannot be copied..."; return; } for (i = 0; i < N; i=i+1) for (j = 0; j < N; j=j+1) A[i*N+j] = M.A[i*N+j]; } } |
int main(int argc, char *argv[]) { int N = 4; MatrixNxN M(N), Q(N); // Define 2 4x4 matrices MatrixNxN R(3); // Define a 3x3 matrix Q = M; // Copy M to Q.... Q.A[0] = 1234; // Modify Q, M is NOT modified } |
 
 
x = y = z; |
x = y = z; => x = (y = z); // Assigns z to y and returns z => x = z; // Assigns z to x and returns z |
MatrixNxN P(4), Q(4), R(4); P = Q = R; // Disallowed.... |
The reason is that the expression is evaluated as follows:
P = Q = R; => P = (Q = R); // Assigns R to Q (that's OK), // but does NOT return anything.... => P = void; // Disallowed |
A better assignment operator:
class MatrixNxN { public: float *A; int N; /* ----------------------- Constructor(int) ----------------------- */ MatrixNxN(int n) { A = new float[n*n]; N = n; } MatrixNxN & operator=(MatrixNxN & M) { int i, j; if ( M.N != N ) { cout << "**Unequal size matrices cannot be copied..."; return(M); } for (i = 0; i < N; i=i+1) for (j = 0; j < N; j=j+1) A[i*N+j] = M.A[i*N+j]; return(M); } } |
int main(int argc, char *argv[]) { int N = 4; MatrixNxN M(N), Q(N); // Define 2 4x4 matrices MatrixNxN R(3); // Define a 3x3 matrix Q = R = M; // M is assigned to Q // (but not R due to size difference) } |
The assignment operator and the copy constructor are similar in many aspects:
  Whenever you define a COPY-CONSTRUCTOR in some class, you MUST define an ASSIGNMENT OPERATOR ALSO, and vice versa   |
 
When you define a class and you need
to define one of these functions:
Then you MUST define ALL three and make sure they
work in the proper manner
  |