Item 12: Copy all parts of an object

In well-designed object-oriented systems that encapsulate the internal parts of objects, only two functions copy objects: the aptly named copy constructor and copy assignment operator. We'll call these the copying functions. Item 5 observes that compilers will generate the copying functions, if needed, and it explains that the compiler-generated versions do precisely what you'd expect: they copy all the data of the object being copied.

When you declare your own copying functions, you are indicating to compilers that there is something about the default implementations you don't like. Compilers seem to take offense at this, and they retaliate in a curious fashion: they don't tell you when your implementations are almost certainly wrong.

Consider a class representing customers, where the copying functions have been manually written so that calls to them are logged:

 void logCall(const std::string& funcName);          // make a log entry class Customer { public:   ...   Customer(const Customer& rhs);   Customer& operator=(const Customer& rhs);   ... private:   std::string name; }; Customer::Customer(const Customer& rhs) : name(                                 // copy rhs's data {   logCall("Customer copy constructor"); } Customer& Customer::operator=(const Customer& rhs) {   logCall("Customer copy assignment operator");   name =;                               // copy rhs's data   return *this;                                  // see Item 10 } 

Everything here looks fine, and in fact everything is fine until another data member is added to Customer:

 class Date { ... };       // for dates in time class Customer { public:   ...                     // as before private:   std::string name;   Date lastTransaction; }; 

At this point, the existing copying functions are performing a partial copy: they're copying the customer's name, but not its lastTransaction. Yet most compilers say nothing about this, not even at maximal warning level (see also Item 53). That's their revenge for your writing the copying functions yourself. You reject the copying functions they'd write, so they don't tell you if your code is incomplete. The conclusion is obvious: if you add a data member to a class, you need to make sure that you update the copying functions, too. (You'll also need to update all the constructors (see Items 4 and 45) as well as any non-standard forms of operator= in the class (Item 10 gives an example). If you forget, compilers are unlikely to remind you.)

One of the most insidious ways this issue can arise is through inheritance. Consider:

 class PriorityCustomer: public Customer {                  // a derived class public:    ...    PriorityCustomer(const PriorityCustomer& rhs);    PriorityCustomer& operator=(const PriorityCustomer& rhs);    ... private:    int priority; }; PriorityCustomer::PriorityCustomer(const PriorityCustomer& rhs) : priority(rhs.priority) {   logCall("PriorityCustomer copy constructor"); } PriorityCustomer& PriorityCustomer::operator=(const PriorityCustomer& rhs) {   logCall("PriorityCustomer copy assignment operator");   priority = rhs.priority;   return *this; } 

PriorityCustomer's copying functions look like they're copying everything in PriorityCustomer, but look again. Yes, they copy the data member that PriorityCustomer declares, but every PriorityCustomer also contains a copy of the data members it inherits from Customer, and those data members are not being copied at all! PriorityCustomer's copy constructor specifies no arguments to be passed to its base class constructor (i.e., it makes no mention of Customer on its member initialization list), so the Customer part of the PriorityCustomer object will be initialized by the Customer constructor taking no arguments by the default constructor. (Assuming it has one. If not, the code won't compile.) That constructor will perform a default initialization for name and lastTransaction.

The situation is only slightly different for PriorityCustomer's copy assignment operator. It makes no attempt to modify its base class data members in any way, so they'll remain unchanged.

Any time you take it upon yourself to write copying functions for a derived class, you must take care to also copy the base class parts. Those parts are typically private, of course (see Item 22), so you can't access them directly. Instead, derived class copying functions must invoke their corresponding base class functions:

 PriorityCustomer::PriorityCustomer(const PriorityCustomer& rhs) :    Customer(rhs),                   // invoke base class copy ctor   priority(rhs.priority) {   logCall("PriorityCustomer copy constructor"); } PriorityCustomer& PriorityCustomer::operator=(const PriorityCustomer& rhs) {   logCall("PriorityCustomer copy assignment operator");   Customer::operator=(rhs);           // assign base class parts   priority = rhs.priority;   return *this; } 

The meaning of "copy all parts" in this Item's title should now be clear. When you're writing a copying function, be sure to (1) copy all local data members and (2) invoke the appropriate copying function in all base classes, too.

In practice, the two copying functions will often have similar bodies, and this may tempt you to try to avoid code duplication by having one function call the other. Your desire to avoid code duplication is laudable, but having one copying function call the other is the wrong way to achieve it.

It makes no sense to have the copy assignment operator call the copy constructor, because you'd be trying to construct an object that already exists. This is so nonsensical, there's not even a syntax for it. There are syntaxes that look like you're doing it, but you're not; and there are syntaxes that do do it in a backwards kind of way, but they corrupt your object under some conditions. So I'm not going to show you any of those syntaxes. Simply accept that having the copy assignment operator call the copy constructor is something you don't want to do.

Trying things the other way around having the copy constructor call the copy assignment operator is equally nonsensical. A constructor initializes new objects, but an assignment operator applies only to objects that have already been initialized. Performing an assignment on an object under construction would mean doing something to a not-yet-initialized object that makes sense only for an initialized object. Nonsense! Don't try it.

Instead, if you find that your copy constructor and copy assignment operator have similar code bodies, eliminate the duplication by creating a third member function that both call. Such a function is typically private and is often named init. This strategy is a safe, proven way to eliminate code duplication in copy constructors and copy assignment operators.

Things to Remember

  • Copying functions should be sure to copy all of an object's data members and all of its base class parts.

  • Don't try to implement one of the copying functions in terms of the other. Instead, put common functionality in a third function that both call.

Effective C++ Third Edition 55 Specific Ways to Improve Your Programs and Designs
Effective C++ Third Edition 55 Specific Ways to Improve Your Programs and Designs
ISBN: 321334876
Year: 2006
Pages: 102 © 2008-2017.
If you may any questions please contact us: