• C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management

Copy Constructor vs Assignment Operator in C++

  • How to Create Custom Assignment Operator in C++?
  • Assignment Operators In C++
  • Why copy constructor argument should be const in C++?
  • Advanced C++ | Virtual Copy Constructor
  • Move Assignment Operator in C++ 11
  • Self assignment check in assignment operator
  • Is assignment operator inherited?
  • Copy Constructor in C++
  • How to Implement Move Assignment Operator in C++?
  • Default Assignment Operator and References in C++
  • Can a constructor be private in C++ ?
  • When is a Copy Constructor Called in C++?
  • C++ Assignment Operator Overloading
  • std::move in Utility in C++ | Move Semantics, Move Constructors and Move Assignment Operators
  • C++ Interview questions based on constructors/ Destructors.
  • Assignment Operators in C
  • Copy Constructor in Python
  • Copy Constructor in Java
  • Constructors in Objective-C

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  Assignment operator 
It is called when a new object is created from an existing object, as a copy of the existing object This operator is called when an already initialized object is assigned a new value from another existing object. 
It creates a separate memory block for the new object. It does not create a separate memory block or new memory space.
It is an overloaded constructor. It is a bitwise operator. 
C++ compiler implicitly provides a copy constructor, if no copy constructor is defined in the class. A bitwise copy gets created, if the Assignment operator is not overloaded. 

className(const className &obj) {

// body 

}

 

className obj1, obj2;

obj2 = obj1;

Consider the following C++ program. 

Explanation: Here, t2 = t1;  calls the assignment operator , same as t2.operator=(t1); and   Test t3 = t1;  calls the copy constructor , same as Test t3(t1);

Must Read: When is a Copy Constructor Called in C++?

Please Login to comment...

Similar reads, improve your coding skills with practice.

 alt=

What kind of Experience do you want to share?

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Copy constructors and copy assignment operators (C++)

  • 8 contributors

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

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 .

Was this page helpful?

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

copy-constructors-and-copy-assignment-operators-cpp.md

Latest commit, file metadata and controls.

description title ms.date helpviewer_keywords ms.assetid

Copy constructors and copy assignment operators (C++)

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

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 .

  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Copy constructors and Assignment Operators

I wrote the following program to test when the copy constructor is called and when the assignment operator is called:

This results in the following output (just added empy lines to make it more understandable):

The second and third set behave as expected, but in the first set the copy constructor is called even though the assignment operator is used.

Is this behaviour part of the C++ standard or just a clever compiler optimization (I am using gcc 4.4.1)

  • copy-constructor

Timothy S. Van Haren's user avatar

3 Answers 3

No assignment operator is used in the first test-case. It just uses the initialization form called "copy initialization". Copy initialization does not consider explicit constructors when initializing the object.

Copy initialization is used in those cases that correspond to implicit conversions, where one does not explicitly kick off a conversion, as in function argument passing, and returning from a function.

Johannes Schaub - litb's user avatar

C++ standard 8.5/12

The initialization that occurs in argument passing, function return, throwing an exception (15.1), handling an exception (15.3), and brace-enclosed initializer lists (8.5.1) is called copy-initialization and is equivalent to the form T x = a; The initialization that occurs in new expressions (5.3.4), static_cast expressions (5.2.9), functional notation type conversions (5.2.3), and base and member initializers (12.6.2) is called direct-initialization and is equivalent to the form T x(a);

Andreas Brinck's user avatar

Your first set is according to the C++ standard, and not due to some optimization.

Section 12.8 ( [class.copy] ) of the C++ standard gives a similar example:

The last line would be the one matching your case.

stakx - no longer contributing's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c++ copy-constructor or ask your own question .

  • The Overflow Blog
  • Introducing Staging Ground: The private space to get feedback on questions...
  • How to prevent your new chatbot from giving away company secrets
  • Featured on Meta
  • The [tax] tag is being burninated
  • The return of Staging Ground to Stack Overflow
  • The 2024 Developer Survey Is Live
  • Policy: Generative AI (e.g., ChatGPT) is banned

Hot Network Questions

  • Death in the saddle
  • Dispute cancellation fees by 3rd-party airline booking
  • Find the limit of an integral using Darboux/Riemann sums
  • Effects if a human was shot by a femtosecond laser
  • What should I get paid for if I can't work due to circumstances outside of my control?
  • How to typeset commutative diagrams
  • Do you have an expression saying "when you are very hungry, bread is also delicious for you" or similar one?
  • Has ever a country by its own volition refused to join United Nations, or those which havent joined it's because they aren't recognized as such by UN?
  • My players think they found a loophole that gives them infinite poison and XP. How can I add the proper challenges to slow them down?
  • Is this a valid PZN?
  • Which program is used in this shot of the movie "The Wrong Woman"
  • Book recommendation introduction to model theory
  • Why don't professors seem to use learning strategies like spaced repetition and note-taking?
  • Is it legal to deposit a check that says pay to the order of cash
  • Datasheet recommends driving relay in an uncommon configuration
  • My vehicle shut off in traffic and will not turn on
  • Calculating Living Area on a Concentric Shellworld
  • Accumulated charge in conductors
  • Can I paraphrase an conference paper I wrote in my dissertation?
  • Bringing homemade sweet bread into Australia
  • How can I hang heavy bikes under a thick wooden shelf?
  • Visual Studio Code crashes with [...ERROR:process_memory_range.cc(75)] read out of range
  • How do I get rid of the artifacts on this sphere?
  • Why do airplanes sometimes turn more than 180 degrees after takeoff?

copy constructor call assignment operator

Copy assignment operator

(C++20)
(C++20)
(C++11)
(C++11)
(C++11)
(C++17)
General
Members
pointer
(C++11)
specifier
specifier
Special member functions
(C++11)
(C++11)
Inheritance
(C++11)
(C++11)

A copy assignment operator of class T is a non-template non-static member function with the name operator = that takes exactly one parameter of type T , T & , const T & , volatile T & , or const volatile T & . For a type to be CopyAssignable , it must have a public copy assignment operator.

class_name class_name ( class_name ) (1)
class_name class_name ( const class_name ) (2)
class_name class_name ( const class_name ) = default; (3) (since C++11)
class_name class_name ( const class_name ) = delete; (4) (since C++11)

Explanation

  • Typical declaration of a copy assignment operator when copy-and-swap idiom can be used.
  • Typical declaration of a copy assignment operator when copy-and-swap idiom cannot be used (non-swappable type or degraded performance).
  • Forcing a copy assignment operator to be generated by the compiler.
  • Avoiding implicit copy assignment.

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.

Implicitly-declared copy assignment operator

If no user-defined copy assignment operators are provided for a class type ( struct , class , or union ), 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:

  • each direct base B of T has a copy assignment operator whose parameters are B or const B & or const volatile B & ;
  • each non-static data member M of T of class type or array of class type has a copy assignment operator whose parameters are M or const M & or const volatile M & .

Otherwise the implicitly-declared copy assignment operator is declared as T & T :: operator = ( T & ) . (Note that 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 = ( const 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) exception 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.

Deleted implicitly-declared copy assignment operator

A implicitly-declared copy assignment operator for class T is defined as deleted if any of the following is true:

  • T has a user-declared move constructor;
  • T has a user-declared move assignment operator.

Otherwise, it is defined as defaulted.

A defaulted copy assignment operator for class T is defined as deleted if any of the following is true:

  • T has a non-static data member of non-class type (or array thereof) that is const ;
  • T has a non-static data member of a reference type;
  • T has a non-static data member or a direct or virtual base class that cannot be copy-assigned (overload resolution for the copy assignment fails, or selects a deleted or inaccessible function);
  • T is a union-like class , and has a variant member whose corresponding assignment operator is non-trivial.

Trivial copy assignment operator

The copy assignment operator for class T is trivial if all of the following is true:

  • it is not user-provided (meaning, it is implicitly-defined or defaulted) , , and if it is defaulted, its signature is the same as implicitly-defined (until C++14) ;
  • T has no virtual member functions;
  • T has no virtual base classes;
  • the copy assignment operator selected for every direct base of T is trivial;
  • the copy assignment operator selected for every non-static class type (or array of class type) member of T is trivial;
has no non-static data members of -qualified type. (since C++14)

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.

Implicitly-defined copy assignment operator

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 . For union types, the implicitly-defined copy assignment copies the object representation (as by std::memmove ). For non-union class types ( class and struct ), the operator performs member-wise copy assignment of the object's bases and non-static members, in their initialization order, using built-in assignment for the scalars and copy assignment operator for class types.

The generation of the implicitly-defined copy assignment operator is deprecated (since C++11) if T has a user-declared destructor or user-declared copy constructor.

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.

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++14 operator=(X&) = default was non-trivial made trivial

Why not just call the assignment operator from copy constructor?

IMAGES

  1. C++ : call copy constructor from assignment operator function

    copy constructor call assignment operator

  2. C++ : Calling assignment operator in copy constructor

    copy constructor call assignment operator

  3. C++: Constructor, Copy Constructor and Assignment operator

    copy constructor call assignment operator

  4. Copy Constructor vs Assignment Operator,Difference between Copy Constructor and Assignment Operator

    copy constructor call assignment operator

  5. PPT

    copy constructor call assignment operator

  6. PPT

    copy constructor call assignment operator

VIDEO

  1. Copy Constructor in C++ in Hindi (Lec-23)

  2. PROGRAM TO COPY CONSTRUCTOR IN C++

  3. COMSC210 Module4 3

  4. C++ class copy constructor [3]

  5. How to implement the rule of three's copy constructor

  6. Linked List, Data Structures and Algorithms Lec 8/30 [Urdu/Hindi]

COMMENTS

  1. c++ - The copy constructor and assignment operator - Stack ...

    v3 = v2; lead to call copy assignment operator. In case 2, Object v3 already exists (We have done: Vector v3{10}; ). There are two obvious differences between copy constructor and copy assignment operator.

  2. What's the difference between assignment operator and copy ...

    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.

  3. Copy Constructor vs Assignment Operator in C++ - GeeksforGeeks

    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: Consider the following C++ program. CPP. // CPP Program to demonstrate the use of copy constructor. // and assignment operator. #include <iostream> #include <stdio.h>

  4. Copy constructors and copy assignment operators (C++ ...

    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.

  5. c++ - Using copy constructor in assignment operator - Stack ...

    If you focus on the assignment operator, it calls the Obj copy constructor to construct a temporary object. Then the Obj -specific swap is called that swaps the individual members. Now, the magic is in the temp object after the swap is called.

  6. Copy Constructors and Assignment Operators - Stanford University

    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.

  7. Copy constructors and copy assignment operators (C++)

    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.

  8. Copy constructors and Assignment Operators - Stack Overflow">Copy constructors and Assignment Operators - Stack Overflow

    No assignment operator is used in the first test-case. It just uses the initialization form called "copy initialization". Copy initialization does not consider explicit constructors when initializing the object.

  9. Copy assignment operator - cppreference.com

    A copy assignment operator of class T is a non-template non-static member function with the name operator = that takes exactly one parameter of type T, T &, const T &, volatile T &, or const volatile T &. For a type to be CopyAssignable, it must have a public copy assignment operator. Syntax

  10. call the assignment operator from copy constructor?">Why not just call the assignment operator from copy constructor?

    A common mistake is to call the assignment operator from the copy constructor. Take the Array class for example. Inside the copy you might think it's simple to write: Here's the problem with this. The first thing the operator= does is to check for self assignment and delete the old memory: const Array& Array::operator= (const Array& right) { if ...