cppreference.com

Copy assignment operator.

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

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

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

[ edit ] Syntax

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

[ edit ] Explanation

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

The copy assignment operator is called whenever selected by overload resolution , e.g. when an object appears on the left side of an assignment expression.

[ edit ] Implicitly-declared copy assignment operator

If no user-defined copy assignment operators are provided for a class type ( struct , class , or union ), the compiler will always declare one as an inline public member of the class. This implicitly-declared copy assignment operator has the form T & T :: operator = ( const T & ) if all of the following is true:

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

Otherwise the implicitly-declared copy assignment operator is declared as T & T :: operator = ( T & ) . (Note that due to these rules, the implicitly-declared copy assignment operator cannot bind to a volatile lvalue argument.)

A class can have multiple copy assignment operators, e.g. both T & T :: operator = ( const T & ) and T & T :: operator = ( T ) . If some user-defined copy assignment operators are present, the user may still force the generation of the implicitly declared copy assignment operator with the keyword default . (since C++11)

The implicitly-declared (or defaulted on its first declaration) copy assignment operator has an exception specification as described in dynamic exception specification (until C++17) exception specification (since C++17)

Because the copy assignment operator is always declared for any class, the base class assignment operator is always hidden. If a using-declaration is used to bring in the assignment operator from the base class, and its argument type could be the same as the argument type of the implicit assignment operator of the derived class, the using-declaration is also hidden by the implicit declaration.

[ edit ] Deleted implicitly-declared copy assignment operator

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

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

Otherwise, it is defined as defaulted.

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

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

[ edit ] Trivial copy assignment operator

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

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

A trivial copy assignment operator makes a copy of the object representation as if by std::memmove . All data types compatible with the C language (POD types) are trivially copy-assignable.

[ edit ] Implicitly-defined copy assignment operator

If the implicitly-declared copy assignment operator is neither deleted nor trivial, it is defined (that is, a function body is generated and compiled) by the compiler if odr-used . For union types, the implicitly-defined copy assignment copies the object representation (as by std::memmove ). For non-union class types ( class and struct ), the operator performs member-wise copy assignment of the object's bases and non-static members, in their initialization order, using built-in assignment for the scalars and copy assignment operator for class types.

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

[ edit ] Notes

If both copy and move assignment operators are provided, overload resolution selects the move assignment if the argument is an rvalue (either a prvalue such as a nameless temporary or an xvalue such as the result of std::move ), and selects the copy assignment if the argument is an lvalue (named object or a function/operator returning lvalue reference). If only the copy assignment is provided, all argument categories select it (as long as it takes its argument by value or as reference to const, since rvalues can bind to const references), which makes copy assignment the fallback for move assignment, when move is unavailable.

It is unspecified whether virtual base class subobjects that are accessible through more than one path in the inheritance lattice, are assigned more than once by the implicitly-defined copy assignment operator (same applies to move assignment ).

See assignment operator overloading for additional detail on the expected behavior of a user-defined copy-assignment operator.

[ edit ] Example

[ edit ] defect reports.

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

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

cppreference.com

Search

Copy assignment operator

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

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

Syntax Explanation Implicitly-declared copy assignment operator Deleted implicitly-declared copy assignment operator Trivial copy assignment operator Implicitly-defined copy assignment operator Notes Copy and swap Example

[ edit ] Syntax

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

[ edit ] Explanation

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

The copy assignment operator is called whenever selected by overload resolution , e.g. when an object appears on the left side of an assignment expression.

[ edit ] Implicitly-declared copy assignment operator

If no user-defined copy assignment operators are provided for a class type ( struct , class , or union ), the compiler will always declare one as an inline public member of the class. This implicitly-declared copy assignment operator has the form T & T :: operator = ( const T & ) if all of the following is true:

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

Otherwise the implicitly-declared copy assignment operator is declared as T & T :: operator = ( T & ) . (Note that due to these rules, the implicitly-declared copy assignment operator cannot bind to a volatile lvalue argument)

A class can have multiple copy assignment operators, e.g. both T & T :: operator = ( const T & ) and T & T :: operator = ( T ) . If some user-defined copy assignment operators are present, the user may still force the generation of the implicitly declared copy assignment operator with the keyword default . (since C++11)

Because the copy assignment operator is always declared for any class, the base class assignment operator is always hidden. If a using-declaration is used to bring in the assignment operator from the base class, and its argument type could be the same as the argument type of the implicit assignment operator of the derived class, the using-declaration is also hidden by the implicit declaration.

[ edit ] Deleted implicitly-declared copy assignment operator

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

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

Otherwise, it is defined as defaulted.

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

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

[ edit ] Trivial copy assignment operator

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

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

A trivial copy assignment operator makes a copy of the object representation as if by std::memmove . All data types compatible with the C language (POD types) are trivially copy-assignable.

[ edit ] Implicitly-defined copy assignment operator

If the implicitly-declared copy assignment operator is neither deleted nor trivial, it is defined (that is, a function body is generated and compiled) by the compiler if odr-used . For union types, the implicitly-defined copy assignment copies the object representation (as by std::memmove ). For non-union class types ( class and struct ), the operator performs member-wise copy assignment of the object's bases and non-static members, in their initialization order, using built-in assignment for the scalars and copy assignment operator for class types.

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

[ edit ] Notes

If both copy and move assignment operators are provided, overload resolution selects the move assignment if the argument is an rvalue (either prvalue such as a nameless temporary or xvalue such as the result of std::move ), and selects the copy assignment if the argument is 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 ).

[ edit ] Copy and swap

Copy assignment operator can be expressed in terms of copy constructor, destructor, and the swap() member function, if one is provided:

T & T :: operator = ( T arg ) { // copy/move constructor is called to construct arg     swap ( arg ) ;     // resources exchanged between *this and arg     return * this ; }   // destructor is called to release the resources formerly held by *this

For non-throwing swap(), this form provides strong exception guarantee . For rvalue arguments, this form automatically invokes the move constructor, and is sometimes referred to as "unifying assignment operator" (as in, both copy and move). However, this approach is not always advisable due to potentially significant overhead: see assignment operator overloading for details.

[ edit ] Example

  • 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 30 November 2015, at 07:24.
  • This page has been accessed 110,155 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

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

Copy Constructor vs Assignment Operator in C++

Copy constructor and Assignment operator are similar as they are both used to initialize one object using another object. But, there are some basic differences between them:

Copy constructor Assignment operator 
It is called when a new object is created from an existing object, as a copy of the existing objectThis operator is called when an already initialized object is assigned a new value from another existing object. 
It creates a separate memory block for the new object.It does not automatically create a separate memory block or new memory space. However, if the class involves dynamic memory management, the assignment operator must first release the existing memory on the left-hand side and then allocate new memory as needed to copy the data from the right-hand side.
It is an overloaded constructor.It is a bitwise operator. 
C++ compiler implicitly provides a copy constructor, if no copy constructor is defined in the class.A bitwise copy gets created, if the Assignment operator is not overloaded. 

className(const className &obj) {

// body 

}

 

className obj1, obj2;

obj2 = obj1;

Consider the following C++ program. 

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

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

Please Login to comment...

Similar reads.

  • How to Delete Discord Servers: Step by Step Guide
  • Google increases YouTube Premium price in India: Check our the latest plans
  • California Lawmakers Pass Bill to Limit AI Replicas
  • Best 10 IPTV Service Providers in Germany
  • Content Improvement League 2024: From Good To A Great Article

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

CS 1124 — Object Oriented Programming

Copy control / big 3, copy constructor, assignment operator.

  • Inheritance

What are the "Big 3"?

The Big 3 refers to the destructor, the assignment operator and the copy constructor.

Why do we care?

Most of the time you don't. At least you haven't so far. But sometimes you need to. Suppose we have a simple class such as the following:

class SimpleClass { public: SimpleClass() { p = new int(17); } private: int* p; };

Now suppose we create an instance of SimpleClass in a function:

void aFunction() { SimpleClass simp; }

What happens when we call aFunction? More importantly, what happens when it finishes? The variable simp goes "out of scope". What happens to the the memory on the heap that simp.p was pointing at? It has become garbage. We now have a memory leak.

Solution? Write a destructor. But after you write the destructor, it will turn out that you want to write a copy constructor and an assignment operator, too. These three functions tend to go together - if you need one, you likely need the other two.

The destructor is pretty simple. It's job is to free up whatever resources need to be freed up when an object is about to be "destroyed". For us, the "resources" just refer to items or arrays that were allocated on the heap. If the object being destroyed is responsible for the memory on the heap, then it should have a destructor to free it up.

How do you write a destructor? First, what's its name? The destructor's name is the same as the name of the class, execept it starts with one extra character, know as "tilde" (rhymes with "Hilda").

Is there anything else special about the function? Glad you asked. Like the constructor(s), it does not have a return type. At all. Unlike the constructors, there is only one destructor. You can't overload it based on passing different parameters, because you don't ever pass parameters to a destructor.

In fact, you don't call the destructor. The "system" does.

So, here's a suitable destructor for our simple class.

~SimpleClass() { delete p; }

That's it. Free up the memory that was allocated for this object.

What does a constructor do? Initializes the member variables of an object when it is created. Sometimes constructors have parameters so that we can pass arguments to tell the constructor how to initialize the new object.

When the argument is another object of the same type, then we call the constructor a copy constructor. This is a very important constructor. It is called a lot. Here are four somewhat different times that the copy constructor is used:

  • SomeClass a; SomeClass b(a);
  • SomeClass a; SomeClass b = a;
  • void someFunc(SomeClass passedByValue) {}
  • SomeClass anotherFunc () { SomeClass returnedByValue; return returnedByValue; }

Items 1 and 2 above are both creating an object and initializing based on another object of the same type. In both cases , it is the copy constructor that is called.

Item 3 shows a function with a parameter that is passed by value. Passing by value uses the copy constructor to initialize the parameter.

Item 4 shows a function with a value that is returned by value. Returning by value uses the copy constructor to return a copy of the value that is being returned. (That all looks cyclical, but it actually says the right thing.)

Here's a suitable copy constructor for our simple class:

SimpleClass(const SimpleClass& rhs) { p = new int; // Allocate *p = *rhs.p; // Initialize (well, actually "set"). }

The constructor is allocating space on the heap, and initializing/setting that space to hold a copy of the value in the original. (There's gotta be a simpler way to say these things.).

Now for the last of the Big 3. But it's the biggest.

Responsibilities

The assignment operator has more responsibility than the copy constructor. Why?

The copy constructor is only initializing an object and doesn't have to worry about any information or resources that the object already has.

The assignment operator, on the other hand, is changing an object. It has to, possibly:

  • get rid of things the object already has
  • replace them with new things
  • copy over the values from the object on the "right-hand side" to the "left-hand side".

Step one is what the destructor does. Steps two and three together are what the copy constructor does. Sure it would be nice if we could just "call" those two functions - but we can't. However, it sure makes this function easier, knowing that it just consists of the same work we would have done for the other two.

In addition the assignment operator has to

  • return the right thing
  • check for self-assignment.

Member or non-member?

Member. The language doesn't give us a choice.

Return Type and Value

The assignment operator has a return type. (Neither the destructor nor the copy constructor did, so we didn't have to worry about them.) What should it be? Void? NOOOOO!!!! (No matter what you may read in "some" books.)

C++ programmers expect to be able to write things like:

That means the same as the parenthesized:

x = ( y = z ) ;

Guess what would happen if the value of the expression y = z was void. That line up there could not compile! That's why it has to have a value. What value? The same as what's in y after the assignment in parentheses.

That tells us that the type could be SomeClass. But should we return it by value or by reference? In other words, should the type be SomeClass or SomeClass&. The answer is SomeClass&. I'm not going to clutter this page with the reason. You can look at the gory details if you like. Otherwise, just remember to do it the right way.

Self-Assignment

What if a programmer writes:

What would the code we've outlined above do? The first thing we've said we should do is "get rid of the things the object already has". Hm, in our example with SomeClass, that means get rid (i.e. delete) the int on the heap. Well, that would be bit of a disaster. We could possibly arrange things so that we didn't end up destroying all our information, but we would still be doing a lot of unneccessary work.

We shouldn't be doing much of anything, other than recognizing that this is a simple no-brainer and returning x as the value of the expression.

How do we check for self-assignment? We need to know if the current object, since we said this is a member function, is the same object as the right-hand side. How can we check if two objects are exactly the same object? Check if their addresses are the same! What is the current object's address? this .

SimpleClass& operator= (const SimpleClass& rhs) { if (this != &rhs) { // Free up resources (as needed) delete p; // Allocate new resources (as needed) p = new int; // Copy over all data *p = *rhs.p; } return *this; }

Inheritance?

If derived does not do copy control.

class Base { public: Base() { cerr
int main() { cerr
Derived der: Base() Derived() main finished. ~Base()
  • We created a Derived object. As we already knew, in its constructor's initialization list it calls the Base constructor. That's why the first thing we see is Base() and after that Derived() .
  • The Derived object gets "destroyed" when its scope, main, is finished. Then, even though we didn't write any code to call it, the Base destructor gets called, resulting in the output ~Base()

Derived Destructor

Ok, so what's next? Let's start with the easiest of the Big 3, the destructor. We will add a destructor to Derived and observe what changes in the output. I won't repeat the Base class as it is not changing (for now).

class Derived : public Base { public: Derived() { cerr
Derived der: Base() Derived() main finished. ~Derived() ~Base()

What happened this time? Simple, when the Derived object was being destroyed, its destructor was called, resulting in the output ~Derived() . The Derived destructor, when it was done, automatically called the Base class destructor. We didn't have to do a thing!

Derived Copy Constructor

Derived der; Base() Derived() Derived der2(der); Base() Derived(const Derived&) main finished. ~Derived() ~Base() ~Derived() ~Base()

How should a Derived object get copied? Same idea here as when we asked how a Derived object should get initialized back when we started talking about inheritance. Always take care of the Base portion first. Idea is that we want a "firm foundation" to build the Derived portion on top of.

Derived der; Base() Derived() Derived der2(der); Base(const Base&) Derived(const Derived&) main finished. ~Derived() ~Base() ~Derived() ~Base()

The only change is that now we get the correct consturctor for Base being called when we make a copy of our Derived object.

Derived Assignment Operator

One more of the Big 3 to go, the assignment operator. As we did with the copy constructor, first we will write our Derived assignment operator the same way we did the one in the Base class and provide a test program.

class Derived : public Base { public: Derived() { cerr Derived& operator= (const Derived& rhs) { cerr }; int main() { cerr cerr cerr
Derived der; Base() Derived() Derived der2; Base() Derived() der = der2; operator=(const Derived&) main finished. ~Derived() ~Base() ~Derived() ~Base()
class Derived : public Base { public: Derived() { cerr Base::operator=(rhs); return *this; } };
Derived der; Base() Derived() Derived der2; Base() Derived() der = der2; operator=(const Derived&) operator=(const Base&) main finished. ~Derived() ~Base() ~Derived() ~Base()

We wee the same call to Derived's assignment operator and an additional call to Base's assignment operator.

One More Thing

We have one more job to take care of. Consider the following test code, using our current class definitions:

Derived* p = new Derived(); Base() Derived() delete p; ~Derived() ~Base() main finished.

But what happens if we change our test program just slightly? Instead of storing the address of our Derived object in a Derived pointer variable we will use a Base pointer variable.

int main() { cerr cerr
Base* p = new Derived(); Base() Derived() delete p; ~Base() main finished.
class Base { public: Base() { cerr virtual ~Base() { cerr Base& operator=(const Base& rhs) { cerr
Base* p = new Derived(); Base() Derived() delete p; ~Derived() ~Base() main finished.
  • destructor: no need to do anything
  • copy constructor: in the initialization list, call the Base copy contructor
  • assingment operator: before doing anything else, explicitly call the Base assignment operator.
  • destructor: mark it virtual.

Maintained by John Sterling ( [email protected] ). Last updated Jan. 6, 2013

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++11)
    
(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
(C++11)
(C++11)

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

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

[ edit ] Syntax

class-name class-name class-name (1)
class-name class-name const class-name (2)
class-name class-name const class-name (3) (since C++11)
class-name class-name const class-name (4) (since C++11)

[ 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 ( 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 = ( 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 ] Deleted implicitly-declared copy assignment operator

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

[ edit ] Trivial copy assignment operator

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

  • it is not user-provided (meaning, it is implicitly-defined or defaulted);
  • 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

, if any, are satisfied, and than it.
(since C++20)

Triviality of eligible copy assignment operators determines whether the class is a trivially copyable type .

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

[ 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 30 September 2022, at 01:20.
  • This page has been accessed 1,200,884 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

21.12 — Overloading the assignment operator

This browser is no longer supported.

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

  • 8 contributors

The assignment operator ( = ) is, strictly speaking, a binary operator. Its declaration is identical to any other binary operator, with the following exceptions:

  • It must be a nonstatic member function. No operator= can be declared as a nonmember function.
  • It is not inherited by derived classes.
  • A default operator= function can be generated by the compiler for class types, if none exists.

The following example illustrates how to declare an assignment operator:

The supplied argument is the right side of the expression. The operator returns the object to preserve the behavior of the assignment operator, which returns the value of the left side after the assignment is complete. This allows chaining of assignments, such as:

The copy assignment operator is not to be confused with the copy constructor. The latter is called during the construction of a new object from an existing one:

It is advisable to follow the rule of three that a class which defines a copy assignment operator should also explicitly define copy constructor, destructor, and, starting with C++11, move constructor and move assignment operator.

  • Operator Overloading
  • Copy Constructors and Copy Assignment Operators (C++)

Was this page helpful?

Additional resources

Russian cities and regions guide main page

  • Visit Our Blog about Russia to know more about Russian sights, history
  • Check out our Russian cities and regions guides
  • Follow us on Twitter and Facebook to better understand Russia
  • Info about getting Russian visa , the main airports , how to rent an apartment
  • Our Expert answers your questions about Russia, some tips about sending flowers

Russia panorama

Russian regions

  • Altay republic
  • Irkutsk oblast
  • Kemerovo oblast
  • Khakassia republic
  • Krasnoyarsk krai
  • Novosibirsk oblast
  • Omsk oblast
  • Tomsk oblast
  • Tuva republic
  • Map of Russia
  • All cities and regions
  • Blog about Russia
  • News from Russia
  • How to get a visa
  • Flights to Russia
  • Russian hotels
  • Renting apartments
  • Russian currency
  • FIFA World Cup 2018
  • Submit an article
  • Flowers to Russia
  • Ask our Expert

Tomsk city, Russia

The capital city of Tomsk oblast .

Tomsk - Overview

Tomsk is a city in Russia located in the east of Western Siberia on the banks of the Tom River, the administrative center of Tomsk Oblast.

The population of Tomsk is about 570,800 (2022), the area - 295 sq. km.

The phone code - +7 3822, the postal codes - 634000-634538.

Tomsk city flag

Tomsk city coat of arms.

Tomsk city coat of arms

Tomsk city map, Russia

Tomsk city latest news and posts from our blog:.

10 November, 2019 / Tomsk - the view from above .

History of Tomsk

Foundation of tomsk.

According to a large number of archaeological finds, people lived on the territory of today’s Tomsk long before its foundation. At the end of the 16th century, by the time the Russians began to actively explore this region, Siberian Tatars and nomadic peoples at war with them lived here.

In January 1604, a delegation headed by Toyan, the prince of the Eushta Tatars, came to Moscow to the Russian Tsar Boris Godunov with a request to accept them into Russia and to protect them from the attacks of warlike neighbors - the Yenisei Kyrgyz and Kalmyks. In response, Boris Godunov signed a charter on the construction of a town on the lands of the Eushta people on the banks of the Tom River.

In June 1604, the fortress of Tomsk was founded on the southern promontory of Voskresenskaya Mountain towering over the right bank of the Tom. Therefore, the City Day of Tomsk is celebrated on June 7th. In the fall of 1604, all construction work was completed. Tomsk became an important strategic military center. Throughout the 17th century, it protected the local population - in 1614, 1617, 1657, and 1698, the fortress repelled the raids of nomads. In 1635, the population of Tomsk was about 2 thousand people.

More Historical Facts…

Tomsk in the 18th - early 20th centuries

In the 18th century, the borders of Russia moved far to the south and east, the raids of nomads stopped, and Tomsk lost its defensive significance. In 1723, about 8.5 thousand people lived in the town. From the middle of the 18th century, due to its remoteness from the European part of the country, it was used as a place of exile. After the creation of the Siberian Route, which ran from Moscow through Tomsk, the town became an important transit trade center.

In 1804, Tomsk became the administrative center of the huge Tomsk Governorate, which included the territories of the present Republic of Altai, Altai Krai, Kemerovo, Novosibirsk, and Tomsk Oblasts, East Kazakhstan Oblast (Kazakhstan), western parts of Khakassia, and Krasnoyarsk Krai. It also became the cultural and economic center of the south of Western Siberia.

From the late 1830s to the middle of the century, the population of Tomsk grew rapidly thanks to the increasing gold mining in Siberia. In 1888, Tomsk University was opened - the first university in Siberia. At the end of the 19th century, during the construction of the Trans-Siberian Railway, it was decided that it should go much south of Tomsk. As a result, it lost its importance as a transport hub.

By the beginning of the 20th century, over 60 thousand people lived in Tomsk. The city had electric lighting, trams, and a telephone network. By 1914, Tomsk, with a population of 114 thousand people, was among the 25 largest cities of the Russian Empire and ranked first in terms of trade turnover in Siberia.

Tomsk after 1917

After the revolutionary events of 1917, Tomsk became a center for the opposition to the Bolshevik forces in Siberia. Until the end of 1919, the city served as a place for the formation and training of units of the White Army.

The period from 1918 to 1940 was a time of relative decline in Tomsk. There was a significant outflow of the population to the fast-growing Novosibirsk and other cities located on the Trans-Siberian Railway, because Tomsk lost the status of the administrative center of the region. In 1925, Tomsk became part of Siberian Krai. In 1930, it was transformed into West Siberian Krai. In 1937, Tomsk became a city of Novosibirsk Oblast.

During the Second World War, about 30 enterprises from the European part of the USSR were evacuated to Tomsk, which became the basis of the city’s industry. During the war years, the volume of industrial production in Tomsk tripled. From 1940 to 1944, the number of residents increased from 145 to 178 thousand people. On August 13, 1944, Tomsk Oblast was formed, and Tomsk became its administrative center.

In the post-war years, new industries appeared in Tomsk - optical-mechanical, electrical, mechanical rubber. Metalworking and mechanical engineering, food and light industries grew significantly. The development of the city and the region was also largely connected with the beginning of the industrial development of oil and natural gas fields.

In 1970, Tomsk, which had a large number of preserved monuments of wooden architecture of the 19th century, was given the status of a historical city. In 1989, the population of Tomsk exceeded half a million people.

In the 1990s, in Tomsk, as in most cities in Russia, there was a decline in industrial production, especially in mechanical engineering focused on military government orders. In 2004, Tomsk celebrated its 400th anniversary.

Pictures of Tomsk

Tomsk entrance sign

Tomsk entrance sign

Author: Tsigankov Konstantin

On the street in the historical center of Tomsk

On the street in the historical center of Tomsk

Author: Vladimir Kharitonov

In the residential area of Tomsk

In the residential area of Tomsk

Author: Dmitry Afonin

Tomsk - Features

Tomsk is located in the very heart of Siberia, about 3.6 thousand kilometers east of Moscow, on the border of the West Siberian Plain and the spurs of the Kuznetsk Alatau on the right bank of the Tom River, 50 km from the place of its confluence with the Ob River. The city is located on the edge of a taiga natural zone.

It was named after the Tom River on which it was founded. The researchers of the 18th century derived the hydronym “Tom” from the Ket word “tom” meaning “river”. The City Day of Tomsk is celebrated on June 7.

The climate in Tomsk is continental-cyclonic (transitional from European temperate continental to Siberian sharply continental). Winter is harsh and long, the average temperature in January is minus 17.1 degrees Celsius, in July - plus 18.7 degrees Celsius.

The international airport Tomsk (Bogashevo) named after Nikolai Kamov offers regular flights to Moscow, St. Petersburg, Yekaterinburg, Surgut, Krasnoyarsk, Barnaul, Ulan-Ude, Ufa, Nizhnevartovsk, and a number of other Russian cities.

The current coat of arms of Tomsk is based on the coat of arms adopted in 1785. The silver horse was placed on the coat of arms as a sign that “the horses of this area are the best and the Tatars living nearby have stud farms”. The silver horse remains the symbol of Tomsk to this day.

Tomsk is the oldest educational and scientific center in Siberia. Today, students make up one fifth of the population of Tomsk - more than 117 thousand people.

Wooden architecture of Siberia is a bright page in the history of Russian architecture. In Tomsk, wooden architecture is original and expressive. It is here that whole groups of wooden buildings of the late 19th - early 20th centuries have been preserved. You will need at least three days to explore the large number of local attractions.

Main Attractions of Tomsk

Voskresenskaya Gora (Mountain) - the place where Tomsk was founded. Here you can see such sights of Tomsk as Beloye (White) Lake, Voskresenskaya (Resurrection) Church built in the rare Siberian Baroque style in 1789-1807, the Makushin House of Science - an architectural monument of the early 20th century, which houses the puppet theater “Skomorokh”, the Polish Church (1833). The best view of the surroundings opens from the Museum of the History of Tomsk.

Museum of the History of Tomsk . The building of this museum stands out for its unordinary architecture - a stone building crowned by a wooden observation tower, which you can climb and see Tomsk from above. Here you can find exhibitions about peasant and merchant life, a collection of porcelain, and other interesting historical and archaeological exhibits. One of the most interesting exhibits is a wooden monument to the Russian ruble - a copy of a 1 ruble coin, but 100 times larger than the original. Bakunin Street, 3.

Lagernyy Sad (Camps Garden) - a park with an area of about 40 hectares located on the right bank of the Tom River. Several thousand years ago, ancient settlements were located on this very place. The park got its name due to the fact that the summer camps of the Tomsk infantry regiment were located here in the 18th-19th centuries. Today, it is a huge green area with a large population of animals and birds.

Novo-Sobornaya Square - the central square of Tomsk. The architectural appearance of this square began to take shape in the 1840s. In 2003, the square was decorated with a fountain, in 2004 - a monument to the students of Tomsk, and in 2006— the Victory Alley memorial complex.

Tomsk Regional Museum of Local Lore - the largest museum in Tomsk Oblast with more than 140 thousand exhibits. The museum occupies an Empire style mansion of the 19th century and is dedicated to the history and culture of the Tomsk region. Among the most interesting collections are bronze items of the 5th-2nd centuries BC, old handwritten books, Russian silver coins, ceramics, furniture, personal funds of major researchers and architects. A tour of the museum can take several hours. Lenin Avenue, 75.

Tomsk Regional Art Museum . It is housed in a magnificent red brick and sandstone mansion built in 1903. This museum has an excellent collection of paintings, graphics, sculpture, arts and crafts, and icons. The exhibition includes canvases created by European painters of the 16th-21st centuries, Russian and Soviet artists of the 18th-21st centuries. Nakhanovich Lane, 3.

Architecture of Tomsk

Beautiful wooden buildings of Tomsk

Beautiful wooden buildings of Tomsk

Author: S. Shugarov

Wooden Lutheran Church of St. Mary in Tomsk

Wooden Lutheran Church of St. Mary in Tomsk

Church of the Resurrection in Tomsk

Church of the Resurrection in Tomsk

Museum of Wooden Architecture . The exposition of this museum is devoted to the main periods in the history of Tomsk wooden architecture. The building of the museum is an architectural monument of federal significance. The main exhibits are wooden fragments of houses (window frames, cornices, pilasters, examples of carved decor). Dozens of contemporary craftsmen showcase their talents in artistic woodworking in a separate hall. Kirov Street, 7.

The First Museum of Slavic Mythology . This museum offers a look at the origins of the Slavic religion - or rather, what was before the arrival of Orthodoxy. The museum collection is dedicated to Slavic epics, folk tales, and their heroes. Zagornaya Street, 12.

“The NKVD Investigative Prison” - a memorial museum located in the basement of the former NKVD prison. It is dedicated to the memory of people who suffered from repression during the Soviet era. The complex consists of the Square of Memory and the exhibition itself. The permanent exhibition is housed in a makeshift prison hall, cells, and the investigator’s office. The collection consists of documentary materials, photographs, handicrafts of prisoners, and their personal belongings. Lenin Avenue, 44.

Monument to Anton Chekhov - an unusual sculpture standing on the embankment of the Tom River opposite the restaurant “Slavyansky Bazar” (the oldest restaurant and one of the oldest buildings in Tomsk, Lenin Square, 10). The monument was created by sculptor L.A. Usov with voluntary donations. The master embodied the image of Chekhov “through the eyes of a drunken man lying in a ditch” according to the inscription on the pedestal. In 1890, during his visit to Sakhalin, Chekhov stayed in Tomsk for a week and found this city boring and not worthy of attention.

Monument to Happiness - one of the most original monuments of Tomsk. It is a bronze figure of a full, extremely pleased, and impudent wolf from the great Soviet cartoon “Once upon a time there was a dog”. Shevchenko Street, 19/1.

Epiphany Cathedral (1777-1784) - one of the oldest churches in Tomsk. This magnificent building constructed in the Siberian Baroque style is located in the very heart of Tomsk. Lenin Square, 7.

White Mosque (1914) - a majestic building constructed in the neo-Moorish style with stone carvings, lancet windows, and doors. Lugovoy Lane, 18.

Siberian Botanical Garden . The garden covers a huge area, more than 120 hectares. There are almost 8 thousand species of plants here including tropical and subtropical. Most of the trees, shrubs, and flowers can be found outdoors. Its grandiose greenhouse is one of the largest and highest in the world. Lenin Avenue, 34/1.

Picturesque architectural monuments of Tomsk:

  • “House with Firebirds” (1890) - a fine example of wooden architecture built by the merchant Zhelyabo as a wedding gift to his daughter, an architectural monument of federal significance (Krasnoarmeyskaya st., 67/1),
  • “House with Dragons” - one of the symbols of Tomsk with 7 bizarre carved dragons (Krasnoarmeyskaya Street, 68),
  • “House with a Hipped Roof”, also known as the Tomsk Regional Russian-German House - an elegant mansion built at the beginning of the 20th century for the wealthy merchant G.M. Golovanov, a masterpiece of wooden architecture not only in Tomsk, but throughout Siberia (Krasnoarmeyskaya st., 71),
  • The mansion of the architect S.V. Khomich (1904) - the architecture of this building is so eclectic that it rather resembles a fabulous gingerbread house (Belinsky, 19),
  • Tomsk State University - this building of the oldest university in Siberia, founded in 1888, is one of the most recognizable symbols of Tomsk (Lenin Avenue, 36),
  • Garrison House of Officers named after N.N. Yakovlev - a beautiful brick building with original decor (Lenin Avenue, 50),
  • Tomsk City Hall (1899) - an eclectic three-story mansion built of red brick and light sandstone located in the city center (Lenin Avenue, 73),
  • The estate of I.D. Astashev (1842) - a magnificent palace that once belonged to the gold miner Astashev, one of the most beautiful buildings in Tomsk (Lenin Avenue, 75).

Tomsk city of Russia photos

Tomsk views.

Tomsk Railway Station

Tomsk Railway Station

Tomsk Regional Drama Theater

Tomsk Regional Drama Theater

House with a Hipped Roof in Tomsk

House with a Hipped Roof in Tomsk

Author: Stanislav Smakotin

Sights of Tomsk

Monument to Happiness in Tomsk

Monument to Happiness in Tomsk

Monument to Anton Chekhov in Tomsk

Monument to Anton Chekhov in Tomsk

Red Mosque in Tomsk

Red Mosque in Tomsk

The questions of our visitors

  • Currently 3.04/5

Rating: 3.0 /5 (179 votes cast)

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

Get the Reddit app

High quality images of the military (from all countries).

Tomsk oblast ROSN UFSB operators [1200 × 1124]

By continuing, you agree to our User Agreement and acknowledge that you understand the Privacy Policy .

Enter the 6-digit code from your authenticator app

You’ve set up two-factor authentication for this account.

Enter a 6-digit backup code

Create your username and password.

Reddit is anonymous, so your username is what you’ll go by here. Choose wisely—because once you get a name, you can’t change it.

Reset your password

Enter your email address or username and we’ll send you a link to reset your password

Check your inbox

An email with a link to reset your password was sent to the email address associated with your account

Choose a Reddit account to continue

Download GPX file for this article

Navigation menu

Copy assignment operator

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

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

Syntax Explanation Implicitly-declared copy assignment operator Deleted implicitly-declared copy assignment operator Trivial copy assignment operator Implicitly-defined copy assignment operator Notes Copy and swap Example

[ edit ] Syntax

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

[ edit ] Explanation

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

The copy assignment operator is called whenever selected by overload resolution , e.g. when an object appears on the left side of an assignment expression.

[ edit ] Implicitly-declared copy assignment operator

If no user-defined copy assignment operators are provided for a class type ( struct , class , or union ), the compiler will always declare one as an inline public member of the class. This implicitly-declared copy assignment operator has the form T & T :: operator = ( const T & ) if all of the following is true:

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

Otherwise the implicitly-declared copy assignment operator is declared as T & T :: operator = ( T & ) . (Note that due to these rules, the implicitly-declared copy assignment operator cannot bind to a volatile lvalue argument)

A class can have multiple copy assignment operators, e.g. both T & T :: operator = ( const T & ) and T & T :: operator = ( T ) . If some user-defined copy assignment operators are present, the user may still force the generation of the implicitly declared copy assignment operator with the keyword default . (since C++11)

Because the copy assignment operator is always declared for any class, the base class assignment operator is always hidden. If a using-declaration is used to bring in the assignment operator from the base class, and its argument type could be the same as the argument type of the implicit assignment operator of the derived class, the using-declaration is also hidden by the implicit declaration.

[ edit ] Deleted implicitly-declared copy assignment operator

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

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

Otherwise, it is defined as defaulted.

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

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

[ edit ] Trivial copy assignment operator

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

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

A trivial copy assignment operator makes a copy of the object representation as if by std::memmove . All data types compatible with the C language (POD types) are trivially copy-assignable.

[ edit ] Implicitly-defined copy assignment operator

If the implicitly-declared copy assignment operator is neither deleted nor trivial, it is defined (that is, a function body is generated and compiled) by the compiler if odr-used . For union types, the implicitly-defined copy assignment copies the object representation (as by std::memmove ). For non-union class types ( class and struct ), the operator performs member-wise copy assignment of the object's bases and non-static members, in their initialization order, using built-in assignment for the scalars and copy assignment operator for class types.

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

[ edit ] Notes

If both copy and move assignment operators are provided, overload resolution selects the move assignment if the argument is an rvalue (either prvalue such as a nameless temporary or xvalue such as the result of std::move ), and selects the copy assignment if the argument is 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 ).

[ edit ] Copy and swap

Copy assignment operator can be expressed in terms of copy constructor, destructor, and the swap() member function, if one is provided:

T & T :: operator = ( T arg ) { // copy/move constructor is called to construct arg     swap ( arg ) ;     // resources exchanged between *this and arg     return * this ; }   // destructor is called to release the resources formerly held by *this

For non-throwing swap(), this form provides strong exception guarantee . For rvalue arguments, this form automatically invokes the move constructor, and is sometimes referred to as "unifying assignment operator" (as in, both copy and move). However, this approach is not always advisable due to potentially significant overhead: see assignment operator overloading for details.

[ edit ] Example

  • 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 for diamond inheritance C++

I have 4 classes in a diamond inheritance hierarchy. Is it right to call both parents' assignment operator for the assignment operator in der12 class? Wouldn't it call the base operator= 2 times? Is there a better way to do it?

  • inheritance
  • operator-overloading
  • assignment-operator

Stefan Nastase's user avatar

  • 1 Your assignment operator for der12 doesn't call the copy constructor for either der1 or der2 . –  Peter Commented Jan 5, 2021 at 11:11
  • @Peter it calls the assignment operator from der1 and der2 I edited my post now, thanks! –  Stefan Nastase Commented Jan 5, 2021 at 11:15
  • 2 You can separate the assignment logic for each class, and put it in a protected member function. Then call the the ones you need from the assignment operator in each class. –  super Commented Jan 5, 2021 at 11:34
  • 1 This goes to show why you should never do diamond inheritance. They are in practice, always a bad idea. –  Passer By Commented Jan 5, 2021 at 12:16

Know someone who can answer? Share a link to this question via email , Twitter , or Facebook .

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 .

Browse other questions tagged c++ oop inheritance operator-overloading assignment-operator or ask your own question .

  • The Overflow Blog
  • Mobile Observability: monitoring performance through cracked screens, old...
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Staging Ground Reviewer Motivation
  • Feedback requested: How do you use tag hover descriptions for curating and do...

Hot Network Questions

  • How to count mismatches between two rows, column by column R?
  • Where to donate foreign-language academic books?
  • How does the summoned monster know who is my enemy?
  • What is this device in my ceiling making out of battery chirps?
  • Can unlimited Duration spells be Dismissed?
  • Determining Error Rate of Phase Shift Keying via Monte Carlo Simulation
  • What is opinion?
  • Which hash algorithms support binary input of arbitrary bit length?
  • What happens when touching a piece which cannot make a legal move?
  • What is the highest apogee of a satellite in Earth orbit?
  • How can one be honest with oneself if one IS oneself?
  • What kind of polymeric anions can be made of boron and sulfur?
  • How to frame certain cells with tabluar?
  • OpenCLLink does print build errors (MacOS M1 / Wolfram Engine 14.1)
  • Can IRS make the taxpayer pay the costs of litigation if the latter loses the case?
  • A SF novel where one character makes a "light portrait" of another one, with huge consequences
  • Is there a nonlinear resistor with a zero or infinite differential resistance?
  • Causal Reconciliation: Is this a viable way for my FTL system to preserve the course of History?
  • Which Mosaic law was in the backdrop of ceremonial hand-washing in Mark 7?
  • Can you use 'sollen' the same way as 'should' in sentences about possibility that something happens?
  • Should you refactor when there are no tests?
  • Seinfeldisms in O.R
  • How can moral disagreements be resolved when the conflicting parties are guided by fundamentally different value systems?
  • Rings demanding identity in the categorical context

copy assignment operator inheritance

IMAGES

  1. Inheritance: The Fundamental Functions

    copy assignment operator inheritance

  2. GitHub

    copy assignment operator inheritance

  3. GitHub

    copy assignment operator inheritance

  4. Inheritance: The Fundamental Functions

    copy assignment operator inheritance

  5. Solved 10. One way to implement the copy assignment operator

    copy assignment operator inheritance

  6. What is the Difference Between Copy Constructor and Assignment Operator

    copy assignment operator inheritance

VIDEO

  1. 30 gündə JavaScript. DƏRS 11 (Destructuring, Spreading)

  2. The Instanceof Operator in Inheritance

  3. Assignment on Genetics and Inheritance

  4. JAVA TOPIC -INHERITANCE VTU VIDEO ASSIGNMENT

  5. Core

  6. [Arabic] copy constructor,assignment operator, the rule of three in C++ شرح

COMMENTS

  1. c++

    An assignment operator shall be implemented by a non-static member function with exactly one parameter. Because a copy assignment operator operator= is implicitly declared for a class if not declared by the user (12.8), a base class assignment operator is always hidden by the copy assignment operator of the derived class.

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

  3. inheritance

    The copy assignment operator of the derived class that is implicitly declared by the compiler hides assignment operators of the base class. Use using declaration in the derived class the following way. using A::operator =; B():A(){}; virtual ~B(){}; virtual void doneit(){myWrite();} Another approach is to redeclare the virtual assignment ...

  4. Copy assignment operator

    Copy assignment operator. 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.

  5. Copy assignment operator

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

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

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

  8. Derived classes

    Public inheritance models the subtyping relationship of object-oriented programming: the derived class object IS-A base class object. References and pointers to a derived object are expected to be usable by any code that expects references or pointers to any of its public bases (see LSP) or, in DbC terms, a derived class should maintain class ...

  9. CS 1124

    That's it for dealing with copy control and inheritance: Derived: destructor: no need to do anything; copy constructor: in the initialization list, call the Base copy contructor; assingment operator: before doing anything else, explicitly call the Base assignment operator. Base: destructor: mark it virtual. Home

  10. Copy assignment operator

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

  11. 21.12

    21.12 — Overloading the assignment operator. 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 .

  12. Assignment

    A default operator= function can be generated by the compiler for class types, if none exists. The following example illustrates how to declare an assignment operator: int _x, _y; // Right side of copy assignment is the argument. Point& operator=(const Point&); // Define copy assignment operator. _x = otherPoint._x;

  13. Tomsk city, Russia travel guide

    Tomsk - Overview. Tomsk is a city in Russia located in the east of Western Siberia on the banks of the Tom River, the administrative center of Tomsk Oblast. The population of Tomsk is about 570,800 (2022), the area - 295 sq. km. The phone code - +7 3822, the postal codes - 634000-634538. Local time in Tomsk city is August 26, 11:33 am (+7 UTC).

  14. Tomsk Oblast

    Tomsk Oblast (Russian: То́мская о́бласть, romanized: Tomskaya oblast') is a federal subject of Russia (an oblast).It lies in the southeastern West Siberian Plain, in the southwest of the Siberian Federal District.Its administrative center is the city of Tomsk.Population: 1,047,394 (2010 Census).[9]The development of the territory which now constitutes the oblast began in the ...

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

  16. Tomsk oblast ROSN UFSB operators [1200 × 1124]

    Tomsk oblast ROSN UFSB operators [1200 × 1124] comments sorted by Best Top New Controversial Q&A Add a Comment andrey_159 ...

  17. Tomsk Oblast

    A wintry residential street in Tomsk. The Tomsk region was long an important center of Western Siberia, but lost importance after the construction of the Trans-Siberian Railway, which passed the region by to the south.But due to the discovery of oil in the late 20th century, Tomsk Oblast received a vital injection of economic importance and has reclaimed some of its status as an important ...

  18. Copy assignment operator

    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.

  19. Copy assignment operator for diamond inheritance C++

    der1::operator=(ref); der2::operator=(ref); d = ref.d; return *this; Your assignment operator for der12 doesn't call the copy constructor for either der1 or der2. @Peter it calls the assignment operator from der1 and der2 I edited my post now, thanks! You can separate the assignment logic for each class, and put it in a protected member function.