Effective C++ Item 12 Copy all parts of an object

This one is simple, do not forget to copy all parts of an object in copy constructor or assignment operator!

There are two cases you tend to make mistakes.

 

1. Make sure you modify copy constructor and assignment operator, if you add a member to a class.

2. Make sure you call the copy constructor and assignment opeator of base class in derived class.

 

A concrete example is that:

member variable "priority" belongs to PriorityCustomer not Customer

PriorityCustomer::PriorityCustomer(const PriorityCustomer& rhs):
	Customer(rhs), 	// call base class' copy constructor
	priority(rhs.priority) {
		...
	}
}

PriorityCustomer&
PriorityCustomer::operator=(const PriorityCustomer& rhs) {
	...
	Customer::operator=(rhs);
	priority = rhs.priority;
	return *this;
}

  

 

 

posted @ 2014-02-28 10:45  SangS  阅读(299)  评论(0编辑  收藏  举报