I l @ ve RuBoard |
Answer 18-1: The copy constructor calls the operator = function. The parameter list to this function is: trouble trouble::operator = (trouble old_trouble) { The parameter to this function is being passed as a call- by-value parameter. When C++ sees this type of parameter it calls the copy constructor to put the parameter on the stack. So we have an infinite loop. The copy constructor calls the operator = function. C++ sees the call-by-value parameter and calls the copy constructor, which calls operator = and causes the copy constructor to be called. This keeps up until the system runs out of stack space or the user gets disgusted and aborts the program. The solution is to pass the parameter to operator = as a reference. This not only is more efficient, but also works: trouble trouble::operator = (const trouble& old_trouble) { Unfortunately, this only solves part of the problem. Now, we don't call the copy constructor going into the operator = function . But when we return (*this) , the return value has to be copied , so we still call the copy constructor. The solution is to return a reference to the class instead of a copy of the class. Thus, our declaration of the operator = function should be: trouble& trouble::operator = (const trouble& old_trouble) { |
I l @ ve RuBoard |