Chapter 27. Coping with the Copy Constructor

In This Chapter

  • Letting C++ make copies of an object

  • Creating your own copy constructor

  • Making copies of data members

  • Avoiding making copies completely

The constructor is a special function that C++ invokes when an object is created in order to allow the class to initialize the object to a legal state. Chapter 25 introduces the concept of the constructor. Chapter 26 demonstrates how to create constructors that take arguments. This chapter concludes the discussion of constructors by examining a particular 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(const X&), where X is the name of the class. That is, it's the constructor of class X that takes as its argument a reference to an object of class X. I know that sounds pretty useless, but let me explain why you need a constructor like that on your team.

Note

A reference argument type like fn(X&) says, "pass a reference to the object" rather than "pass a copy of the object." I discuss reference arguments in Chapter 23.

Think for a minute about the following function call:

void fn(Student s)
{
     // ...whatever fn() does...
}

void someOtherFn()
{
    Student s;
    fn(s);
};

Here the function someOtherFn() creates a Student object and passes a copy of that object to fn().

Note

By default, C++ passes objects by value, meaning that it must make a copy of the object to pass to the functions it calls (refer ...

Get Beginning Programming with C++ For Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.