gautron@nuri.inria.fr (Philippe Gautron) (02/20/91)
The following example shows how difficult it can be to well understand assignment operator and copy constructor. This example was a student's answer to an examen about C++. The raw subject was supposed easy, a matrix 2-2 with operator overloading. Look at the code: - a constructor with default arguments - a copy constructor (no real need here except for completeness) - an assignment operator: here will be our problem - a printing function ------------------------------------------- # include <stream.h> // classe Matrix 2-2 class Matrix { int a1, a2, a3, a4; public: Matrix (int a1=0, int a2=0, int a3=0, int a4=0); Matrix (const Matrix&); Matrix operator= (const Matrix&); friend ostream& operator<< (ostream&, const Matrix&); }; Matrix::Matrix (int a1, int a2, int a3, int a4){ this->a1 = a1; this->a2 = a2; this->a3 = a3; this->a4 = a4; } Matrix::Matrix (const Matrix& m){ this->a1 = m.a1; this->a2 = m.a2; this->a3 = m.a3; this->a4 = m.a4; } Matrix Matrix::operator= (const Matrix& m){ return Matrix(m); // <=== } ostream& operator<< (ostream& stream, const Matrix& m){ stream << "a1= " << m.a1 << " a2= " << m.a2 << " a3= " << m.a3 << " a4= " << m.a4 << '\n'; return stream; } void f(){ Matrix m1(1,1,1,1), m2(2,2,2,2); cout << m1 << m2; m1 = m2; cout << m1 << m2; } ------------------------------------------- In the assignment operator function, the student used a smalltalk-like style, creating a new matrix in the function block and expecting a copy as return value. What cfront (the result is similar with g++) generates is (pseudo-C code): void operator= (Matrix *this, Matrix *result, Matrix *m){ ctor (result, m); } void f(){ Matrix m1; Matrix m2; ctor (&m1, 1, 1, 1, 1); ctor (&m2, 2, 2, 2, 2); Matrix result; // printing operator = (&m1, &result, &m2); // printing } There is no copy of m2 into m1. Note I'm using <<AT&T C++ Translator 2.0 06/30/89>> g++ version 1.37.1 (based on GCC 1.37) Any comment, please email-me directly, my News access is with some contortion by these days. ----------------------- Philippe Gautron, UUCP: gautron@rxf.ibp.fr Rank Xerox France / LITP Universite de Paris VI 4 place Jussieu, 75252 PARIS CEDEX 05 FRANCE