/ | ||||
(C++11) | ||||
(C++11) |
(C++11) | ||||
(C++20) | ||||
(C++20) |
(C++11) | ||||
expression |
pointer |
specifier | ||||
specifier (C++11) | ||||
specifier (C++11) |
(C++11) | ||||
(C++11) |
(C++11) | ||||
(C++11) |
General | ||||
/ types | ||||
types | ||||
Members | ||||
pointer | ||||
-declarations | ||||
(C++11) | ||||
specifier | ||||
specifier | ||||
Special member functions | ||||
(C++11) | ||||
(C++11) | ||||
Inheritance | ||||
specifier (C++11) | ||||
specifier (C++11) |
A copy assignment operator is a non-template non-static member function with the name operator = that can be called with an argument of the same class type and copies the content of the argument without mutating the argument.
Syntax Explanation Implicitly-declared copy assignment operator Implicitly-defined copy assignment operator Deleted copy assignment operator Trivial copy assignment operator Eligible copy assignment operator Notes Example Defect reports See also |
For the formal copy assignment operator syntax, see function declaration . The syntax list below only demonstrates a subset of all valid copy assignment operator syntaxes.
return-type parameter-list | (1) | ||||||||
return-type parameter-list function-body | (2) | ||||||||
return-type parameter-list-no-default | (3) | (since C++11) | |||||||
return-type parameter-list | (4) | (since C++11) | |||||||
return-type class-name parameter-list function-body | (5) | ||||||||
return-type class-name parameter-list-no-default | (6) | (since C++11) | |||||||
class-name | - | the class whose copy assignment operator is being declared, the class type is given as in the descriptions below |
parameter-list | - | a of only one parameter, which is of type , , const T&, volatile T& or const volatile T& |
parameter-list-no-default | - | a of only one parameter, which is of type , , const T&, volatile T& or const volatile T& and does not have a default argument |
function-body | - | the of the copy assignment operator |
return-type | - | any type, but is favored in order to allow chaining asssignments |
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.
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:
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.
If the implicitly-declared copy assignment operator is neither deleted nor trivial, it is defined (that is, a function body is generated and compiled) by the compiler if odr-used or needed for constant evaluation (since C++14) . For union types, the implicitly-defined copy assignment copies the object representation (as by std::memmove ). For non-union class types, the operator performs member-wise copy assignment of the object's direct bases and non-static data members, in their initialization order, using built-in assignment for the scalars, memberwise copy-assignment for arrays, and copy assignment operator for class types (called non-virtually).
The implicitly-defined copy assignment operator for a class is if is a , and that is of class type (or array thereof), the assignment operator selected to copy that member is a constexpr function. | (since C++14) (until C++23) |
The implicitly-defined copy assignment operator for a class is . | (since C++23) |
The generation of the implicitly-defined copy assignment operator is deprecated if has a user-declared destructor or user-declared copy constructor. | (since C++11) |
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:
The implicitly-declared copy assignment operator for class is defined as deleted if declares a or . | (since C++11) |
The copy assignment operator for class T is trivial if all of the following is true:
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.
A copy assignment operator is eligible if it is either user-declared or both implicitly-declared and definable. | (until C++11) |
A copy assignment operator is eligible if it is not deleted. | (since C++11) (until C++20) |
A copy assignment operator is eligible if all following conditions are satisfied: (if any) are satisfied. than any other copy assignment operator. | (since C++20) |
Triviality of eligible copy assignment operators determines whether the class is a trivially copyable type .
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 ] defect reports.
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR | Applied to | Behavior as published | Correct behavior |
---|---|---|---|
C++98 | the conditions where implicitly-declared copy assignment operators are undefined did not consider multi-dimensional array types | consider these types | |
C++11 | a volatile subobject made defaulted copy assignment operators non-trivial ( ) | triviality not affected | |
C++11 | operator=(X&) = default was non-trivial | made trivial | |
C++11 | a defaulted copy assignment operator for class was not defined as deleted if is abstract and has non-copy-assignable direct virtual base classes | the operator is defined as deleted in this case | |
C++20 | a copy assignment operator was not eligible if there is another copy assignment operator which is more constrained but does not satisfy its associated constraints | it can be eligible in this case |
In C++, operator overloading is the concept that allows us to redefine the behavior of the already existing operator for our class. C++ provides a special function called operator function that can be used to achieve operator overloading.
In this article, we will learn the different ways in which we can define the operator function for operator overloading in C++.
We can define the operator function as the following three functions:
Similar to the above approach where we defined the overload function outside the class definition, we can define that function as a friend when we want our operator function to modify the value of the private data members.
Again, the binary operator function will take two arguments and the unary operator function will take one argument as the function is defined outside the class and there will be no this pointer.
Note: Apart from the case where we need the operator function to give access to the private memebers, we should not use the friend function to prevent the exposure of private members to public API.
Operators that cannot be overloaded when declaring that function as friend function are = () [] -> .
In this method, we create a member operator function defined inside the class. It is one of the simplest and most straightforward methods of operator overlading.
Here, the operator function takes one less argument as compared to the global operator overloads. For the binary operator, one argument will be the *this object, and the other will be taken as an argument. For unary, only * this object will be used.
Note: The operator function must ber a non-static (member function)
Explanation: In the above program, it shows that no argument is passed and no return_type value is returned, because the unary operator works on a single operand. (-) operator changes the functionality to its member function. For the (+) operator, one argument was passed and it returned an object of the same type with values of them added.
Note: d2 = -d1 will not work, because operator-() does not return any value.
We can also overload an operator as the global function which is not a friend of the class. The compiler will find the overload by matching the types of the argument. If there are multiple matching operator overloads, then it will throw an ambiguity error.
Now, the global binary operator function will take two arguments, while the global unary operator function will take a single argument.
Explanation: Here, d1 calls the operator function of its class object and takes d2 as a parameter, by which the operator function returns the object and the result will reflect in the d3 object.
It is generally preferred to overload binary operator as global function. It is because in global function, both the object or the value that can be converted to the object can be used as either left or right operand and it will work. For member operator function, it won’t work if the value that can be converted to object is used as left operand. For Example,
We overload the relational operator < for our class, then
Similar reads.
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.
I'm new to C++ and I'm starting with learncpp website. In Assignment Operator Overloading chapter has those lines of code:
The first thing is why overloading assignment have to return reference instead of value?
And second thing is since this is a pointer itself then *this will be represented as dereference so its value should be object, but return value of assignment operator is Fraction& . Do I have a misunderstanding here?
A pointer is a data type that holds a memory address of the type the pointer points to, or nullptr if it doesn't refer to anything. (Or a dangling pointer, or a garbage value... but that's a bad place.)
So dereferencing a pointer by *this means that you are now dealing with the object pointed to by the pointer. Which is why this->foo and (*this).foo do the same thing.
Why does C++ have a this pointer, rather than (say) a self reference? That's just how C++ evolved, which Bjarne Stroustrup discusses at length in his excellent book The Design and Evolution of C++.
Back to your operator= situation. In C++, you can typically do this kind of construct: x = y = z; , which is ordered like x = (y = z); due to the right-to-left association of assignment.
If your assignment was void operator=(Fraction const&) then it could not be used to do assignment chaining. Not supporting assignment chaining would be "friction" for anyone used to the expected behavior of assignment and how C++ built-in types allow chaining.
Why return Fraction& versus Fraction object, is more than a simple performance optimization. Because if you did (x = y).negate(); the hypothetical negate method would be operating on a temporary rather than on x .
why overloading assignment have to return reference instead of value?
Well, consider the semantics of assignment.
should the last line create a new temporary X object? I can't think why you'd want it to, but that would be the effect of operator= returning a value.
So why does it return a reference at all? Because built-in types have these assignment semantics:
that is, you can use the value of an assignment expression in an outer expression. The value is the same as the value of the left-hand-side after the assignment. How do you get the same behaviour for user-defined types?
For a motivating example, consider
Would it be reasonable for this to create a redundant temporary copy of the (hopefully) massive vector?
"*this" will be represented as dereference
When you dereference a pointer-to-object, you get a reference to the object. Otherwise, again, dereferencing a pointer would have to create a temporary copy of the object. Consider:
is the same as
should we be initializing a copy of the object pointed to by x ? We'd never be able to initialize the allocated object. So, the only sane thing for (*x) to evaluate to, is a reference to the object.
It returns a reference so you can perform further actions on the object after assigning to it:
If the assignment operator returned by value then you would call doSomething() on the unnamed temporary object, instead of on a . That would not be useful.
COMMENTS
I am overloading assignment operator like this: SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs) { itsRadius = rhs.getRadius(); return *this; } When we are working on the current object like "itsRadius = rhs.getRadius()", the current object's radius will be changed, then, what is the need for returning "*this" ?
All built-in assignment operators return * this, and most user-defined overloads also return * this so that the user-defined operators can be used in the same manner as the built-ins. However, in a user-defined operator overload, any type can be used as return type (including void). T2 can be any type including T.
21.12 — Overloading the assignment operator. Alex July 22, 2024. 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 .
The assignment operator,"=", is the operator used for Assignment. It copies the right value into the left value. Assignment Operators are predefined to operate only on built-in Data types. Assignment operator overloading is binary operator overloading. Overloading assignment operator in C++ copies all values of one object to another object.
Although the canonical implementations of the prefix increment and decrement operators return by reference, as with any operator overload, the return type is user-defined; for example the overloads of these operators for std::atomic return by value. [] Binary arithmetic operatorBinary operators are typically implemented as non-members to maintain symmetry (for example, when adding a complex ...
When overloading the assignment operator in C++, it's important that it returns a reference to the object being assigned. There are several key reasons for this: 1. Chaining of Assignment Operations. In C++, assignment operations can be chained together. For example: A a, b, c; a = b = c; To support this chaining, the assignment operator must ...
Canonical implementations. Other than the restrictions above, the language puts no other constraints on what the overloaded operators do, or on the return type (it does not participate in overload resolution), but in general, overloaded operators are expected to behave as similar as possible to the built-in operators: operator + is expected to add, rather than multiply its arguments, 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 ...
Overloaded operators. When an operator appears in an expression, and at least one of its operands has a class type or an enumeration type, then overload resolution is used to determine the user-defined function to be called among all the functions whose signatures match the following: Expression. As member function.
C++ Operator Overloading. C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. Operator overloading is a compile-time polymorphism. For example, we can overload an operator '+' in a class like String so that we can concatenate two strings by just using +.
Overloading assignments (C++ only) You overload the assignment operator, operator=, with a nonstatic member function that has only one parameter. You cannot declare an overloaded assignment operator that is a nonmember function. The following example shows how you can overload the assignment operator for a particular class: struct X {. int data;
In general, an operator whose result is a new value (such as +, -, etc) must return the new value by value, and an operator whose result is an existing value, but modified (such as <<, >>, +=, -=, etc), should return a reference to the modified value. For example, cout is a std::ostream, and inserting data into the stream is a modifying ...
The bitwise shift operators << and >>, although still used in hardware interfacing for the bit-manipulation functions they inherit from C, have become more prevalent as overloaded stream input and output operators in most applications.. The stream operators, among the most commonly overloaded operators, are binary infix operators for which the syntax does not specify any restriction on whether ...
Overloaded operators. When an operator appears in an expression, and at least one of its operands has a class type or an enumeration type, then overload resolution is used to determine the user-defined function to be called among all the functions whose signatures match the following: Expression. As member function.
Always return a reference to the newly altered left hand side, return *this. This is to allow operator chaining, e.g. a = b = c;. Always check for self assignment (this == &rhs). This is especially important when your class does its own memory allocation. MyClass& MyClass::operator=(const MyClass &rhs) {.
Explanation: Here, d1 calls the operator function of its class object and takes d2 as a parameter, by which the operator function returns the object and the result will reflect in the d3 object. It is generally preferred to overload binary operator as global function. It is because in global function, both the object or the value that can be converted to the object can be used as either left ...
There is already a special instance of overloading = in place that the designers deemed ok: property setters. Let X be a property of foo. In foo.X = 3, the = symbol is replaced by the compiler by a call to foo.set_X(3). You can already define a public static T op_Assign(ref T assigned, T assignee) method. All that is left is for the compiler to ...
2. It returns a reference so you can perform further actions on the object after assigning to it: void doSomething(); A& operator=(const A&); If the assignment operator returned by value then you would call doSomething() on the unnamed temporary object, instead of on a.