Concept

Copy constructor (C++)

Summary
In the C++ programming language, a copy constructor is a special constructor for creating a new object as a copy of an existing object. Copy constructors are the standard way of copying objects in C++, as opposed to cloning, and have C++-specific nuances. The first argument of such a constructor is a reference to an object of the same type as is being constructed (const or non-const), which might be followed by parameters of any type (all having default values). Normally the compiler automatically creates a copy constructor for each class (known as an implicit copy constructor) but for special cases the programmer creates the copy constructor, known as a user-defined copy constructor. In such cases, the compiler does not create one. Hence, there is always one copy constructor that is either defined by the user or by the system. A user-defined copy constructor is generally needed when an object owns pointers or non-shareable references, such as to a , in which case a destructor and an assignment operator should also be written (see Rule of three). Copying of objects is achieved by the use of a copy constructor and an assignment operator. A copy constructor has as its first parameter a (possibly const or volatile) reference to its own class type. It can have more arguments, but the rest must have default values associated with them. The following would be valid copy constructors for class X: X(const X& copy_from_me); X(X& copy_from_me); X(volatile X& copy_from_me); X(const volatile X& copy_from_me); X(X& copy_from_me, int = 0); X(const X& copy_from_me, double = 1.0, int = 42); The first one should be used unless there is a good reason to use one of the others. One of the differences between the first and the second is that temporaries can be copied with the first. For example: X a = X(); // valid given X(const X& copy_from_me) but not valid given X(X& copy_from_me) // because the second wants a non-const X& // to create a, the compiler first creates a temporary by invoking the default constructor // of X, then uses the copy constructor to initialize as a copy of that temporary.
About this result
This page is automatically generated and may contain information that is not correct, complete, up-to-date, or relevant to your search query. The same applies to every other page on this website. Please make sure to verify the information with EPFL's official sources.