11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

250Part III: Introduction to ClassesThis precludes any external functions, including C++, from constructing acopy of your Student objects. (This does not affect the capability of memberfunctions to create copies.) If no one can invoke the copy constructor, nocopies are being generated. Voilà.Referring to the copy constructor’sreferential argumentThe fact that the copy constructor is used to create temporaries and copieson the stack answers one pesky detail that may have occurred to you.Consider the following program:class Student{public:Student(Student s){// ...whatever...}};void fn(Student fs) {}void fn(){Student ms;fn(ms);}Notice how the argument to the copy constructor is no longer referential. Infact, such a declaration isn’t even legal. The Dev-C++ compiler generates a horriblelist of meaningless error messages in this case. Another public domainC++ compiler generates the following, much more meaningful error message:Error: invalid constructor; you probably meant ‘Student(const Student&)’Why must the argument to the copy constructor be referential? Consider theprogram carefully: When main() calls the function fn(), the C++ compiler usesthe copy constructor to create a copy of the Student object on the stack.However, the copy constructor itself requires an object of class Student. Noproblem, the compiler can invoke the copy constructor to create a Studentobject for the copy constructor. But, of course, that requires another callto the copy constructor, and so it goes until eventually the compiler collapsesin a confused heap of exhaustion.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!