The copy assignment operator replaces an existing object’s state with member-by-member values copied from another object. For a Date object, it assigns year, month, and day, then returns the updated object. section 6.2.2
Use the operator with these design cautions:
- Check for self-assignment before overwriting members by comparing this with the source object's address. section 6.2.2
- Treat the destructor, copy constructor, and copy assignment operator as the Big Three; explicitly implementing one usually calls for implementing all three. section 6.2.2
- Account for hidden copies and assignments when objects move through vectors, because automatic operations can add allocations, deallocations, and runtime cost. section 6.2.2
- Disable copy assignment when a class must have exactly one object, as with the Singleton Design Pattern. section 14.1.3
Instrumented Date assignment
A Date assignment such as d = d2027 replaces d’s existing date fields with d2027’s values. Instrumenting constructors, assignment, and destruction exposes the extra operations triggered while Appointments stores and prints Date objects in a vector. section 6.2.2
Listing 6.13 (Program 6.8 SurpriseVector-2): Date.h (instrumented)
#include <iostream>
#include <string>
using namespace std;
class Date
{
public:
Date() : year(2000), month(1), day(1)
{
cout << "(default constructor) " << endl;
}
Date(const int y, const int m, const int d)
: year(y), month(m), day(d)
{
cout << "(regular constructor) "; print(); cout << endl;
}
Date(const Date& other)
{
cout << "(copy constructor) "; other.print(); cout << endl;
year = other.year; #1
month = other.month; #1
day = other.day; #1
}
Date& operator =(const Date& other)
{
cout << "(assignment operator) "; other.print();
cout << endl;
if (this == &other) return *this;
year = other.year; #2
month = other.month; #2
day = other.day; #2
return *this;
}
~Date()
{
cout << «(destructor) «; print(); cout << endl;
}
void print() const;
private:
static const string MONTH_NAMES[13];
int year, month, day;
};
#1 Explicit member-by-member copying
#2 Explicit member-by-member assignments
Inspect the Date implementation to see the self-assignment guard, explicit field assignments, and diagnostic output. section 6.2.2

