Compartilhar via


Copying Class Objects

Both the assignment operation and the initialization operation 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 when a new object is declared, when arguments are passed to functions by value, or when values are returned from functions by value.

You can define the semantics of "copy" for objects of class type. For example, consider this 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." You must attach appropriate copying semantics to each class, as follows.

  • By using the assignment operator operator= together with a reference to the class type as the return type and the parameter that is passed by const reference—for example ClassName& operator=(const ClassName& x);.

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

If you do not declare a copy constructor, the compiler generates a member-wise copy constructor for you.  If you do not declare a copy assignment operator, the compiler generates a member-wise copy assignment operator for you. Declaring a copy constructor does not suppress the compiler-generated copy assignment operator, nor vice versa. If you implement either one, we recommend that you also implement the other one so that the meaning of the code is clear.

Member-wise assignment is covered in more detail in Memberwise Assignment and Initialization.

The copy constructor takes an 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()
{
}

Note

Make the type of the copy constructor's argument const class-name& whenever possible. This prevents the copy constructor from accidentally changing the object from which it is copying. It also enables copying from const objects.

See Also

Reference

Special Member Functions (C++)