Copying Class Objects

Two operations cause objects to be copied:

  • Assignment. When one object's value is assigned to another object, the first object is copied to the second object. Therefore:

    Point a, b;
    ...
    a = b;
    

    causes the value of b to be copied to a.

  • Initialization. Initialization occurs at the point of declaration of a new object, when arguments are passed to functions by value, and when values are returned from functions by value.

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:

  • Assignment (using the assignment operator, operator=).

  • Initialization (using the copy constructor). (For more information about the copy constructor, see Rules for Declaring Constructors.)

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:

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

int main()
{
}

Nota

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.

See Also

Reference

Special Member Functions