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.

Chapter 18Copying the Copy Copy CopyConstructorIn This Chapter Introducing the copy constructor Making copies Having copies made for you automatically Creating shallow copies versus deep copies Avoiding all those copiesThe constructor is a special function that C++ invokes automatically whenan object is created to allow the object to initialize itself. Chapter 16introduces the concept of the constructor, whereas Chapter 17 describesother types of constructors. This chapter examines a particular variation ofthe constructor known as the copy constructor.Copying an ObjectA copy constructor is the constructor that C++ uses to make copies of objects.It carries the name X::X(X&), where X is the name of the class. That is, it’s theconstructor of class X, which takes as its argument a reference to an object ofclass X. Now, I know that this sounds really useless, but just give me a chanceto explain why C++ needs such a beastie.Why you need the copy constructorThink for a moment about what happens when you call a function like thefollowing:void fn(Student fs){// ...same scenario; different argument...

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

Saved successfully!

Ooh no, something went wrong!