Chapter 17. Copying the Copy Copy Copy Constructor

In This Chapter

  • Introducing the copy constructor

  • Making copies

  • Having copies made for you automatically

  • Creating shallow copies versus deep copies

  • Avoiding all those copies

The constructor is a special function that C++ invokes automatically when an object is created to allow the object to initialize itself. Chapter 15 introduces the concept of the constructor, whereas Chapter 16 describes other types of constructors. This chapter examines a particular variation of the constructor known as the copy constructor.

Copying an Object

A 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 the constructor of class X, which takes as its argument a reference to an object of class X. Now, I know that this sounds really useless, but just give me a chance to explain why C++ needs such a beastie.

Why you need the copy constructor

Think for a moment about what happens when you call a function like the following:

void fn(Student fs)
    // ...same scenario; different argument...
int main(int argcs, char* pArgs[])
    Student ms;
    return 0;

In the call to fn(), C++ passes a copy of the object ms and not the object itself.

Now consider what it means to create a copy of an object. First, it takes a constructor to create an object, even a copy of an existing object. C++ could create a default copy constructor that copies the existing object into the new ...

Get C++ For Dummies®, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.