Effective C++ : Copy all parts of an object

1. If you add a data member to a class, you need to make sure that you update all the constructors as well as any nonstandard forms of operator= in the class, if you forget, compilers are unlikely to remind you.

2. 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.

3. 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.

an example given in the book to illustrate 2nd point  is:

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 namee;

};

class PriorityCustomer : public Customer {     // a derived class

public:

PriorityCustomer( const PriorityCustomer & rhs);

PriorityCustomer & operator= (const PriorityCustomer & rhs);

private:

int priority;

};

 

The correct way to the two copy functions in PriorityCustomer class is:

 

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;

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s