Copying Class Objects

Two operations cause objects to be copied:

The programmer can define the semantics of “copy” for objects of class type. For example, consider the following code:

TextFile a, b;
a.Open( "FILE1.DAT" );
b.Open( "FILE2.DAT" );
b = a;

The preceding code could mean “copy the contents of FILE1.DAT to FILE2.DAT,” or it could mean “ignore FILE2.DAT and make b a second handle to FILE1.DAT.” The programmer is responsible for attaching appropriate copying semantics to each class.

Copying is done in one of two ways:

Any given class can implement one or both copy methods. If neither method is implemented, assignment is handled as a member-by-member (“memberwise”) assignment, and initialization is handled as a member-by-member initialization. Memberwise assignment is covered in more detail in Memberwise Assignment and Initialization.

The copy constructor takes a single argument of type class-name&, where class-name is the name of the class for which the constructor is defined. For example:

class Window
{
public:
    Window( const Window& ); // Declare copy constructor.
    ...
};

Note   The type of the copy constructor’s argument should be const class-name& whenever possible. This prevents the copy constructor from accidentally changing the object from which it is copying. It also allows copying from const objects.