cppreference.com

Copy assignment operator.

(C++20)
(C++20)
(C++11)
(C++20)
(C++17)
(C++11)
(C++11)
General topics
(C++11)
-
-expression
block


/
(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

[ edit ] Syntax

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

[ edit ] Explanation

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, 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 & ) .

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.

[ 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 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)

[ edit ] Deleted copy assignment operator

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:

  • T has a non-static data member of a const-qualified non-class type (or possibly multi-dimensional array thereof).
  • T has a non-static data member of a reference type.
  • T has a potentially constructed subobject of class type M (or possibly multi-dimensional array thereof) such that the overload resolution as applied to find M 's copy assignment operator
  • does not result in a usable candidate, or
  • in the case of the subobject being a variant member , selects a non-trivial function.

The implicitly-declared copy assignment operator for class is defined as deleted if declares a or .

(since C++11)

[ 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);
  • 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.

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 ] Eligible copy assignment operator

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 .

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

[ edit ] See also

  • converting constructor
  • copy constructor
  • copy elision
  • default constructor
  • aggregate initialization
  • constant initialization
  • copy initialization
  • default initialization
  • direct initialization
  • initializer list
  • list initialization
  • reference initialization
  • value initialization
  • zero initialization
  • move assignment
  • move constructor
  • 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 2 February 2024, at 16:13.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

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

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

14.14 — Introduction to the copy constructor

The copy constructor

When an object is passed by value, the argument is copied into the parameter. When the argument and parameter are the same class type, the copy is made by implicitly invoking the copy constructor. Similarly, when an object is returned back to the caller by value, the copy constructor is implicitly invoked to make the copy.

  • Windows Programming
  • UNIX/Linux Programming
  • General C++ Programming
  • copy assignment operator - arrays

  copy assignment operator - arrays

copy assignment operator c example

a[n]; b[n]; a = b;
It says that in the body of the assignment operator, I need to release the previous array block but then am i not losing the array I am copying from then?
main() { std::array a = {1,2,3}; std::array b = {4,5,6}; a = b; }
std::ostream; indexOutOfBoundsException {}; intArray { : * ptr = ; size = 0; isValidIndex( index) { (index >= 0) && (index < size); } : intArray() = ; intArray( size) { (size != 0) { ptr = [size] {}; ->size = size; } } ~intArray() { [] ptr; ptr = ; } intArray( intArray& obj) { (!obj.isEmpty()) { size = obj.size; ptr = [size] {}; ( i = 0; i < size; i++) { ptr[i] = obj.ptr[i]; } } } Size() { size; } isEmpty() { (size == 0); } & [] ( index) { (!isValidIndex(index)) { indexOutOfBoundsException{}; } ptr[index]; } };
std::cout; std::cin; ostream& << (ostream &os, intArray& a) { os << ; ( i = 0; i < a.Size(); i++) { os << a[i] << ; } os << ; os; } main() { intArray a{ 3 }; a[0] = 10; a[1] = 20; a[2] = 30; intArray b = a; cout << << a << ; cout << << b << ; b[1] = 100; cout << << b << ; 0; }
a copy constructor not copy assignment ... and the built-in type is not the user-defined type intArray. It is rather different from your original post.
=( intArray& other) { ( != &other) { (size != other.size) { [] ptr; ptr = ; size = 0; (other.size > 0) ptr = [size]; size = other.size; } std::copy(other.ptr, other.ptr + size, ptr); } * ; }
main() { intArray a{ 3 }; a[0] = 10; a[1] = 20; a[2] = 30; cout << << a << ; intArray b = a; cout << << a << ; cout << << b << ; b[1] = 100; cout << << a << ; cout << << b << ; a = b; cout << << a << ; cout << << b << ; }
  • C++ Classes and Objects
  • C++ Polymorphism

C++ Inheritance

  • C++ Abstraction
  • C++ Encapsulation
  • C++ OOPs Interview Questions
  • C++ OOPs MCQ

C++ Interview Questions

C++ function overloading.

  • C++ Programs
  • C++ Preprocessor

C++ Templates

  • C++ Programming Language

C++ Overview

  • Introduction to C++ Programming Language
  • Features of C++
  • History of C++
  • Interesting Facts about C++
  • Setting up C++ Development Environment
  • Difference between C and C++
  • Writing First C++ Program - Hello World Example
  • C++ Basic Syntax
  • C++ Comments
  • Tokens in C
  • C++ Keywords
  • Difference between Keyword and Identifier in C

C++ Variables and Constants

  • C++ Variables
  • Constants in C
  • Scope of Variables in C++
  • Storage Classes in C++ with Examples
  • Static Keyword in C++

C++ Data Types and Literals

  • C++ Data Types
  • Literals in C
  • Derived Data Types in C++
  • User Defined Data Types in C++
  • Data Type Ranges and their macros in C++
  • C++ Type Modifiers
  • Type Conversion in C++
  • Casting Operators in C++

C++ Operators

  • Operators in C++
  • C++ Arithmetic Operators
  • Unary operators in C
  • Bitwise Operators in C
  • Assignment Operators in C
  • C++ sizeof Operator
  • Scope resolution operator in C++

C++ Input/Output

  • Basic Input / Output in C++
  • cout in C++
  • cerr - Standard Error Stream Object in C++
  • Manipulators in C++ with Examples

C++ Control Statements

  • Decision Making in C (if , if..else, Nested if, if-else-if )
  • C++ if Statement
  • C++ if else Statement
  • C++ if else if Ladder
  • Switch Statement in C++
  • Jump statements in C++
  • for Loop in C++
  • Range-based for loop in C++
  • C++ While Loop
  • C++ Do/While Loop

C++ Functions

  • Functions in C++
  • return statement in C++ with Examples
  • Parameter Passing Techniques in C
  • Difference Between Call by Value and Call by Reference in C
  • Default Arguments in C++
  • Inline Functions in C++
  • Lambda expression in C++

C++ Pointers and References

  • Pointers and References in C++
  • C++ Pointers
  • Dangling, Void , Null and Wild Pointers in C
  • Applications of Pointers in C
  • Understanding nullptr in C++
  • References in C++
  • Can References Refer to Invalid Location in C++?
  • Pointers vs References in C++
  • Passing By Pointer vs Passing By Reference in C++
  • When do we pass arguments by pointer?
  • Variable Length Arrays (VLAs) in C
  • Pointer to an Array | Array Pointer
  • How to print size of array parameter in C++?
  • Pass Array to Functions in C
  • What is Array Decay in C++? How can it be prevented?

C++ Strings

  • Strings in C++
  • std::string class in C++
  • Array of Strings in C++ - 5 Different Ways to Create
  • String Concatenation in C++
  • Tokenizing a string in C++
  • Substring in C++

C++ Structures and Unions

  • Structures, Unions and Enumerations in C++
  • Structures in C++
  • C++ - Pointer to Structure
  • Self Referential Structures
  • Difference Between C Structures and C++ Structures
  • Enumeration in C++
  • typedef in C++
  • Array of Structures vs Array within a Structure in C

C++ Dynamic Memory Management

  • Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
  • new and delete Operators in C++ For Dynamic Memory
  • new vs malloc() and free() vs delete in C++
  • What is Memory Leak? How can we avoid?
  • Difference between Static and Dynamic Memory Allocation in C

C++ Object-Oriented Programming

  • Object Oriented Programming in C++
  • Access Modifiers in C++
  • Friend Class and Function in C++
  • Constructors in C++
  • Default Constructors in C++
  • Copy Constructor in C++
  • Destructors in C++
  • Private Destructor in C++
  • When is a Copy Constructor Called in C++?

Shallow Copy and Deep Copy in C++

  • When Should We Write Our Own Copy Constructor in C++?
  • Does C++ compiler create default constructor when we write our own?
  • C++ Static Data Members
  • Static Member Function in C++
  • 'this' pointer in C++
  • Scope Resolution Operator vs this pointer in C++
  • Local Classes in C++
  • Nested Classes in C++
  • Enum Classes in C++ and Their Advantage over Enum DataType
  • Difference Between Structure and Class in C++
  • Why C++ is partially Object Oriented Language?

C++ Encapsulation and Abstraction

  • Encapsulation in C++
  • Abstraction in C++
  • Difference between Abstraction and Encapsulation in C++
  • Function Overriding in C++
  • Virtual Functions and Runtime Polymorphism in C++
  • Difference between Inheritance and Polymorphism
  • Function Overloading in C++
  • Constructor Overloading in C++
  • Functions that cannot be overloaded in C++
  • Function overloading and const keyword
  • Function Overloading and Return Type in C++
  • Function Overloading and float in C++
  • C++ Function Overloading and Default Arguments
  • Can main() be overloaded in C++?
  • Function Overloading vs Function Overriding in C++
  • Advantages and Disadvantages of Function Overloading in C++

C++ Operator Overloading

  • Operator Overloading in C++
  • Types of Operator Overloading in C++
  • Functors in C++
  • What are the Operators that Can be and Cannot be Overloaded in C++?
  • Inheritance in C++
  • C++ Inheritance Access
  • Multiple Inheritance in C++
  • C++ Hierarchical Inheritance
  • C++ Multilevel Inheritance
  • Constructor in Multiple Inheritance in C++
  • Inheritance and Friendship in C++
  • Does overloading work with Inheritance?

C++ Virtual Functions

  • Virtual Function in C++
  • Virtual Functions in Derived Classes in C++
  • Default Arguments and Virtual Function in C++
  • Can Virtual Functions be Inlined in C++?
  • Virtual Destructor
  • Advanced C++ | Virtual Constructor
  • Advanced C++ | Virtual Copy Constructor
  • Pure Virtual Functions and Abstract Classes in C++
  • Pure Virtual Destructor in C++
  • Can Static Functions Be Virtual in C++?
  • RTTI (Run-Time Type Information) in C++
  • Can Virtual Functions be Private in C++?

C++ Exception Handling

  • Exception Handling in C++
  • Exception Handling using classes in C++
  • Stack Unwinding in C++
  • User-defined Custom Exception with class in C++

C++ Files and Streams

  • File Handling through C++ Classes
  • I/O Redirection in C++
  • Templates in C++ with Examples
  • Template Specialization in C++
  • Using Keyword in C++ STL

C++ Standard Template Library (STL)

  • The C++ Standard Template Library (STL)
  • Containers in C++ STL (Standard Template Library)
  • Introduction to Iterators in C++
  • Algorithm Library | C++ Magicians STL Algorithm

C++ Preprocessors

  • C Preprocessors
  • C Preprocessor Directives
  • #include in C
  • Difference between Preprocessor Directives and Function Templates in C++

C++ Namespace

  • Namespace in C++ | Set 1 (Introduction)
  • namespace in C++ | Set 2 (Extending namespace and Unnamed namespace)
  • Namespace in C++ | Set 3 (Accessing, creating header, nesting and aliasing)
  • C++ Inline Namespaces and Usage of the "using" Directive Inside Namespaces

Advanced C++

  • Multithreading in C++
  • Smart Pointers in C++
  • auto_ptr vs unique_ptr vs shared_ptr vs weak_ptr in C++
  • Type of 'this' Pointer in C++
  • "delete this" in C++
  • Passing a Function as a Parameter in C++
  • Signal Handling in C++
  • Generics in C++
  • Difference between C++ and Objective C
  • Write a C program that won't compile in C++
  • Write a program that produces different results in C and C++
  • How does 'void*' differ in C and C++?
  • Type Difference of Character Literals in C and C++
  • Cin-Cout vs Scanf-Printf

C++ vs Java

  • Similarities and Difference between Java and C++
  • Comparison of Inheritance in C++ and Java
  • How Does Default Virtual Behavior Differ in C++ and Java?
  • Comparison of Exception Handling in C++ and Java
  • Foreach in C++ and Java
  • Templates in C++ vs Generics in Java
  • Floating Point Operations & Associativity in C, C++ and Java

Competitive Programming in C++

  • Competitive Programming - A Complete Guide
  • C++ tricks for competitive programming (for C++ 11)
  • Writing C/C++ code efficiently in Competitive programming
  • Why C++ is best for Competitive Programming?
  • Test Case Generation | Set 1 (Random Numbers, Arrays and Matrices)
  • Fast I/O for Competitive Programming
  • Setting up Sublime Text for C++ Competitive Programming Environment
  • How to setup Competitive Programming in Visual Studio Code for C++
  • Which C++ libraries are useful for competitive programming?
  • Common mistakes to be avoided in Competitive Programming in C++ | Beginners
  • C++ Interview Questions and Answers (2024)
  • Top C++ STL Interview Questions and Answers
  • 30 OOPs Interview Questions and Answers (2024)
  • Top C++ Exception Handling Interview Questions and Answers
  • C++ Programming Examples

In general, creating a copy of an object means to create an exact replica of the object having the same literal value, data type , and resources.

  • Copy Constructor
  • Default assignment operator
// Copy Constructor Geeks Obj1(Obj); or Geeks Obj1 = Obj; // Default assignment operator Geeks Obj2; Obj2 = Obj1;

Depending upon the resources like dynamic memory held by the object, either we need to perform Shallow Copy or Deep Copy in order to create a replica of the object. In general, if the variables of an object have been dynamically allocated, then it is required to do a Deep Copy in order to create a copy of the object.

Shallow Copy :

In shallow copy, an object is created by simply copying the data of all variables of the original object. This works well if none of the variables of the object are defined in the heap section of memory . If some variables are dynamically allocated memory from heap section, then the copied object variable will also reference the same memory location. This will create ambiguity and run-time errors, dangling pointer. Since both objects will reference to the same memory location, then change made by one will reflect those change in another object as well. Since we wanted to create a replica of the object, this purpose will not be filled by Shallow copy.  Note: C++ compiler implicitly creates a copy constructor and overloads assignment operator in order to perform shallow copy at compile time.  

copy assignment operator c example

Shallow Copy of object if some variables are defined in heap memory, then:

copy assignment operator c example

Below is the implementation of the above approach:

Deep Copy :

In Deep copy, an object is created by copying data of all variables, and it also allocates similar memory resources with the same value to the object. In order to perform Deep copy, we need to explicitly define the copy constructor and assign dynamic memory as well, if required. Also, it is required to dynamically allocate memory to the variables in the other constructors, as well.

copy assignment operator c example

Let us see the differences in a tabular form -:

 
When we create a copy of object by copying data of all member variables as it is, then it is called shallow copy  When we create an object by copying data of another object along with the values of memory resources that reside outside the object, then it is called a deep copy
A shallow copy of an object copies all of the member field values.  Deep copy is performed by implementing our own copy constructor.
In shallow copy, the two objects are not independent It copies all fields, and makes copies of dynamically allocated memory pointed to by the fields
It also creates a copy of the dynamically allocated objects If we do not create the deep copy in a rightful way then the copy will point to the original, with disastrous consequences.

Please Login to comment...

Similar reads.

  • Constructors
  • cpp-constructor
  • Difference Between
  • Programming Language

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

C# Corner

  • TECHNOLOGIES
  • An Interview Question

C#

Mastering the Null-Coalescing Operator in C#

copy assignment operator c example

  • Jitendra Mesavaniya
  • Jun 30, 2024
  • Other Artcile

Learn how to efficiently handle null values in C# using the null-coalescing operator. This guide covers the syntax, practical applications, and advanced techniques to enhance your programming skills.

Handling null values efficiently is a common requirement in software development. C# offers powerful tools to manage nulls, including the null-coalescing operator (??). This article explores the null-coalescing operator, its benefits, and how it can simplify and enhance your code.

Table of Contents

  • Introduction to Null-Coalescing Operator

Basic Usage of Null-Coalescing Operator

Combining with null-conditional operator, chaining null-coalescing operators, the null-coalescing assignment operator, practical examples.

  • Traditional Null Handling vs. Null-Coalescing Operator

Introduction

The null-coalescing operator (??) in C# allows you to provide a default value for an expression that might be null. This operator simplifies the handling of null values, making your code more readable and less error-prone.

The syntax of the null-coalescing operator is straightforward.

In this example, displayName is assigned the value "Guest" because the name is null.

The null-conditional operator (?.) can be used with the null-coalescing operator to safely navigate through potential null references.

In this example, a person.Address?.The city evaluates to null, so "Unknown" is returned.

You can chain multiple null-coalescing operators to provide multiple fallback values.

In this example, firstNonNullName is assigned the first non-null value in the chain, which is "John".

Introduced in C# 8.0, the null-coalescing assignment operator (??=) assigns a value to a variable if it is currently null.

Here, the name is assigned "Default Name" because it was initially null.

Example 1. Default Configuration.

Example 2. Safe Navigation with Fallback

Traditional Null Handling vs. Null-Coalescing Operator  

Traditional approach.

Before these operators were available, handling null values required explicit null checks, which could be verbose and cumbersome.

Modern Approach

With the null-coalescing operator and null-conditional operator, the same logic becomes much simpler and more readable.

The null-coalescing operator (??) and its companion, the null-coalescing assignment operator (??=), provide powerful and concise ways to handle null values in C#. They significantly reduce the boilerplate code needed for null checks and make your code more readable and maintainable. By mastering these operators, you can write cleaner, more robust C# code that efficiently handles null values.

  • .NET Programming
  • C# Operators
  • C# Programming
  • Null-Coalescing
  • Null-Coalescing Operator

C# Corner Ebook

Programming List with C#

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

copy assignment operator clarification

Im writing a copy assignment operator for a class I've created and I'm using a previous post as a guide: What is The Rule of Three?

Im a bit confused on one aspect of this person's explanation.

Here is their class:

Here is the copy assignment operator definition that I am using as a reference (there are at least 2 offered):

What I'm finding confusing is, why are they including the line delete[] name; ?

Here is the other example they provide:

I immediately shied away from this one because I couldn't understand why the function checks if(this != &that) and then runs delete (delete[] name;) on an array that doesn't seem to have been generated yet. When the assignment operator is invoked, is the regular constructor called immediately before the copy assignment operator function is called? Therefore meaning that we must delete the array that was generated by the classes constructor because it can only be full of junk data?

Why can't I just write: name = that.name or

This is probably really basic and I should just implement what the post suggests but my actual use-case involves an array of struct s with multiple members and so Im just having a little bit of a difficulty understanding what exactly I need to do.

I realize there are like 2.5 questions here. Any insight would be appreciated.

This is my first time implementing custom copy constructors and copy assignment operators and Im sure it will seem easy after I've done it a few times.

Thanks in advance.

  • operator-overloading
  • copy-assignment

Vlad from Moscow's user avatar

  • 1 If the old and new name would be of the same length you could reuse the name pointer. But if not, it must point to a new place. –  Ripi2 Commented Dec 16, 2019 at 21:04
  • person temp(that); std::swap(temp.name, name); std::swap(temp.age, age); return *this; Using copy/swap instead of what you have in your question, that would be the entire assignment operator, providing that there is a copy constructor and destructor. –  PaulMcKenzie Commented Dec 16, 2019 at 21:06
  • More on Copy and Swap . –  user4581301 Commented Dec 16, 2019 at 21:20
  • Can copy() and swap() be used on arrays of struct s? –  MagicGAT Commented Dec 16, 2019 at 21:22
  • 1 operator= runs on objects that already exist. The object must have been constructed at some point earlier in the code so that you can do assignment on it. E.g. Person p; /* ... */ p = q; –  M.M Commented Dec 16, 2019 at 21:52

3 Answers 3

All of this is needed to make sure that memory is managed correctly.

If I understand correctly, you need an answer to when is operator= actually called? Well, operator= is always called when two valid objects exist . One of them is being assigned to, and second one is source of data. After this operation, both object must still remain valid .

This means than inside operator= you have this object with memory allocated for a string (which was allocated in one of the contrusctors) and that object, also with memory allocated for another string.

We have to first clean up memory which is currently residing in this object, or else we would lose this pointer after assigning new momry to it.

When the assignment operator is invoked, is the regular constructor called immediately before the copy assignment operator function is called?

No. The object already exists, that's why operator= is called (and not a copy constructor).

Therefore meaning that we must delete the array that was generated by the classes constructor because it can only be full of junk data?

It is full of valid data . Your object was contructed, it has some data in it, and then you assign something else to this object.

Addendum: When is copy contructor called and when is operator= called? (see this question for more detailed information):

Yksisarvinen's user avatar

  • thank you very much, I had already accepted the first answer before I saw this. Both are quite good. Thank you for your time writing this. I will review the linked post as well. –  MagicGAT Commented Dec 16, 2019 at 21:18
What I'm finding confusing is, why are they including the line delete[] name;?

When using new and new[] to manage memory, the rule is thumb is that they should have a matching delete or delete[] . Presumably, name was previously allocated with new[] (either in the constructor or by a previous assignment), so before reassigning it on the next line with name = local_name; , we need to delete[] it.

I couldn't understand why the function checks if(this != &that)

This check is a sanity check. If you assign an object to itself, then there is no need to do anything. In fact, it could cause problems because if you delete[] name; when this points to the same object as that references, then you can no longer copy that.name because its memory has been freed.

This will make name in two different instances point to the same memory. In some cases, such shared memory is not only useful but desired. However, you have to be careful because if one of the instances executes delete[] on its name then name in the other instance is no longer valid.

Code-Apprentice's user avatar

  • name was previously allocated with new[] in that object's constructor? That is what is confusing me, why isn't the line delete[] that.name ?. I could understand if we were deleting the old object's memory resources but why are we deleting the new object's memory resources, which I didn't think were even allocated yet? Unless, the object's constructor was run before the copy assignment operator code is run. –  MagicGAT Commented Dec 16, 2019 at 21:07
  • @MagicGAT "name was previously allocated with new[] in that object's constructor?" Yes, either in the constructor or in a previous call to operator=() . –  Code-Apprentice Commented Dec 16, 2019 at 21:08
  • 1 @MagicGAT "That is what is confusing me, why isn't the line delete[] that.name ?. I could understand if we were deleting the old object's memory resources but why are we deleting the new object's memory resources" Don't think of these as the "old" vs "new" objects. They are the left and right side of the assignment operators. The object on the left presumably already has a name field that was allocated memory. But we are overwriting that memory and before we do, we need to free the memory that name points to in order to avoid a memory leak. –  Code-Apprentice Commented Dec 16, 2019 at 21:10
  • ok, that makes more sense. because if are using = on an object, it had to have been instantiated already (even if the C++ code instantiated the object and then assigned it the value of another object in the same line) –  MagicGAT Commented Dec 16, 2019 at 21:11
  • @MagicGAT Suppose you have the assignment a = b . Then if operator=() does delete[] that.name; , then b.name no longer points to a valid memory address. This will lead to surprising behavior because we don't expect the assignment to modify b . –  Code-Apprentice Commented Dec 16, 2019 at 21:12

Let's start from the question about this code snippet.

The data member name has the type char *. That is it is a pointer. Neither pointers nor characters pointed to by pointers have member functions like size .

So this code snippet is invalid and will not compile.

You could use such an approach like this

if the data member had the type std::string .

Why can't I just write: name = that.name

In this case two objects of the class will contain pointers that point to the same memory extent. So if one object will be deleted then the pointer of other object will be invalid and using it to delete the allocated memory results in undefined behavior.

The copy assignment operator may be applied only for already constructed object. That is an object of the class must already to exist and the used constructor shall initialize its data member name either by nullptr or by the address of allocated memory.

I immediately shied away from this one because I couldn't understand why the function checks if(this != &that)

This check allows to avoid self-assignment of an object. That is in the case when an object is assigned to itself the code of allocating and deleting memory will be redundant.

Because the object was already constructed and its data member name can point to allocated memory that contains a string for name.

Taking all what was said into account the copy assignment operator can look like

  • Ok, I see now that the copy assignment operator has nothing to do with instantiation. Thank you for this clarification. –  MagicGAT Commented Dec 16, 2019 at 21:27

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++ class operator-overloading copy-assignment or ask your own question .

  • The Overflow Blog
  • How to build open source apps in a highly regulated industry
  • Community Products Roadmap Update, July 2024
  • Featured on Meta
  • We spent a sprint addressing your requests — here’s how it went
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • The [lib] tag is being burninated
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Are there examples of triple entendres in English?
  • Do Christians believe that Jews and Muslims go to hell?
  • Position where last x halfmoves are determined
  • A very basic autosegmental tree using forest
  • Phantom points in QGIS do not dissapear
  • Will electrolysis hydrolyze esters?
  • I want to leave my current job during probation but I don't want to tell the next interviewer I am currently working
  • Is "conversational" used precisely in this context?
  • Unsorted Intersection
  • How soon should you apply and unapply the sustain pedal after markings?
  • Is non-temperature related Symmetry Breaking possible?
  • How do I prevent losing the binoculars?
  • Inversion naming conventions
  • Dagesh on final letter kaf
  • Joint measurability in quantum mechanics
  • Examples of distribution for which first-order condition is not enough for MLE
  • Ideal diode in parallel with resistor and voltage source
  • Is this halting time a non-standard integer?
  • Why does Paul's fight with Feyd-Rautha take so long?
  • lme4 Inconsistency
  • Imagining Graham's number in your head collapses your head to a Black hole
  • Is there a drawback to using Heart's blood rote repeatedly?
  • Book that I read around 1975, where the main character is a retired space pilot hired to steal an object from a lab called Menlo Park
  • How to NDSolve a PDE that contains the integral of the solution?

copy assignment operator c example

IMAGES

  1. Assignment Operators in C » PREP INSTA

    copy assignment operator c example

  2. Programming example: Copy assignment operator

    copy assignment operator c example

  3. [100% Working Code]

    copy assignment operator c example

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

    copy assignment operator c example

  5. Assignment Operators in C Example

    copy assignment operator c example

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

    copy assignment operator c example

VIDEO

  1. assignment Operator C Language in Telugu

  2. Assignment Operator in C Programming

  3. Augmented assignment operators in C

  4. Assignment Operator in C Programming

  5. Assignment Operator│C programming│Part# 15│Learn CSE Malayalam

  6. Operators in C language

COMMENTS

  1. Copy assignment operator

    the copy assignment operator selected for every non-static class type (or array of class type) member of T is trivial. 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.

  2. c++

    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: struct X {. int a; // an assignment operator which is not a copy assignment operator. X &operator=(int rhs) { a = rhs; return *this ...

  3. Copy Constructor vs Assignment Operator in C++

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

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

    21.12 — Overloading the assignment operator. Alex November 27, 2023. 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 .

  6. Copy constructors, assignment operators,

    An example of this is when you have a reference-counted object. boost::shared_ptr<> is example. Const correctness ... in either T's copy constructor or assignment operator throwing, you are politely required to provide a swap() overload for your type that does not throw. [Since swap() cannot return failure, and you are not allowed to throw,

  7. 22.3

    C++11 defines two new functions in service of move semantics: a move constructor, and a move assignment operator. Whereas the goal of the copy constructor and copy assignment is to make a copy of one object to another, the goal of the move constructor and move assignment is to move ownership of the resources from one object to another (which is typically much less expensive than making a copy).

  8. Copy assignment operator

    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)

  9. Copy assignment operator

    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)

  10. Assignment Operators in C

    Different types of assignment operators are shown below: 1. "=": This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example: a = 10; b = 20; ch = 'y'; 2. "+=": This operator is combination of '+' and '=' operators. This operator first adds the current ...

  11. PDF Copy Constructors and Assignment Operators

    Unless you specify otherwise, C++ will automatically provide objects a basic copy constructor and assignment operator that simply invoke the copy constructors and assignment operators of all the class's data members. In many cases, this is exactly what you want. For example, consider the following class: class MyClass {public: /* Omitted ...

  12. Copy assignment operators (C++ only)

    Copy assignment operators (C++ only) The copy assignment operator lets you create a new object from an existing one by initialization. A copy assignment operator of a class A is a nonstatic non-template member function that has one of the following forms: A::operator= (A) A::operator= (A&) A::operator= (const A&)

  13. C++ : Implementing copy constructor and copy assignment operator

    Your copy assignment operator is implemented incorrectly. The object being assigned to leaks the object its base points to.. Your default constructor is also incorrect: it leaves both base and var uninitialized, so there is no way to know whether either is valid and in the destructor, when you call delete base;, Bad Things Happen.. The easiest way to implement the copy constructor and copy ...

  14. 14.14

    The rule of three is a well known C++ principle that states that if a class requires a user-defined copy constructor, destructor, or copy assignment operator, then it probably requires all three. In C++11, this was expanded to the rule of five, which adds the move constructor and move assignment operator to the list.

  15. Everything You Need To Know About The Copy Assignment Operator In C++

    The Copy Assignment Operator in a class is a non-template non-static member function that is declared with the operator=. When you create a class or a type that is copy assignable (that you can copy with the = operator symbol), it must have a public copy assignment operator. Here is a simple syntax for the typical declaration of a copy ...

  16. Copy Constructor in C++

    In the above example (1) calls the copy constructor and (2) calls the assignment operator. See this for more details. Example - Class Where a Copy Constructor is Required 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. Example:

  17. c++

    Copy constructor is called when a new object is created from an existing object, as a copy of the existing object. And assignment operator is called when an already initialized object is assigned a new value from another existing object. Example-. t2 = t1; // calls assignment operator, same as "t2.operator=(t1);"

  18. copy assignment operator

    Your example is using plain old arrays. There is no built-in assignment operator for arrays. And if n isn't constant then the code is not proper C++. ... After a = b, with a normal copy assignment operator, a would become a logical copy of b and b would remain unchanged. With a move assignment operator, https: ...

  19. Shallow Copy and Deep Copy in C++

    In C++, the copy constructor enables us to initialize an object using another object of the same class. In this article, we will learn, how to implement a copy constructor for deep copying. Implementing a Copy Constructor for Deep CopyingIn C++, a copy constructor is used to create a copy of an object from an existing object of the same class. By d

  20. Mastering the Null-Coalescing Operator in C#

    The Null-Coalescing Assignment Operator; Practical Examples; Traditional Null Handling vs. Null-Coalescing Operator; Conclusion; Introduction. The null-coalescing operator (??) in C# allows you to provide a default value for an expression that might be null. This operator simplifies the handling of null values, making your code more readable ...

  21. c++

    This code will call the copy constructor of the class Test: Test::Test(const Test& t); Use the assignment operator on an existing Test object: Test t2; t2 = t1; As a general rule of thumb, when you need to define an operator=, then you probably need to define also a copy constructor and a destructor. See the Rule of Three for more details.

  22. c++

    Here is the copy assignment operator definition that I am using as a reference (there are at least 2 offered): // 2. copy assignment operator. person& operator=(const person& that) {. char* local_name = new char[strlen(that.name) + 1]; // If the above statement throws, // the object is still in the same state as before.