• 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

*

Trending Articles on Technical and Non Technical topics

  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Difference Between Copy Constructor and Assignment Operator in C++

C++ is a General purpose, middle-level, case sensitive, platform independent programming language that supports object oriented programming concept. C++ was created by Bjarne Stroustrup at Bell Labs in 1979. Since C++ is a platform independent programming language, it can be used on a variety of systems, including Windows, Mac OS, and various UNIX versions.

Operators in C++ are used to perform specific operations on values and variables. The following are the list of operators used in C++

Arithmetic operators

Assignment operators

Comparison operators

Relational Operators

Logical operators

Bitwise operators

Unary operators

Ternary/Conditional operators.

From the above groups, Assignment operators are used to assign values to variables.

Before learning about copy constructors, let’s get a brief idea about constructors. A Constructor in C++ is a special method, same name as class name with parenthesis "( )", that is automatically invoked when an object is created. Constructor is used to initialize the variables of the object which is created newly.

A Copy Constructor is a type of constructor that uses another object from the same class which has been created previously, to initialize an object.

Now let’s go through the detailed concept and compare and contrast the various features of copy constructor and assignment operator.

What is Assignment operator

The use of Assignment operator is to assign a value to a variable. The left operand of the assignment operator is variable name and the right operand of the operator is value to that variable. The datatype must be same for both the operands, if not so a compilation error will be raised.

The types of assignment operators are

= operator − It only assigns the value to the variable. For example, "a=10", here the value 10 will be assigned to variable "a".

+= operator −This operator first adds the current value of the variable by the value which is on right side and then assigns the new value to variable.

–= operator − This operator first subtracts the current value of the variable by the value which is on right side and then assigns the new value to variable.

*= operator − This operator first multiplies the current value of the variable by the value which is on right side and then assigns the new value to variable.

/= operator − This operator first divides the current value of the variable by the value which is on right side and then assigns the new value to variable.

Example on Assignment Operator

Let’s see an example of assignment operator. Here we are using the assignment operator to assign values to different variables.

In the above example, we have taken two variables "a" and "b" and at first we have assigned the value of a to 5 through assignment operator "=". And we have assigned the value of a to variable b. The above code will result the output as given below.

What is a Copy Constructor?

This is often required in programming to make a separate copy of an object without impacting the original. In these cases, the copy constructor comes in use. The copy constructor is a constructor that creates an object by initializing it using a previously created object of the same class. There are two types of copy constructor.

Default Copy Constructor − When the copy Constructor is not declared, the C++ compiler creates a default Constructor that copies all member variables as they are.

User-Defined Copy Constructor − The copy constructor defined by the user is called user defined copy constructor.

The syntax for Copy Constructor is −

Copy Constructor - Example

The copy constructor is used to initialize one object from another object of the same class, to copy an object to pass as an argument to a function, and to copy an object to pass as a parameter to a function. To return an object from a function, copy the object.

Let’s see an example to understand how exactly we can use a copy constructor.

In the above example, we have taken the class name as Example, and created a constructor and passed the value 20 and 30 to the constructor. The statement Example (Example &ex) indicates the copy constructor. It copies the value of the data members previously created.

The above code will produce the following output −

In our example, we have created two objects obj1 and obj2 and we are assigning the value of obj1 to obj2.

Comparison between Copy Constructor and Assignment Operator

The main purpose of both the concepts in C++ is to assign the value, but the main difference between both is copy constructor creates a new object and assigns the value but assignment operator does not create a new object, instead it assigns the value to the data member of the same object.

The following table highlights the major differences between copy constructor and assignment operator.

The difference between a copy constructor and an assignment operator is that a copy constructor helps to create a copy of an already existing object without altering the original value of the created object, whereas an assignment operator helps to assign a new value to a data member or an object in the program.

Kiran Kumar Panigrahi

Related Articles

  • What's the difference between assignment operator and copy constructor in C++?
  • Copy constructor vs assignment operator in C++
  • Difference between Static Constructor and Instance Constructor in C#
  • Copy Constructor in C++
  • What is the difference between new operator and object() constructor in JavaScript?
  • Virtual Copy Constructor in C++
  • Difference between "new operator" and "operator new" in C++?
  • What is an assignment operator in C#?
  • Difference Between Constructor and Destructor
  • How to use an assignment operator in C#?
  • What is a copy constructor in C#?
  • When is copy constructor called in C++?
  • What is the difference between initialization and assignment of values in C#?
  • Explain the concept of logical and assignment operator in C language
  • Difference between constructor and method in Java

Kickstart Your Career

Get certified by completing the course

Learn C++

22.3 — Move constructors and move assignment

In lesson 22.1 -- Introduction to smart pointers and move semantics , we took a look at std::auto_ptr, discussed the desire for move semantics, and took a look at some of the downsides that occur when functions designed for copy semantics (copy constructors and copy assignment operators) are redefined to implement move semantics.

In this lesson, we’ll take a deeper look at how C++11 resolves these problems via move constructors and move assignment.

Recapping copy constructors and copy assignment

First, let’s take a moment to recap copy semantics.

Copy constructors are used to initialize a class by making a copy of an object of the same class. Copy assignment is used to copy one class object to another existing class object. By default, C++ will provide a copy constructor and copy assignment operator if one is not explicitly provided. These compiler-provided functions do shallow copies, which may cause problems for classes that allocate dynamic memory. So classes that deal with dynamic memory should override these functions to do deep copies.

Returning back to our Auto_ptr smart pointer class example from the first lesson in this chapter, let’s look at a version that implements a copy constructor and copy assignment operator that do deep copies, and a sample program that exercises them:

In this program, we’re using a function named generateResource() to create a smart pointer encapsulated resource, which is then passed back to function main(). Function main() then assigns that to an existing Auto_ptr3 object.

When this program is run, it prints:

(Note: You may only get 4 outputs if your compiler elides the return value from function generateResource())

That’s a lot of resource creation and destruction going on for such a simple program! What’s going on here?

Let’s take a closer look. There are 6 key steps that happen in this program (one for each printed message):

  • Inside generateResource(), local variable res is created and initialized with a dynamically allocated Resource, which causes the first “Resource acquired”.
  • Res is returned back to main() by value. We return by value here because res is a local variable -- it can’t be returned by address or reference because res will be destroyed when generateResource() ends. So res is copy constructed into a temporary object. Since our copy constructor does a deep copy, a new Resource is allocated here, which causes the second “Resource acquired”.
  • Res goes out of scope, destroying the originally created Resource, which causes the first “Resource destroyed”.
  • The temporary object is assigned to mainres by copy assignment. Since our copy assignment also does a deep copy, a new Resource is allocated, causing yet another “Resource acquired”.
  • The assignment expression ends, and the temporary object goes out of expression scope and is destroyed, causing a “Resource destroyed”.
  • At the end of main(), mainres goes out of scope, and our final “Resource destroyed” is displayed.

So, in short, because we call the copy constructor once to copy construct res to a temporary, and copy assignment once to copy the temporary into mainres, we end up allocating and destroying 3 separate objects in total.

Inefficient, but at least it doesn’t crash!

However, with move semantics, we can do better.

Move constructors and move assignment

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

Defining a move constructor and move assignment work analogously to their copy counterparts. However, whereas the copy flavors of these functions take a const l-value reference parameter (which will bind to just about anything), the move flavors of these functions use non-const rvalue reference parameters (which only bind to rvalues).

Here’s the same Auto_ptr3 class as above, with a move constructor and move assignment operator added. We’ve left in the deep-copying copy constructor and copy assignment operator for comparison purposes.

The move constructor and move assignment operator are simple. Instead of deep copying the source object (a) into the implicit object, we simply move (steal) the source object’s resources. This involves shallow copying the source pointer into the implicit object, then setting the source pointer to null.

When run, this program prints:

That’s much better!

The flow of the program is exactly the same as before. However, instead of calling the copy constructor and copy assignment operators, this program calls the move constructor and move assignment operators. Looking a little more deeply:

  • Res is returned back to main() by value. Res is move constructed into a temporary object, transferring the dynamically created object stored in res to the temporary object. We’ll talk about why this happens below.
  • Res goes out of scope. Because res no longer manages a pointer (it was moved to the temporary), nothing interesting happens here.
  • The temporary object is move assigned to mainres. This transfers the dynamically created object stored in the temporary to mainres.
  • The assignment expression ends, and the temporary object goes out of expression scope and is destroyed. However, because the temporary no longer manages a pointer (it was moved to mainres), nothing interesting happens here either.

So instead of copying our Resource twice (once for the copy constructor and once for the copy assignment), we transfer it twice. This is more efficient, as Resource is only constructed and destroyed once instead of three times.

Related content

Move constructors and move assignment should be marked as noexcept . This tells the compiler that these functions will not throw exceptions.

We introduce noexcept in lesson 27.9 -- Exception specifications and noexcept and discuss why move constructors and move assignment are marked as noexcept in lesson 27.10 -- std::move_if_noexcept .

When are the move constructor and move assignment called?

The move constructor and move assignment are called when those functions have been defined, and the argument for construction or assignment is an rvalue. Most typically, this rvalue will be a literal or temporary value.

The copy constructor and copy assignment are used otherwise (when the argument is an lvalue, or when the argument is an rvalue and the move constructor or move assignment functions aren’t defined).

Implicit move constructor and move assignment operator

The compiler will create an implicit move constructor and move assignment operator if all of the following are true:

  • There are no user-declared copy constructors or copy assignment operators.
  • There are no user-declared move constructors or move assignment operators.
  • There is no user-declared destructor.

The implicit move constructor and implicit move assignment operator both do a memberwise move. That is, each member of the moved-from object is moved to the moved-to object.

The key insight behind move semantics

You now have enough context to understand the key insight behind move semantics.

If we construct an object or do an assignment where the argument is an l-value, the only thing we can reasonably do is copy the l-value. We can’t assume it’s safe to alter the l-value, because it may be used again later in the program. If we have an expression “a = b” (where b is an lvalue), we wouldn’t reasonably expect b to be changed in any way.

However, if we construct an object or do an assignment where the argument is an r-value, then we know that r-value is just a temporary object of some kind. Instead of copying it (which can be expensive), we can simply transfer its resources (which is cheap) to the object we’re constructing or assigning. This is safe to do because the temporary will be destroyed at the end of the expression anyway, so we know it will never be used again!

C++11, through r-value references, gives us the ability to provide different behaviors when the argument is an r-value vs an l-value, enabling us to make smarter and more efficient decisions about how our objects should behave.

Key insight

Move semantics is an optimization opportunity.

Move functions should always leave both objects in a valid state

In the above examples, both the move constructor and move assignment functions set a.m_ptr to nullptr. This may seem extraneous -- after all, if a is a temporary r-value, why bother doing “cleanup” if parameter a is going to be destroyed anyway?

The answer is simple: When a goes out of scope, the destructor for a will be called, and a.m_ptr will be deleted. If at that point, a.m_ptr is still pointing to the same object as m_ptr , then m_ptr will be left as a dangling pointer. When the object containing m_ptr eventually gets used (or destroyed), we’ll get undefined behavior.

When implementing move semantics, it is important to ensure the moved-from object is left in a valid state, so that it will destruct properly (without creating undefined behavior).

Automatic l-values returned by value may be moved instead of copied

In the generateResource() function of the Auto_ptr4 example above, when variable res is returned by value, it is moved instead of copied, even though res is an l-value. The C++ specification has a special rule that says automatic objects returned from a function by value can be moved even if they are l-values. This makes sense, since res was going to be destroyed at the end of the function anyway! We might as well steal its resources instead of making an expensive and unnecessary copy.

Although the compiler can move l-value return values, in some cases it may be able to do even better by simply eliding the copy altogether (which avoids the need to make a copy or do a move at all). In such a case, neither the copy constructor nor move constructor would be called.

Disabling copying

In the Auto_ptr4 class above, we left in the copy constructor and assignment operator for comparison purposes. But in move-enabled classes, it is sometimes desirable to delete the copy constructor and copy assignment functions to ensure copies aren’t made. In the case of our Auto_ptr class, we don’t want to copy our templated object T -- both because it’s expensive, and whatever class T is may not even support copying!

Here’s a version of Auto_ptr that supports move semantics but not copy semantics:

If you were to try to pass an Auto_ptr5 l-value to a function by value, the compiler would complain that the copy constructor required to initialize the function parameter has been deleted. This is good, because we should probably be passing Auto_ptr5 by const l-value reference anyway!

Auto_ptr5 is (finally) a good smart pointer class. And, in fact the standard library contains a class very much like this one (that you should use instead), named std::unique_ptr. We’ll talk more about std::unique_ptr later in this chapter.

Another example

Let’s take a look at another class that uses dynamic memory: a simple dynamic templated array. This class contains a deep-copying copy constructor and copy assignment operator.

Now let’s use this class in a program. To show you how this class performs when we allocate a million integers on the heap, we’re going to leverage the Timer class we developed in lesson 18.4 -- Timing your code . We’ll use the Timer class to time how fast our code runs, and show you the performance difference between copying and moving.

On one of the author’s machines, in release mode, this program executed in 0.00825559 seconds.

Now let’s run the same program again, replacing the copy constructor and copy assignment with a move constructor and move assignment.

On the same machine, this program executed in 0.0056 seconds.

Comparing the runtime of the two programs, (0.00825559 - 0.0056) / 0.00825559 * 100 = 32.1% faster!

Do not implement move semantics using std::swap

Since the goal of move semantics is to move a resource from a source object to a destination object, you might think about implementing the move constructor and move assignment operator using std::swap() . However, this is a bad idea, as std::swap() calls both the move constructor and move assignment on move-capable objects, which would result in an infinite recursion. You can see this happen in the following example:

This prints:

And so on… until the stack overflows.

You can implement the move constructor and move assignment using your own swap function, as long as your swap member function does not call the move constructor or move assignment. Here’s an example of how that can be done:

This works as expected, and prints:

Deleting the move constructor and move assignment

You can delete the move constructor and move assignment using the = delete syntax in the exact same way you can delete the copy constructor and copy assignment.

If you delete the copy constructor, the compiler will not generate an implicit move constructor (making your objects neither copyable nor movable). Therefore, when deleting the copy constructor, it is useful to be explicit about what behavior you want from your move constructors. Either explicitly delete them (making it clear this is the desired behavior), or default them (making the class move-only).

The rule of five says that if the copy constructor, copy assignment, move constructor, move assignment, or destructor are defined or deleted, then each of those functions should be defined or deleted.

While deleting only the move constructor and move assignment may seem like a good idea if you want a copyable but not movable object, this has the unfortunate consequence of making the class not returnable by value in cases where mandatory copy elision does not apply. This happens because a deleted move constructor is still declared, and thus is eligible for overload resolution. And return by value will favor a deleted move constructor over a non-deleted copy constructor. This is illustrated by the following program:

guest

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.

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

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

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

[ 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

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.

[ 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 15:13.
  • This page has been accessed 1,333,785 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Learn C++ practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c++ interactively, c++ introduction.

  • C++ Variables and Literals
  • C++ Data Types
  • C++ Basic I/O
  • C++ Type Conversion
  • C++ Operators
  • C++ Comments

C++ Flow Control

  • C++ if...else
  • C++ for Loop
  • C++ do...while Loop
  • C++ continue
  • C++ switch Statement
  • C++ goto Statement
  • C++ Functions
  • C++ Function Types
  • C++ Function Overloading
  • C++ Default Argument
  • C++ Storage Class
  • C++ Recursion
  • C++ Return Reference

C++ Arrays & String

  • Multidimensional Arrays
  • C++ Function and Array
  • C++ Structures
  • Structure and Function
  • C++ Pointers to Structure
  • C++ Enumeration

C++ Object & Class

  • C++ Objects and Class

C++ Constructors

  • C++ Objects & Function
  • C++ Operator Overloading
  • C++ Pointers
  • C++ Pointers and Arrays
  • C++ Pointers and Functions
  • C++ Memory Management
  • C++ Inheritance
  • Inheritance Access Control
  • C++ Function Overriding
  • Inheritance Types
  • C++ Friend Function
  • C++ Virtual Function
  • C++ Templates

C++ Tutorials

C++ Constructor Overloading

  • C++ clock()

C++ Classes and Objects

How to pass and return object from C++ Functions?

C++ Class Templates

  • C++ Encapsulation

A constructor is a special type of member function that is called automatically when an object is created.

In C++, a constructor has the same name as that of the class , and it does not have a return type. For example,

Here, the function Wall() is a constructor of the class Wall . Notice that the constructor

  • has the same name as the class,
  • does not have a return type, and
  • C++ Default Constructor

A constructor with no parameters is known as a default constructor . For example,

Here, when the wall1 object is created, the Wall() constructor is called. This sets the length variable of the object to 5.5 .

Note: If we have not defined a constructor in our class, then the C++ compiler will automatically create a default constructor with an empty code and no parameters.

C++ Parameterized Constructor

In C++, a constructor with parameters is known as a parameterized constructor. This is the preferred method to initialize member data. For example,

Here, we have created a parameterized constructor Wall() that has two parameters: double len and double hgt . The values contained in these parameters are used to initialize the member variables length and height .

When we create an object of the Wall class, we pass the values for the member variables as arguments. The code for this is:

With the member variables thus initialized, we can now calculate the area of the wall with the calculateArea() function.

  • C++ Copy Constructor

The copy constructor in C++ is used to copy data from one object to another. For example,

In this program, we have used a copy constructor to copy the contents of one object of the Wall class to another. The code of the copy constructor is:

Notice that the parameter of this constructor has the address of an object of the Wall class.

We then assign the values of the variables of the obj object to the corresponding variables of the object, calling the copy constructor. This is how the contents of the object are copied.

In main() , we then create two objects wall1 and wall2 and then copy the contents of wall1 to wall2 :

Here, the wall2 object calls its copy constructor by passing the address of the wall1 object as its argument, i.e., &obj = &wall1 .

Note : A constructor is primarily used to initialize objects. They are also used to run a default code when an object is created.

  • C++ Friend Function and Classes

Table of Contents

  • Introduction
  • Parameterized Constructor C++

Sorry about that.

Related Tutorials

C++ Tutorial

  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
  • Compound Statements in C++
  • Rethrowing an Exception in C++
  • Variable Shadowing in C++
  • Condition Variables in C++ Multithreading
  • C++23 <print> Header
  • Literals In C++
  • How to Define Constants in C++?
  • C++ Variable Templates
  • Introduction to GUI Programming in C++
  • Concurrency in C++
  • Hybrid Inheritance In C++
  • Dereference Pointer in C
  • shared_ptr in C++
  • Nested Inline Namespaces In C++20
  • C++20 std::basic_syncbuf
  • std::shared_mutex in C++
  • Partial Template Specialization in C++
  • Pass By Reference In C
  • Address Operator & in C

Assignment Operators In C++

In C++, the assignment operator forms the backbone of many algorithms and computational processes by performing a simple operation like assigning a value to a variable. It is denoted by equal sign ( = ) and provides one of the most basic operations in any programming language that is used to assign some value to the variables in C++ or in other words, it is used to store some kind of information.

The right-hand side value will be assigned to the variable on the left-hand side. The variable and the value should be of the same data type.

The value can be a literal or another variable of the same data type.

Compound Assignment Operators

In C++, the assignment operator can be combined into a single operator with some other operators to perform a combination of two operations in one single statement. These operators are called Compound Assignment Operators. There are 10 compound assignment operators in C++:

  • Addition Assignment Operator ( += )
  • Subtraction Assignment Operator ( -= )
  • Multiplication Assignment Operator ( *= )
  • Division Assignment Operator ( /= )
  • Modulus Assignment Operator ( %= )
  • Bitwise AND Assignment Operator ( &= )
  • Bitwise OR Assignment Operator ( |= )
  • Bitwise XOR Assignment Operator ( ^= )
  • Left Shift Assignment Operator ( <<= )
  • Right Shift Assignment Operator ( >>= )

Lets see each of them in detail.

1. Addition Assignment Operator (+=)

In C++, the addition assignment operator (+=) combines the addition operation with the variable assignment allowing you to increment the value of variable by a specified expression in a concise and efficient way.

This above expression is equivalent to the expression:

2. Subtraction Assignment Operator (-=)

The subtraction assignment operator (-=) in C++ enables you to update the value of the variable by subtracting another value from it. This operator is especially useful when you need to perform subtraction and store the result back in the same variable.

3. Multiplication Assignment Operator (*=)

In C++, the multiplication assignment operator (*=) is used to update the value of the variable by multiplying it with another value.

4. Division Assignment Operator (/=)

The division assignment operator divides the variable on the left by the value on the right and assigns the result to the variable on the left.

5. Modulus Assignment Operator (%=)

The modulus assignment operator calculates the remainder when the variable on the left is divided by the value or variable on the right and assigns the result to the variable on the left.

6. Bitwise AND Assignment Operator (&=)

This operator performs a bitwise AND between the variable on the left and the value on the right and assigns the result to the variable on the left.

7. Bitwise OR Assignment Operator (|=)

The bitwise OR assignment operator performs a bitwise OR between the variable on the left and the value or variable on the right and assigns the result to the variable on the left.

8. Bitwise XOR Assignment Operator (^=)

The bitwise XOR assignment operator performs a bitwise XOR between the variable on the left and the value or variable on the right and assigns the result to the variable on the left.

9. Left Shift Assignment Operator (<<=)

The left shift assignment operator shifts the bits of the variable on the left to left by the number of positions specified on the right and assigns the result to the variable on the left.

10. Right Shift Assignment Operator (>>=)

The right shift assignment operator shifts the bits of the variable on the left to the right by a number of positions specified on the right and assigns the result to the variable on the left.

Also, it is important to note that all of the above operators can be overloaded for custom operations with user-defined data types to perform the operations we want.

Please Login to comment...

Similar reads.

  • Geeks Premier League 2023
  • Geeks Premier League
  • What are Tiktok AI Avatars?
  • Poe Introduces A Price-per-message Revenue Model For AI Bot Creators
  • Truecaller For Web Now Available For Android Users In India
  • Google Introduces New AI-powered Vids App
  • 30 OOPs Interview Questions and Answers (2024)

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.

Move Constructors and Move Assignment Operators (C++)

  • 9 contributors

This topic describes how to write a move constructor and a move assignment operator for a C++ class. A move constructor enables the resources owned by an rvalue object to be moved into an lvalue without copying. For more information about move semantics, see Rvalue Reference Declarator: && .

This topic builds upon the following C++ class, MemoryBlock , which manages a memory buffer.

The following procedures describe how to write a move constructor and a move assignment operator for the example C++ class.

To create a move constructor for a C++ class

Define an empty constructor method that takes an rvalue reference to the class type as its parameter, as demonstrated in the following example:

In the move constructor, assign the class data members from the source object to the object that is being constructed:

Assign the data members of the source object to default values. This prevents the destructor from freeing resources (such as memory) multiple times:

To create a move assignment operator for a C++ class

Define an empty assignment operator that takes an rvalue reference to the class type as its parameter and returns a reference to the class type, as demonstrated in the following example:

In the move assignment operator, add a conditional statement that performs no operation if you try to assign the object to itself.

In the conditional statement, free any resources (such as memory) from the object that is being assigned to.

The following example frees the _data member from the object that is being assigned to:

Follow steps 2 and 3 in the first procedure to transfer the data members from the source object to the object that is being constructed:

Return a reference to the current object, as shown in the following example:

Example: Complete move constructor and assignment operator

The following example shows the complete move constructor and move assignment operator for the MemoryBlock class:

Example Use move semantics to improve performance

The following example shows how move semantics can improve the performance of your applications. The example adds two elements to a vector object and then inserts a new element between the two existing elements. The vector class uses move semantics to perform the insertion operation efficiently by moving the elements of the vector instead of copying them.

This example produces the following output:

Before Visual Studio 2010, this example produced the following output:

The version of this example that uses move semantics is more efficient than the version that does not use move semantics because it performs fewer copy, memory allocation, and memory deallocation operations.

Robust Programming

To prevent resource leaks, always free resources (such as memory, file handles, and sockets) in the move assignment operator.

To prevent the unrecoverable destruction of resources, properly handle self-assignment in the move assignment operator.

If you provide both a move constructor and a move assignment operator for your class, you can eliminate redundant code by writing the move constructor to call the move assignment operator. The following example shows a revised version of the move constructor that calls the move assignment operator:

The std::move function converts the lvalue other to an rvalue.

Rvalue Reference Declarator: && std::move

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

  • Share full article

Advertisement

Supported by

Wordplay, The CROSSWORD COLUMN

Savings Plan

John Rippe and Jeff Chen collaborate on a puzzle with a big heart.

A close-up of a fiberglass model of a blue whale. The whale is gray and has stripes running down its underbelly.

By Caitlin Lovinger

Jump to: Tricky Clues | Today’s Theme

SUNDAY PUZZLE — In his print introduction to this grid, Joel Fagliano writes: “John Rippe, of Silver Spring, Md., works in the Office of Protected Resources at the National Marine Fisheries Service. Jeff Chen, of Seattle, is a writer and prolific crossword collaborator. John specifically focuses on the 112-/114-Across in his work, and this puzzle is a tribute to its impact.”

We frequently get great Sunday puzzles with historical and educational angles, but I can’t remember the last time I found myself being emotionally moved by a theme. It’s the topic, of course, which is near and dear to me. But I’m also affected by the origins of the puzzle; it was a passion project and a first crossword construction for Mr. Rippe.

A biologist at NOAA’s Fisheries Service, Mr. Rippe writes of his job helping to enforce the Endangered Species Act (more on that later): “Our agency, together with the U.S. Fish and Wildlife Service, is responsible for implementing the act to protect, conserve and recover more than 1,500 plant and animal species that are listed as threatened or endangered under the act. I personally work on the team that is responsible for determining which marine and anadromous species meet the requirements to be listed as threatened or endangered under the act, and for those species that are listed, we work to develop plans and regulations to facilitate their recovery.”

Today’s Theme

There are seven examples of today’s theme set; each is presented as a pair of down entries in the same column, at 2-/56-, 9-/70-, 16-/64-, 19-/74-, 21-/75-, 36-/96- and 40-/101-Down. The upper entry in each pair contains a smattering of circled squares, and its clue begins with “BEFORE:”; the lower entry in each pair has a clue that starts with “AFTER:”.

I did not find any of the upper clues simple. But one thing about theme entries in the down entries, when you solve a crossword the ordinary way, starting with the across clue set, is that you’re going to have some letters in place to help you along. The first theme entry I completely filled in was 36-Down, “BEFORE: Begin operating effectively,” which solves to GE T I N GE A R . The circled letters, I realized, spell TIGER.

I soon picked up on 19-Down as well. “BEFORE: Rear-end, e.g.,” is C R AS H IN T O ; in this case, the circled letters contain another creature, a RHINO. That is the case for all the upper entries, in fact.

I stumbled on this theme’s trick at 96-Down. “AFTER: Actress Rowlands” has to be GENA; this entry sits just below GE T I N GE A R at 36-Across. Note that the uncircled letters in the upper entry are G-E-N-A, meaning that once the TIGER in GE T I N GE A R disappears, you’re left with GENA. Sure enough, the clue for 74-Down — which sits right below 19-Down, C R AS H IN T O — is “AFTER: Like some statues,” which solves to CAST, and C-A-S-T is what remains after the RHINO vanishes.

Once you know the relationship between the two theme clues in each column, you can use letters from each to guess the other entry and the animal that runs in the circled letters. When you make that connection, your solve will speed up. But take a moment to appreciate what’s happening: Each animal disappears as you move through its pair of theme clues.

The animals also have something in common that is explained by this puzzle’s revealer, which spans two entries at 112- and 114-Across. The “conservation law that celebrated its 50th anniversary in December 2023” is the ENDANGERED / SPECIES ACT, which has proved to be both resilient and effective in preventing hundreds of vulnerable species , including every animal running through the upper theme entries, from going extinct. As today’s title suggests, you might call it a critical “savings plan” for the whole planet.

Tricky Clues

21A. This is sweet wordplay. The “Results of an iron deficiency?” in this puzzle are CREASES, wrinkles in clothes that need to be pressed.

30A/40A. These are two names that have appeared in the crossword for decades, almost always clued the same way. Here, they get fresh trivia questions, neither of which I recognized. At 30A, “Lydic of ‘The Daily Show’” is DESI, a comedian; this entry has been clued as “Lucille’s hubby” or some variation of it since 1953. 40A, the “App used to track fertility” is MIRA, which was a “Star in Cetus” starting in 1943 and for decades after that — until Mira Sorvino came along.

74A. “A bull market it is not!” refers to an old idiom that has to do with livestock, not the stock market. The answer is a fragile place that is often figuratively beset by bulls: a CHINA SHOP.

107A. The solution to this clue surprised me: A “Tiny ‘canvas’ on which to paint” in this puzzle is a TOENAIL. Nail art is big business, though; you can get jewels and glitter with your pedicure, these days.

88D. “Philip II of ____, father of Alexander the Great,” ruled much of classical Greece and built a palace in MACEDON, or Macedonia.

93D. This entry appears in the crossword every so often and seems to have attained some kind of classic status . “‘The Future of Law Enforcement,’ according to a 1987 movie,” refers to ROBOCOP.

Constructor Notes

John Rippe : Jeff and I brainstormed several different approaches to represent the role of the Endangered Species Act in protecting and recovering species that are at risk of extinction. I had initially approached Jeff with the vague idea of constructing an endangered-species-themed puzzle and, with his brilliance and creativity, we came up with the vanishing effect as a nice way to simulate a species going extinct. However, it was important to me that the puzzle highlighted the overwhelming success of the act in preventing that “vanishing” from occurring. Since its passage, the act has prevented extinction for over 99 percent of the species that have been listed as threatened or endangered, including a number of species that have been removed from the list because of their recovery, such as the bald eagle, the American alligator and the brown pelican, and many others that are showing positive signs toward recovery. After playing with the wording of the revealer clues a bit, we landed on the final version of the puzzle. It highlights seven taxa, each comprising one or more species that are currently listed as threatened or endangered under the act. The disappearance of the creatures represented by the paired BEFORE and AFTER entries illustrates a frightening prospect that the Endangered Species Act is in place to prevent. More than anything, I hope that this puzzle is a fun way for people to appreciate and celebrate the incredible impact of the Endangered Species Act over the past 50 years and to look forward to a promising future of species recovery in the next 50 years. Jeff Chen : It was a pleasure working with John on this one. I admire people doing great things with their lives, and the efforts of NOAA are so admirable.

Need a Lifeline?

Subscribers can take a peek at the answer key .

Trying to get back to the puzzle page? Right here .

What did you think?

It’s Game Time!

Take your puzzling skills in new directions..

WordleBot , our daily Wordle companion that tells you how skillful or lucky you are, is getting an upgrade. Here’s what to know .

The editor of Connections , our new game about finding common threads between words, talks about how she makes this daily puzzle feel fun .

We asked some of the best Sudoku  solvers in the world for their tips and tricks. Try them to  tackle even the most challenging puzzles.

Read today’s Wordle Review , and get insights on the game from our columnists.

We asked Times readers how they play Spelling Bee. The hive mind weighed in with their favorite tips and tricks .

Ready to play? Try Wordle , Spelling Bee  or The Crossword .

COMMENTS

  1. What's the difference between assignment operator and copy constructor?

    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);"

  2. Copy Constructor vs Assignment Operator in C++

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

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

  4. Copy constructors, assignment operators,

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

  5. Assignment operators

    for assignments to class type objects, the right operand could be an initializer list only when the assignment is defined by a user-defined assignment operator. removed user-defined assignment constraint. CWG 1538. C++11. E1 ={E2} was equivalent to E1 = T(E2) ( T is the type of E1 ), this introduced a C-style cast. it is equivalent to E1 = T{E2}

  6. 21.12

    The difference between the copy constructor and the copy assignment operator causes a lot of confusion for new programmers, but it's really not all that difficult. Summarizing: If a new object has to be created before the copying can occur, the copy constructor is used (note: this includes passing or returning objects by value). ...

  7. PDF Constructors and Assignment

    Copy Assignment Not really a constructor Assign an instance of a type to be a copy of another instance. Copy Constructors A copy constructor is called when an instance of a type is constructed from another instance Two ways it can be called. Copy Constructors

  8. Difference Between Copy Constructor and Assignment Operator in C++

    Syntax for assignment operator is: Class name Obj1, Obj2; Obj2=Obj1; Invoke: Copy Constructor is invoked when a new object is initialized with old object and also invoked when the object is passed to a function as non-reference parameter. Assignment operator is invoked when the value of an old object is assigned to a new object.

  9. c++

    It's always the constructor taking an int that's called in this case. This is called an implicit conversion and is semantically equivalent to the following code: CTest b(5); The assignment operator is never invoked in an initialisation. Consider the following case: CTest b = CTest(5); Here, we call the constructor (taking an int) explicitly ...

  10. 22.3

    mainres = generateResource(); // this assignment will invoke the move assignment return 0; } The move constructor and move assignment operator are simple. Instead of deep copying the source object (a) into the implicit object, we simply move (steal) the source object's resources. This involves shallow copying the source pointer into the ...

  11. Copy assignment operator

    Triviality of eligible copy assignment operators determines whether the class is a trivially copyable type. [] NoteIf 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 ...

  12. C++ Constructors: Types and Copy Constructors (With Examples)

    A constructor with no parameters is known as a default constructor.For example, // C++ program to demonstrate the use of default constructor #include <iostream> using namespace std; // declare a class class Wall { private: double length; public: // default constructor to initialize variable Wall() { length = 5.5; cout << "Creating a wall."

  13. Constructors in C++

    Constructor is a special type of member function that is used to initialize the data members for an object of a class automatically when an object of the same class is created. Constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as a constructor.

  14. Assignment Operators In C++

    In C++, the addition assignment operator (+=) combines the addition operation with the variable assignment allowing you to increment the value of variable by a specified expression in a concise and efficient way. Syntax. variable += value; This above expression is equivalent to the expression: variable = variable + value; Example.

  15. inheritance

    Normally copy constructors chain so that they are copy constructed from the base up. Here because you are calling the assignment operator the copy constructor must call the default constructor to default initialize the object from the bottom up first. Then you go down again using the assignment operator. This seems rather inefficient.

  16. Move Constructors and Move Assignment Operators (C++)

    This topic describes how to write a move constructor and a move assignment operator for a C++ class. A move constructor enables the resources owned by an rvalue object to be moved into an lvalue without copying. For more information about move semantics, see Rvalue Reference Declarator: &&. This topic builds upon the following C++ class ...

  17. PDF Assignment 7

    Assignment 7 - 100 points Object Oriented Programming and Classes What students will learn: 1) Designing classes including attributes, constructors and methods 2) Creating objects of those class types Overview: The programs you've written up to this point have started at "main" and basically executed from "top to bottom".

  18. NYT Crossword Answers for April 12, 2024

    If you are considering turning in, you are probably SLEEPY. 44A. This "Block with a horn" is an ANVIL. 7D. As a verb, "Pen" is a synonym for AUTHOR. 11D. I didn't know where ...

  19. c++

    1. What is the difference between the functionality of a copy constructor and an Assignment operator. Difference is that copy ctor constructs new object with a copy of existing one, assignment operator overrides fully constructed object with a copy. For example if you have a raw pointer to dynamically allocated memory in your class - copy ctor ...

  20. Like Some Smiles and Winks

    Constructor Notes. This is my debut puzzle for The New York Times. I have also been published by Universal, USA Today, The Los Angeles Times and The Inkubator. Recently, I constructed Puzzle No. 2 ...

  21. When assigning A=B, does this call A's or B's assignment operator?

    There's copy constructor and there's assignment operator. Since A != B, the copy assignment operator will be called. Short answer: operator = from class A, since you're assigning to class A. Long answer: A=B will not work, since A and B are class types. You probably mean: A a; B b; a = b; In which case, operator = for class A will be called ...

  22. Savings Plan

    The answer is a fragile place that is often figuratively beset by bulls: a CHINA SHOP. 107A. The solution to this clue surprised me: A "Tiny 'canvas' on which to paint" in this puzzle is a ...

  23. c++

    Copy Constructor (If no copy constructor is defined) Calls the base class copy constructor passing the src object. Then calls the copy constructor of each member using the src objects members as the value to be copied. Assignment Operator. Calls the base class assignment operator passing the src object.

  24. What is the difference between initialization and assignment?

    34. Oh my. Initialization and assignment. Well, that's confusion for sure! To initialize is to make ready for use. And when we're talking about a variable, that means giving the variable a first, useful value. And one way to do that is by using an assignment. So it's pretty subtle: assignment is one way to do initialization.

  25. What is the difference between initialization and assignment in a

    Constructor-initializers allow initialization of data members at the time of their creation. Some programmers prefer to assign initial values in the body of the constructor. However, several data types must be initialized in a constructor-initializer. The following lines summarizes them: const data members