/ | ||||
(C++11) | ||||
(C++11) |
(C++11) | ||||
(C++20) | ||||
(C++20) |
(C++11) | ||||
expression |
pointer |
specifier | ||||
specifier (C++11) | ||||
specifier (C++11) |
(C++11) | ||||
(C++11) |
(C++11) | ||||
(C++11) |
General | ||||
/ types | ||||
types | ||||
Members | ||||
pointer | ||||
-declarations | ||||
(C++11) | ||||
specifier | ||||
specifier | ||||
Special member functions | ||||
(C++11) | ||||
(C++11) | ||||
Inheritance | ||||
specifier (C++11) | ||||
specifier (C++11) |
A copy assignment operator is a non-template non-static member function with the name operator = that can be called with an argument of the same class type and copies the content of the argument without mutating the argument.
Syntax Explanation Implicitly-declared copy assignment operator Implicitly-defined copy assignment operator Deleted copy assignment operator Trivial copy assignment operator Eligible copy assignment operator Notes Example Defect reports See also |
For the formal copy assignment operator syntax, see function declaration . The syntax list below only demonstrates a subset of all valid copy assignment operator syntaxes.
return-type parameter-list | (1) | ||||||||
return-type parameter-list function-body | (2) | ||||||||
return-type parameter-list-no-default | (3) | (since C++11) | |||||||
return-type parameter-list | (4) | (since C++11) | |||||||
return-type class-name parameter-list function-body | (5) | ||||||||
return-type class-name parameter-list-no-default | (6) | (since C++11) | |||||||
class-name | - | the class whose copy assignment operator is being declared, the class type is given as in the descriptions below |
parameter-list | - | a of only one parameter, which is of type , , const T&, volatile T& or const volatile T& |
parameter-list-no-default | - | a of only one parameter, which is of type , , const T&, volatile T& or const volatile T& and does not have a default argument |
function-body | - | the of the copy assignment operator |
return-type | - | any type, but is favored in order to allow chaining asssignments |
The copy assignment operator is called whenever selected by overload resolution , e.g. when an object appears on the left side of an assignment expression.
If no user-defined copy assignment operators are provided for a class type, the compiler will always declare one as an inline public member of the class. This implicitly-declared copy assignment operator has the form T & T :: operator = ( const T & ) if all of the following is true:
Otherwise the implicitly-declared copy assignment operator is declared as T & T :: operator = ( T & ) .
Due to these rules, the implicitly-declared copy assignment operator cannot bind to a volatile lvalue argument.
A class can have multiple copy assignment operators, e.g. both T & T :: operator = ( T & ) and T & T :: operator = ( T ) . If some user-defined copy assignment operators are present, the user may still force the generation of the implicitly declared copy assignment operator with the keyword default . (since C++11)
The implicitly-declared (or defaulted on its first declaration) copy assignment operator has an exception specification as described in dynamic exception specification (until C++17) noexcept specification (since C++17)
Because the copy assignment operator is always declared for any class, the base class assignment operator is always hidden. If a using-declaration is used to bring in the assignment operator from the base class, and its argument type could be the same as the argument type of the implicit assignment operator of the derived class, the using-declaration is also hidden by the implicit declaration.
If the implicitly-declared copy assignment operator is neither deleted nor trivial, it is defined (that is, a function body is generated and compiled) by the compiler if odr-used or needed for constant evaluation (since C++14) . For union types, the implicitly-defined copy assignment copies the object representation (as by std::memmove ). For non-union class types, the operator performs member-wise copy assignment of the object's direct bases and non-static data members, in their initialization order, using built-in assignment for the scalars, memberwise copy-assignment for arrays, and copy assignment operator for class types (called non-virtually).
The implicitly-defined copy assignment operator for a class is if is a , and that is of class type (or array thereof), the assignment operator selected to copy that member is a constexpr function. | (since C++14) (until C++23) |
The implicitly-defined copy assignment operator for a class is . | (since C++23) |
The generation of the implicitly-defined copy assignment operator is deprecated if has a user-declared destructor or user-declared copy constructor. | (since C++11) |
An implicitly-declared or explicitly-defaulted (since C++11) copy assignment operator for class T is undefined (until C++11) defined as deleted (since C++11) if any of the following conditions is satisfied:
The implicitly-declared copy assignment operator for class is defined as deleted if declares a or . | (since C++11) |
The copy assignment operator for class T is trivial if all of the following is true:
A trivial copy assignment operator makes a copy of the object representation as if by std::memmove . All data types compatible with the C language (POD types) are trivially copy-assignable.
A copy assignment operator is eligible if it is either user-declared or both implicitly-declared and definable. | (until C++11) |
A copy assignment operator is eligible if it is not deleted. | (since C++11) (until C++20) |
A copy assignment operator is eligible if all following conditions are satisfied: (if any) are satisfied. than any other copy assignment operator. | (since C++20) |
Triviality of eligible copy assignment operators determines whether the class is a trivially copyable type .
If both copy and move assignment operators are provided, overload resolution selects the move assignment if the argument is an rvalue (either a prvalue such as a nameless temporary or an xvalue such as the result of std::move ), and selects the copy assignment if the argument is an lvalue (named object or a function/operator returning lvalue reference). If only the copy assignment is provided, all argument categories select it (as long as it takes its argument by value or as reference to const, since rvalues can bind to const references), which makes copy assignment the fallback for move assignment, when move is unavailable.
It is unspecified whether virtual base class subobjects that are accessible through more than one path in the inheritance lattice, are assigned more than once by the implicitly-defined copy assignment operator (same applies to move assignment ).
See assignment operator overloading for additional detail on the expected behavior of a user-defined copy-assignment operator.
[ edit ] defect reports.
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR | Applied to | Behavior as published | Correct behavior |
---|---|---|---|
C++98 | the conditions where implicitly-declared copy assignment operators are undefined did not consider multi-dimensional array types | consider these types | |
C++11 | a volatile subobject made defaulted copy assignment operators non-trivial ( ) | triviality not affected | |
C++11 | operator=(X&) = default was non-trivial | made trivial | |
C++11 | a defaulted copy assignment operator for class was not defined as deleted if is abstract and has non-copy-assignable direct virtual base classes | the operator is defined as deleted in this case | |
C++20 | a copy assignment operator was not eligible if there is another copy assignment operator which is more constrained but does not satisfy its associated constraints | it can be eligible in this case |
A copy constructor is a type of constructor that initializes an object using another object of the same class. In simple terms, a constructor which creates an object by initializing it with an object of the same class, which has been created previously is known as a copy constructor .
The process of initializing members of an object through a copy constructor is known as copy initialization . It is also called member-wise initialization because the copy constructor initializes one object with the existing object, both belonging to the same class on a member-by-member copy basis.
Copy constructor takes a reference to an object of the same class as an argument:
Here, the const qualifier is optional but is added so that we do not modify the obj by mistake.
Syntax of Copy Constructor
For a deeper understanding of constructors and memory management, check out our Complete C++ Course , which covers constructors, destructors, and advanced object management techniques.
Example 1: user defined copy constructor.
If the programmer does not define the copy constructor, the compiler does it for us.
An implicitly defined copy constructor will copy the bases and members of an object in the same order that a constructor would initialize the bases and members of the object.
If we don’t define our own copy constructor, the C++ compiler creates a default copy constructor for each class which works fine in general. However, we need to define our own copy constructor only if an object has pointers or any runtime allocation of the resource like a file handle , a network connection, etc because the default constructor does only shallow copy.
Shallow Copy means that only the pointers will be copied not the actual resources that the pointers are pointing to. This can lead to dangling pointers if the original object is deleted.
Deep copy is possible only with a user-defined copy constructor. In a user-defined copy constructor, we make sure that pointers (or references) of copied objects point to new copy of the dynamic resource allocated manually in the copy constructor using new operators.
Following is a complete C++ program to demonstrate the use of the Copy constructor. In the following String class, we must write a copy constructor.
Note: Such classes also need the overloaded assignment operator. See this article for more info – C++ Assignment Operator Overloading
If we remove the copy constructor from the above program, we don’t get the expected output. The c hanges made to str2 reflect in str1 as well which is never expected. Also, if the str1 is destroyed, the str2’s data member s will be pointing to the deallocated memory.
In C++, a copy constructor may be called in the following cases:
It is, however, not guaranteed that a copy constructor will be called in all these cases, because the C++ Standard allows the compiler to optimize the copy away in certain cases, one example is the return value optimization (sometimes referred to as RVO).
Refer to this article for more details – When is a Copy Constructor Called in C++?
In copy elision, the compiler prevents the making of extra copies by making the use to techniques such as NRVO and RVO which results in saving space and better the program complexity (both time and space); Hence making the code more optimized.
The main difference between Copy Constructor and Assignment Operator is that the Copy constructor makes a new memory storage every time it is called while the assignment operator does not make new memory storage.
Which of the following two statements calls the copy constructor and which one calls the assignment operator?
A copy constructor is called when a new object is created from an existing object, as a copy of the existing object. The assignment operator is called when an already initialized object is assigned a new value from another existing object. In the above example (1) calls the copy constructor and (2) calls the assignment operator.
Can we make the copy constructor private .
Yes, a copy constructor can be made private. When we make a copy constructor private in a class, objects of that class become non-copyable. This is particularly useful when our class has pointers or dynamically allocated resources. In such situations, we can either write our own copy constructor like the above String example or make a private copy constructor so that users get compiler errors rather than surprises at runtime.
If you pass the object by value in the copy constructor, it will result in a recursive call to the copy constructor itself. This happens because passing by value involves making a copy, and making a copy involves calling the copy constructor, leading to an infinite recursion. Using a reference avoids this recursion. So, we use reference of objects to avoid infinite calls.
One reason for passing const reference is, that we should use const in C++ wherever possible so that objects are not accidentally modified. This is one good reason for passing reference as const , but there is more to it than ‘ Why argument to a copy constructor should be const?’
Search code, repositories, users, issues, pull requests..., provide feedback.
We read every piece of feedback, and take your input very seriously.
Use saved searches to filter your results more quickly.
To see all available qualifiers, see our documentation .
Latest commit, file metadata and controls.
description | title | ms.date | helpviewer_keywords | ms.assetid | |||||
---|---|---|---|---|---|---|---|---|---|
Starting in C++11, two kinds of assignment are supported in the language: copy assignment and move assignment . In this article "assignment" means copy assignment unless explicitly stated otherwise. For information about move assignment, see Move Constructors and Move Assignment Operators (C++) .
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. So, this code copies the value of b into a :
Initialization : Initialization occurs when you declare a new object, when you pass function arguments by value, or when you return by value from a function.
You can define the semantics of "copy" for objects of class type. For example, consider this code:
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:
Use an assignment operator operator= that returns a reference to the class type and takes one parameter that's passed by const reference—for example ClassName& operator=(const ClassName& x); .
Use the copy constructor.
If you don't declare a copy constructor, the compiler generates a member-wise copy constructor for you. Similarly, if you don't declare a copy assignment operator, the compiler generates a member-wise copy assignment operator for you. Declaring a copy constructor doesn't suppress the compiler-generated copy assignment operator, and vice-versa. If you implement either one, we recommend that you implement the other one, too. When you implement both, the meaning of the code is clear.
The copy constructor takes an argument of type ClassName& , where ClassName is the name of the class. For example:
Make the type of the copy constructor's argument const ClassName& whenever possible. This prevents the copy constructor from accidentally changing the copied object. It also lets you copy from const objects.
Compiler-generated copy constructors, like user-defined copy constructors, have a single argument of type "reference to class-name ." An exception is when all base classes and member classes have copy constructors declared as taking a single argument of type const class-name & . In such a case, the compiler-generated copy constructor's argument is also const .
When the argument type to the copy constructor isn't const , initialization by copying a const object generates an error. The reverse isn't true: If the argument is const , you can initialize by copying an object that's not const .
Compiler-generated assignment operators follow the same pattern for const . They take a single argument of type ClassName& unless the assignment operators in all base and member classes take arguments of type const ClassName& . In this case, the generated assignment operator for the class takes a const argument.
When virtual base classes are initialized by copy constructors, whether compiler-generated or user-defined, they're initialized only once: at the point when they are constructed.
The implications are similar to the copy constructor. When the argument type isn't const , assignment from a const object generates an error. The reverse isn't true: If a const value is assigned to a value that's not const , the assignment succeeds.
For more information about overloaded assignment operators, see Assignment .
IMAGES
VIDEO
COMMENTS
If a new object has to be created before the copying can occur, the copy constructor is used. If a new object does not have to be created before the copying can occur, the assignment operator is used. Example for assignment operator: Base obj1(5); //calls Base class constructor.
Copy constructor and Assignment operator are similar as they are both used to initialize one object using another object. But, there are some basic differences between them: Copy constructor
There are two obvious differences between copy constructor and copy assignment operator. copy constructor NO NEED to delete old elements, it just copy construct a new object. (as it Vector v2) copy constructor NO NEED to return the this pointer. (Furthermore, all the constructor does not return a value).
Use an assignment operator operator= that returns a reference to the class type and takes one parameter that's passed by const reference—for example ClassName& operator=(const ClassName& x);. Use the copy constructor. If you don't declare a copy constructor, the compiler generates a member-wise copy constructor for you.
The difference between a copy constructor and an assignment operator is that a copy constructor helps to create a copy of an already existing object without altering the original value of the created object, whereas an assignment operator helps to assign a new value to a data member or an object in the program.
Copy assignment operator. A copy assignment operator is a non-template non-static member function with the name operator= that can be called with an argument of the same class type and copies the content of the argument without mutating the argument.
The main difference between Copy Constructor and Assignment Operator is that the Copy constructor makes a new memory storage every time it is called while the assignment operator does not make new memory storage.
A copy constructor is a constructor that is used to initialize an object with an existing object of the same type. After the copy constructor executes, the newly created object should be a copy of the object passed in as the initializer. An implicit copy constructor
Use an assignment operator operator= that returns a reference to the class type and takes one parameter that's passed by const reference—for example ClassName& operator=(const ClassName& x);. Use the copy constructor. If you don't declare a copy constructor, the compiler generates a member-wise copy constructor for you.
C++ handles object copying and assignment through two functions called copy constructors and assignment operators. While C++ will automatically provide these functions if you don't explicitly define them, in many cases you'll need to manually control how your objects are duplicated.