Chapter 27

Coping with the Copy Constructor

In This Chapter

arrow Letting C++ make copies of an object

arrow Creating your own copy constructor

arrow Making copies of data members

arrow Avoiding making copies altogether

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.

remember.eps A reference argument ...

Get Beginning Programming with C++ For Dummies, 2nd Edition now with O’Reilly online learning.

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