• Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

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.

what is the copy assignement operator?

At the present moment I am reading C++ 11 standard , in which (chapter 12) among special member functions is mentioned ?copy? assignment operator .

I have already faced with operator= , which is simply assignment operator

My first guess was that it is used in statements like this:

when an object is created and initialized simultaneously, I checked my assumption and got that this done by means of copy constructor(which was expected).

So, what for copy assignment operator is used, how to declare it and can you give me some example of its usage. Thanks in advance!

Community's user avatar

3 Answers 3

It's defined in the standard, 12.8/17:

A user-declared copy assignment operator X::operator= is a non-static non-template member function of class X with exactly one parameter of type X , X& , const X& , volatile X& or const volatile X& .

So for example:

Assignment operators are used when you assign to an object. You might think that doesn't say much, but your example code Class_name instance_name1 = instance_name2; doesn't assign to an object, it initializes one. The difference is in the grammar of the language: in both cases the = symbol precedes something called an initializer-clause , but Class_name instance_name1 = instance_name2; is a definition, whereas instance_name1 = instance_name2; on its own after instance_name1 has been defined is an expression-statement containing an assignment-expression . Assignment-expressions use assignment operators, definitions use constructors.

If the usual rules for overload resolution select an assignment operator that is a copy assignment operator, then that's when a copy assignment operator is used:

The reason there's a distinction between copy and non-copy assignment operators, is that if you declare a copy assignment operator, that suppresses the default copy assignment operator. If you declare any non-copy assignment operators, they don't suppress the default copy assignment.

Steve Jessop's user avatar

  • 1 Thank you very much for detailed explanation! Now copy assignement operator and it`s usage makes sense for me. –  spin_eight Commented Nov 7, 2012 at 10:38
  • It may be worth pointing out that the reason the standard uses the expression "copy assignment operator", and not just "assignment operator", is that it isn't unusual for classes to define assignment from some other type. For example, std::string has an assignment operator which takes a char const* (and so isn't a copy assignment operator. –  James Kanze Commented Feb 16 at 10:19

They are the same most of the time. Pedantically, the standard says:

13.5.3 Assignment [over.ass]

2) Any assignment operator, even the copy and move assignment operators, can be virtual.

(correct reference in Steve's answer)

Which leads us to believe that an assignment operator can exist without being a copy or move one.

The example given is:

which makes me believe the first one is a simple assignment operator, while the second is the copy assignment operator. This also preserves the nomenclature used by the copy constructor.

So, I'd say a copy assignment operator is an assignment operator that takes as parameter a reference (or object) of the same type.

Luchian Grigore's user avatar

The assignment operator is = , and you can overload it like so:

In this case I've made it take int , which is pretty unusual and probably not desirable. Usually you write a copy assignment operator , which means it takes a reference to a T :

Lightness Races in Orbit'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++ standards or ask your own question .

  • The Overflow Blog
  • The evolution of full stack engineers
  • One of the best ways to get value for AI coding tools: generating tests
  • Featured on Meta
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • User activation: Learnings and opportunities
  • Staging Ground Reviewer Motivation
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • Book that features clones used for retirement
  • How will the Polaris Dawn cabin pressure and oxygen partial pressure dovetail with that of their EVA suits? (100% oxygen?)
  • What is the least number of colours Peter could use to color the 3x3 square?
  • Correct syntax to add WMTS to Leaflet map
  • Is it possible for one wing to stall due to icing while the other wing doesn't ice?
  • Can flood basalt eruptions start in historical timescales?
  • "Truth Function" v.s. "Truth-Functional"
  • Philosophical dogma hindering scientific progress?
  • Should I write an email to a Latino teacher working in the US in English or Spanish?
  • Finding Exact Trigonometric Values
  • Why does friendship seem transitive with befriended function templates?
  • How do I go about writing a tragic ending in a story while making it overall satisfying to the reader?
  • Why is so much of likelihood theory focused on solving the score function equation?
  • What film is it where the antagonist uses an expandable triple knife?
  • Is this grammartically correct sentence "這藥物讓你每天都是良好的狀態"?
  • Where to put acknowledgments in a math paper
  • How can I format a partition in a mapper device?
  • Two sisters live alone in a house after the rest of their family died
  • Why were there so many OSes that had the name "DOS" in them?
  • Please help me identify my Dad's bike collection (80's-2000's)
  • An English word for "visible side". (cooking term)
  • Overstaying knowing I have a new Schengen visa
  • What prevents indoor climbing gyms from making a v18 boulder even if one hasn't been found outside?
  • How do you ensure that calendar invites won't be moved out of your inbox when your rules are executed?

assignment on copy

  • 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++

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 objectThis 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 automatically create a separate memory block or new memory space. However, if the class involves dynamic memory management, the assignment operator must first release the existing memory on the left-hand side and then allocate new memory as needed to copy the data from the right-hand side.
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.

  • Best Twitch Extensions for 2024: Top Tools for Viewers and Streamers
  • Discord Emojis List 2024: Copy and Paste
  • Best Adblockers for Twitch TV: Enjoy Ad-Free Streaming in 2024
  • PS4 vs. PS5: Which PlayStation Should You Buy in 2024?
  • Full Stack Developer Roadmap [2024 Updated]

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?

Additional resources

cppreference.com

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.

Syntax Explanation Implicitly-declared copy assignment operator Deleted implicitly-declared copy assignment operator Trivial copy assignment operator Implicitly-defined copy assignment operator Notes Example Defect reports

[ edit ] Syntax

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)

[ edit ] 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.

[ edit ] 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.

[ edit ] 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.

[ edit ] 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.

[ edit ] 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.

[ edit ] Notes

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 ] Example

[ 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++14 operator=(X&) = default was non-trivial made trivial
  • Pages with unreviewed CWG DR marker
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 9 January 2019, at 07:16.
  • This page has been accessed 570,566 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

21.12 — Overloading the assignment operator

21.12 — Overloading the assignment operator

  • Graphics and multimedia
  • Language Features
  • Unix/Linux programming
  • Source Code
  • Standard Library
  • Tips and Tricks
  • Tools and Libraries
  • Windows API
  • Copy constructors, assignment operators,

Copy constructors, assignment operators, and exception safe assignment

*

MyClass& other ); MyClass( MyClass& other ); MyClass( MyClass& other ); MyClass( MyClass& other );
MyClass* other );
MyClass { x; c; std::string s; };
MyClass& other ) : x( other.x ), c( other.c ), s( other.s ) {}
);
print_me_bad( std::string& s ) { std::cout << s << std::endl; } print_me_good( std::string& s ) { std::cout << s << std::endl; } std::string hello( ); print_me_bad( hello ); print_me_bad( std::string( ) ); print_me_bad( ); print_me_good( hello ); print_me_good( std::string( ) ); print_me_good( );
, );
=( MyClass& other ) { x = other.x; c = other.c; s = other.s; * ; }
< T > MyArray { size_t numElements; T* pElements; : size_t count() { numElements; } MyArray& =( MyArray& rhs ); };
<> MyArray<T>:: =( MyArray& rhs ) { ( != &rhs ) { [] pElements; pElements = T[ rhs.numElements ]; ( size_t i = 0; i < rhs.numElements; ++i ) pElements[ i ] = rhs.pElements[ i ]; numElements = rhs.numElements; } * ; }
<> MyArray<T>:: =( MyArray& rhs ) { MyArray tmp( rhs ); std::swap( numElements, tmp.numElements ); std::swap( pElements, tmp.pElements ); * ; }
< T > swap( T& one, T& two ) { T tmp( one ); one = two; two = tmp; }
<> MyArray<T>:: =( MyArray tmp ) { std::swap( numElements, tmp.numElements ); std::swap( pElements, tmp.pElements ); * ; }

IMAGES

  1. How to Copy an Assignment in Google Classroom: 6 Steps

    assignment on copy

  2. Copying Gradescope Assignments & Rubrics

    assignment on copy

  3. Copying an Assignment

    assignment on copy

  4. Copying an Assignment

    assignment on copy

  5. Copying Assignments to Other Courses

    assignment on copy

  6. How to write an assignment in 7 steps

    assignment on copy

VIDEO

  1. Art 1110

  2. August 11, 2024 P.G. 4th Semester Political Science #Assignment Copy #Paper_Name EC-2

  3. August 11, 2024 #P.G. 4th Semester Political Science #Assignment Copy #Paper_Name EC-5

  4. UPRTOU assignment copy geography 4th semester #education #uprtou_prayagraj #knowledgeispower

  5. August 12, 2024 #P.G. 4th Semester Political Science #Assignment Copy

  6. UPRTOU assignment copy #uprtou blis programme code???#blis assignment #

COMMENTS

  1. Copy assignment operator - cppreference.com

    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.

  2. c++ - what is the copy assignement operator? - Stack Overflow

    y = x; // uses copy assignment operator. The reason there's a distinction between copy and non-copy assignment operators, is that if you declare a copy assignment operator, that suppresses the default copy assignment operator.

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

    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.

  4. 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++).

  5. Everything You Need To Know About The Copy Assignment ...

    One of the great features of an object orientated language like C++ is a copy assignment operator that is used with operator= to create a new object from an existing one. In this post, we explain what a copy assignment operator is and its types in usage with some C++ examples.

  6. Copy assignment operator - cppreference.com - man6.org

    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. Explanation.

  7. 21.12 — Overloading the assignment operator – Learn C++

    The copy assignment operator (operator=) is used to copy values from one object to another already existing object. As of C++11, C++ also supports “Move assignment”. We discuss move assignment in lesson 22.3 -- Move constructors and move assignment.

  8. Copy constructors, assignment operators, - C++ Articles

    Copy constructors, assignment operators, and exception safe assignment. Score: 4.3/5 (3169 votes) What is a copy constructor? A copy constructor is a special constructor for a class/struct that is. used to make a copy of an existing instance. According to the C++. standard, the copy constructor for MyClass must have one of the.

  9. Assignment operator (C++) - Wikipedia">Assignment operator (C++) - Wikipedia

    The copy assignment operator, often just called the "assignment operator", is a special case of assignment operator where the source (right-hand side) and destination (left-hand side) are of the same class type.

  10. Copy assignment operator - cppreference.com - LSU">Copy assignment operator - cppreference.com - LSU

    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&. A type with a public copy assignment operator is CopyAssignable .