21.12 — Overloading the assignment operator

operator overloading

(C++20)
(C++20)
(C++11)
(C++11)
(C++11)
(C++17)
General topics
(C++11)
-
-expression
- block
(C++11)
(C++11)
(C++11)
/
(C++11)
(C++11)
Expressions
expression
pointer
specifier
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
General
(lvalue, rvalue, xvalue)
(sequence points)
(C++11)
Literals
including
(C++11)
(C++11)
Operators
: , , , , , , , , , ,
: , , ,
: , , , , , , , , , , , ,
: , ,
: , , , , , , (C++20)
: , , , , , ,
: , ,
(C++20)
(C++17)
(C++11)
(C++11)
Conversions
,

Customizes the C++ operators for operands of user-defined types.

Overloaded operators are functions with special function names:

op (1)
type (2)

(3)

(4)
suffix-identifier (5) (since C++11)
op - any of the following 38 (until C++20)40 (since C++20) operators:+ - * / % ^ & | ~ ! = < > += -= *= /= %= ^= &= |= << >> >>= <<= == != <= >= <=> (since C++20) && || ++ -- , ->* -> ( ) [ ] co_await (since C++20)

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 As non-member function Example
@a (a).operator@ ( ) operator@ (a) ! calls .operator!()
a@b (a).operator@ (b) operator@ (a, b) << 42 calls .operator<<(42)
a=b (a).operator= (b) cannot be non-member s; s = "abc"; calls s.operator=("abc")
a(b...) (a).operator()(b...) cannot be non-member r; auto n = r(); calls r.operator()()
a[b] (a).operator[](b) cannot be non-member <int, int> m; m[1] = 2; calls m.operator[](1)
a-> (a).operator-> ( ) cannot be non-member auto p = <S>(); p->bar() calls p.operator->()
a@ (a).operator@ (0) operator@ (a, 0) <int>::iterator i = v.begin(); i++ calls i.operator++(0)

in this table, is a placeholder representing all matching operators: all prefix operators in @a, all postfix operators other than -> in a@, all infix operators other than = in a@b

Note: for overloading user-defined conversion functions , user-defined literals , allocation and deallocation see their respective articles.

Overloaded operators (but not the built-in operators) can be called using function notation:

Restrictions

  • The operators :: (scope resolution), . (member access), .* (member access through pointer to member), and ?: (ternary conditional) cannot be overloaded.
  • New operators such as ** , <> , or &| cannot be created.
  • The overloads of operators && and || lose short-circuit evaluation.
  • The overload of operator -> must either return a raw pointer, or return an object (by reference or by value) for which operator -> is in turn overloaded.
  • It is not possible to change the precedence, grouping, or number of operands of operators.
, , and (comma) lose their special when overloaded and behave like regular function calls even when they are used without function-call notation. (until C++17)

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 = is expected to assign, etc. The related operators are expected to behave similarly ( operator + and operator + = do the same addition-like operation). The return types are limited by the expressions in which the operator is expected to be used: for example, assignment operators return by reference to make it possible to write a = b = c = d , because the built-in operators allow that.

Commonly overloaded operators have the following typical, canonical forms: [1]

Assignment operator

The assignment operator ( operator = ) has special properties: see copy assignment and move assignment for details.

The canonical copy-assignment operator is expected to perform no action on self-assignment , and to return the lhs by reference:

The canonical move assignment is expected to leave the moved-from object in valid state (that is, a state with class invariants intact), and either do nothing or at least leave the object in a valid state on self-assignment, and return the lhs by reference to non-const, and be noexcept:

In those situations where copy assignment cannot benefit from resource reuse (it does not manage a heap-allocated array and does not have a (possibly transitive) member that does, such as a member std::vector or std::string ), there is a popular convenient shorthand: the copy-and-swap assignment operator, which takes its parameter by value (thus working as both copy- and move-assignment depending on the value category of the argument), swaps with the parameter, and lets the destructor clean it up.

This form automatically provides strong exception guarantee , but prohibits resource reuse.

Stream extraction and insertion

The overloads of operator>> and operator<< that take a std:: istream & or std:: ostream & as the left hand argument are known as insertion and extraction operators. Since they take the user-defined type as the right argument ( b in a@b ), they must be implemented as non-members.

These operators are sometimes implemented as friend functions .

Function call operator

When a user-defined class overloads the function call operator, operator ( ) , it becomes a FunctionObject type. Many standard algorithms, from std:: sort to std:: accumulate accept objects of such types to customize behavior. There are no particularly notable canonical forms of operator ( ) , but to illustrate the usage

Increment and decrement

When the postfix increment and decrement appear in an expression, the corresponding user-defined function ( operator ++ or operator -- ) is called with an integer argument 0 . Typically, it is implemented as T operator ++ ( int ) , where the argument is ignored. The postfix increment and decrement operator is usually implemented in terms of the prefix version:

Although canonical form of pre-increment/pre-decrement returns a 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 operators

Binary operators are typically implemented as non-members to maintain symmetry (for example, when adding a complex number and an integer, if operator+ is a member function of the complex type, then only complex + integer would compile, and not integer + complex ). Since for every binary arithmetic operator there exists a corresponding compound assignment operator, canonical forms of binary operators are implemented in terms of their compound assignments:

Relational operators

Standard algorithms such as std:: sort and containers such as std:: set expect operator < to be defined, by default, for the user-provided types, and expect it to implement strict weak ordering (thus satisfying the Compare requirements). An idiomatic way to implement strict weak ordering for a structure is to use lexicographical comparison provided by std::tie :

Typically, once operator < is provided, the other relational operators are implemented in terms of operator < .

Likewise, the inequality operator is typically implemented in terms of operator == :

When three-way comparison (such as std::memcmp or std::string::compare ) is provided, all six relational operators may be expressed through that:

All six relational operators are automatically generated by the compiler if the three-way comparison operator operator<=> is defined, and that operator, in turn, is generated by the compiler if it is defined as defaulted:

Record { name; unsigned int floor; double weight; auto operator<=>(const Record&) = default; }; // records can now be compared with ==, !=, <, <=, >, and >=

See for details.

(since C++20)

Array subscript operator

User-defined classes that provide array-like access that allows both reading and writing typically define two overloads for operator [ ] : const and non-const variants:

If the value type is known to be a built-in type, the const variant should return by value.

Where direct access to the elements of the container is not wanted or not possible or distinguishing between lvalue c [ i ] = v ; and rvalue v = c [ i ] ; usage, operator[] may return a proxy. see for example std::bitset::operator[] .

To provide multidimensional array access semantics, e.g. to implement a 3D array access a [ i ] [ j ] [ k ] = x ; , operator[] has to return a reference to a 2D plane, which has to have its own operator[] which returns a reference to a 1D row, which has to have operator[] which returns a reference to the element. To avoid this complexity, some libraries opt for overloading operator ( ) instead, so that 3D access expressions have the Fortran-like syntax a ( i, j, k ) = x ;

Bitwise arithmetic operators

User-defined classes and enumerations that implement the requirements of BitmaskType are required to overload the bitwise arithmetic operators operator & , operator | , operator ^ , operator~ , operator & = , operator | = , and operator ^ = , and may optionally overload the shift operators operator << operator >> , operator >>= , and operator <<= . The canonical implementations usually follow the pattern for binary arithmetic operators described above.

Boolean negation operator

The operator operator ! is commonly overloaded by the user-defined classes that are intended to be used in boolean contexts. Such classes also provide a user-defined conversion function explicit operator bool ( ) (see std::basic_ios for the standard library example), and the expected behavior of operator ! is to return the value opposite of operator bool .

Rarely overloaded operators

The following operators are rarely overloaded:

  • The address-of operator, operator & . If the unary & is applied to an lvalue of incomplete type and the complete type declares an overloaded operator & , the behavior is undefined (until C++11) it is unspecified whether the operator has the built-in meaning or the operator function is called (since C++11) . Because this operator may be overloaded, generic libraries use std::addressof to obtain addresses of objects of user-defined types. The best known example of a canonical overloaded operator& is the Microsoft class CComPtr . An example of its use in EDSL can be found in boost.spirit .
  • The boolean logic operators, operator && and operator || . Unlike the built-in versions, the overloads cannot implement short-circuit evaluation. Also unlike the built-in versions, they do not sequence their left operand before the right one. (until C++17) In the standard library, these operators are only overloaded for std::valarray .
  • The comma operator, operator, . Unlike the built-in version, the overloads do not sequence their left operand before the right one. (until C++17) Because this operator may be overloaded, generic libraries use expressions such as a, void ( ) ,b instead of a,b to sequence execution of expressions of user-defined types. The boost library uses operator, in boost.assign , boost.spirit , and other libraries. The database access library SOCI also overloads operator, .
  • The member access through pointer to member operator - > * . There are no specific downsides to overloading this operator, but it is rarely used in practice. It was suggested that it could be part of smart pointer interface , and in fact is used in that capacity by actors in boost.phoenix . It is more common in EDSLs such as cpp.react .

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 taking address of incomplete type that overloads address-of was undefined behavior the behavior is only unspecified
  • Operator precedence
  • Alternative operator syntax
Common operators

a = b
a += b
a -= b
a *= b
a /= b
a %= b
a &= b
a |= b
a ^= b
a <<= b
a >>= b

++a
--a
a++
a--

+a
-a
a + b
a - b
a * b
a / b
a % b
~a
a & b
a | b
a ^ b
a << b
a >> b

!a
a && b
a || b

a == b
a != b
a < b
a > b
a <= b
a >= b
a <=> b

a[b]
*a
&a
a->b
a.b
a->*b
a.*b

a(...)
a, b
? :

Special operators

converts one type to another related type
converts within inheritance hierarchies
adds or removes qualifiers
converts type to unrelated type
converts one type to another by a mix of , , and
creates objects with dynamic storage duration
destructs objects previously created by the new expression and releases obtained memory area
queries the size of a type
queries the size of a (since C++11)
queries the type information of a type
checks if an expression can throw an exception (since C++11)
queries alignment requirements of a type (since C++11)

  • ↑ Operator Overloading on StackOverflow C++ FAQ

cppreference.com

Copy assignment operator.

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


/
(C++11)
(C++11)
(C++11)
(C++20)
(C++20)
(C++11)

expression
pointer
specifier

specifier (C++11)
specifier (C++11)
(C++11)

(C++11)
(C++11)
(C++11)
General
/ types
types
Members
pointer
-declarations
(C++11)
specifier
specifier
Special member functions
(C++11)
(C++11)
Inheritance
specifier (C++11)
specifier (C++11)

A copy assignment operator is a non-template non-static member function with the name operator = that can be called with an argument of the same class type and copies the content of the argument without mutating the argument.

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

[ edit ] Syntax

For the formal copy assignment operator syntax, see function declaration . The syntax list below only demonstrates a subset of all valid copy assignment operator syntaxes.

return-type parameter-list  (1)
return-type parameter-list  function-body (2)
return-type parameter-list-no-default  (3) (since C++11)
return-type parameter-list  (4) (since C++11)
return-type class-name  parameter-list  function-body (5)
return-type class-name  parameter-list-no-default  (6) (since C++11)
class-name - the class whose copy assignment operator is being declared, the class type is given as in the descriptions below
parameter-list - a of only one parameter, which is of type , , const T&, volatile T& or const volatile T&
parameter-list-no-default - a of only one parameter, which is of type , , const T&, volatile T& or const volatile T& and does not have a default argument
function-body - the of the copy assignment operator
return-type - any type, but is favored in order to allow chaining asssignments

[ edit ] Explanation

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

[ edit ] Implicitly-declared copy assignment operator

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

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

Otherwise the implicitly-declared copy assignment operator is declared as T & T :: operator = ( T & ) .

Due to these rules, the implicitly-declared copy assignment operator cannot bind to a volatile lvalue argument.

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

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

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

[ edit ] Implicitly-defined copy assignment operator

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

The implicitly-defined copy assignment operator for a class is if

is a , and that is of class type (or array thereof), the assignment operator selected to copy that member is a constexpr function.
(since C++14)
(until C++23)

The implicitly-defined copy assignment operator for a class is .

(since C++23)

The generation of the implicitly-defined copy assignment operator is deprecated if has a user-declared destructor or user-declared copy constructor.

(since C++11)

[ edit ] Deleted copy assignment operator

An implicitly-declared or explicitly-defaulted (since C++11) copy assignment operator for class T is undefined (until C++11) defined as deleted (since C++11) if any of the following conditions is satisfied:

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

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

(since C++11)

[ edit ] Trivial copy assignment operator

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

  • it is not user-provided (meaning, it is implicitly-defined or defaulted);
  • T has no virtual member functions;
  • T has no virtual base classes;
  • the copy assignment operator selected for every direct base of T is trivial;
  • the copy assignment operator selected for every non-static class type (or array of class type) member of T is trivial.

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

[ edit ] Eligible copy assignment operator

A copy assignment operator is eligible if it is either user-declared or both implicitly-declared and definable.

(until C++11)

A copy assignment operator is eligible if it is not deleted.

(since C++11)
(until C++20)

A copy assignment operator is eligible if all following conditions are satisfied:

(if any) are satisfied. than any other copy assignment operator.
(since C++20)

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

[ edit ] Notes

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

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

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

[ edit ] Example

[ edit ] defect reports.

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

DR Applied to Behavior as published Correct behavior
C++98 the conditions where implicitly-declared copy assignment operators
are undefined did not consider multi-dimensional array types
consider these types
C++11 a volatile subobject made defaulted copy
assignment operators non-trivial ( )
triviality not affected
C++11 operator=(X&) = default was non-trivial made trivial
C++11 a defaulted copy assignment operator for class was not defined as deleted
if is abstract and has non-copy-assignable direct virtual base classes
the operator is defined
as deleted in this case
C++20 a copy assignment operator was not eligible if there
is another copy assignment operator which is more
constrained but does not satisfy its associated constraints
it can be eligible
in this case

[ edit ] See also

  • converting constructor
  • copy constructor
  • copy elision
  • default constructor
  • aggregate initialization
  • constant initialization
  • copy initialization
  • default initialization
  • direct initialization
  • initializer list
  • list initialization
  • reference initialization
  • value initialization
  • zero initialization
  • move assignment
  • move constructor
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 2 February 2024, at 16:13.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

  • C++ Classes and Objects
  • C++ Polymorphism
  • C++ Inheritance
  • C++ Abstraction
  • C++ Encapsulation
  • C++ OOPs Interview Questions
  • C++ OOPs MCQ
  • C++ Interview Questions
  • C++ Function Overloading
  • C++ Programs
  • C++ Preprocessor
  • C++ Templates

Different Ways of Operator Overloading in C++

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:

  • Operator Overloading using Friend Function
  • Operator Overloading using Member Function
  • Operator Overloading using Global Non-Friend Function

1. Operator Overloading Using Friend Function

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.

E xample of Operator Overloading Using Friend Function

Operators that cannot be overloaded when declaring that function as friend function are = () [] -> .

2. Overloading Operator Using Member Function

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)

Example of Overloading Operator Using 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.

3. Overloading Operator Using Global Function

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.

Example of Overloading Operator Using Global Function

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

Please Login to comment...

Similar reads.

  • cpp-overloading

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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

Return value of assignment operator overloading c++ [duplicate]

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?

  • operator-overloading

alseether's user avatar

  • Note: *this is lvalue –  Chen Li Commented Nov 24, 2017 at 15:04
  • As you ask for mis-understanding: There are multiple meanings of & which are precisely distinguished by the compiler but no everytimes by the human readers/writers: (in declarators) & after a type modifies the type to a reference to this type (similar like * for pointers), (in expressions) & before an expression as address operator, not to forget the & between expressions which denotes "bitwise and". –  Scheff's Cat Commented Nov 24, 2017 at 15:10
  • "Note that 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 chained assignment (as pointed in answer below). - msdn.microsoft.com/en-us/library/7ac5szsk.aspx –  SChepurin Commented Nov 24, 2017 at 15:33
  • The linked duplicate has a large large amount of information in it, happy reading I suppose –  Passer By Commented Nov 24, 2017 at 18:11

3 Answers 3

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 .

Eljay's user avatar

  • i mean return value of operator=(Fraction const&) is Fraction& which is reference but it returns *this (represented as object) –  sasorihuriko Commented Nov 24, 2017 at 15:16
  • *this is required when member function with ref-qualifier –  Chen Li Commented Nov 24, 2017 at 15:18
  • A reference is an alias for the object. So in this situation a Fraction& is an alias for *this object. (How the magic of a reference is done under the covers is an implementation detail. My platform does it as a pointer, but the pointer-ness is not manipulable in C++.) –  Eljay Commented Nov 24, 2017 at 15:23
  • 1 this is a pointer because C++ had this before it had references. stroustrup.com/bs_faq2.html#this –  Christian Hackl Commented Nov 24, 2017 at 19:10
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.

Useless's user avatar

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.

Jonathan Wakely's user avatar

Not the answer you're looking for? Browse other questions tagged c++ operator-overloading or ask your own question .

  • The Overflow Blog
  • Ryan Dahl explains why Deno had to evolve with version 2.0
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • bash script quoting frustration
  • Explaining Arithmetic Progression
  • Do linguists have a noun for referring to pieces of commendatory language, as a sort of antonym of 'pejoratives'?
  • How can I put node of a forest correctly?
  • Multiple unds in a sentence
  • google-chrome-stable : Depends: libgcc-s1 (>= 4.2) but it is not installable
  • Would it take less thrust overall to put an object into higher orbit?
  • What did Scott Lang mean by "living as a tenant of the state"?
  • Did anyone ever ask Neil Armstrong whether he said "for man" or "for a man?"
  • If you get pulled for secondary inspection at immigration, missing flight, will the airline rebook you?
  • Should I be worried about this giant crack?
  • Population impacts on temperature
  • 1969s-1970s novel, mankind needs to emigrate to escape Sun going nova, women are higher status than men, men have artificial snake familiars
  • Should it be "until" or "before" in "Go home until it's too late"?
  • Fitting 10 pieces of pizza in a box
  • Requring a Social Membership to a golf course
  • How many people could we get off of the planet in a month?
  • What type of directions are fruitful to innovate in quantum hardware?
  • A consequence of Firoozbakht's conjecture?
  • What might cause these striations in this solder joint?
  • Seven different digits are placed in a row. The products of the first 3, middle 3 and last 3 are all equal. What is the middle digit?
  • Consistency strength of HoTT
  • How to make outhouses less icky?
  • Series of discrete groups with a Lie group limit

c assignment operator overload return type

COMMENTS

  1. return type of overloading assignment operator in c++

    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" ?

  2. Assignment operators

    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.

  3. 21.12

    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 .

  4. C++ Assignment Operator Overloading

    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.

  5. operator overloading

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

  6. Why Assignment Operator Overloading Must Return Reference?

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

  7. operator overloading

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

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

  9. operator overloading

    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.

  10. Operator Overloading in C++

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

  11. Overloading assignments (C++ only)

    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;

  12. return value of operator overloading in C++

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

  13. The Three Basic Rules of Operator Overloading in C++

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

  14. operator overloading

    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.

  15. c++

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

  16. Different Ways of Operator Overloading in C++

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

  17. Overloading assignment operator in C#

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

  18. Return value of assignment operator overloading c++

    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.