21.12 — Overloading the assignment operator

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

Why Assignment Operator Overloading Must Return Reference?

Operator overloading in C++ allows us to define custom behaviors for operators when applied to user-defined types. One of the most commonly overloaded operators is the assignment operator (=), which is used to assign the value of one object to another. However, when overloading the assignment operator, it’s important to ensure that it returns a reference to the object being assigned. But why is this necessary?

In this article, we will learn why the assignment operator must return a reference in C++ when overloading, and what could go wrong if it doesn’t.

Why Must the Assignment Operator Return a 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:

To support this chaining, the assignment operator must return a reference to the object being assigned. This allows the operation b = c to return b, enabling a = b to work as expected.

2. Consistency with Built-in Types

For built-in types, the assignment operator in C++ returns a reference to the left-hand operand. To maintain consistency and intuitive behavior for user-defined types, overloaded assignment operators should also return a reference.

3. Avoiding Unnecessary Object Copies

If the assignment operator returned an object by value instead of by reference, it would result in the creation of a temporary object, which is immediately discarded. This unnecessary copying is inefficient and could lead to performance issues, especially for large objects or objects managing dynamic resources.

C++ Program to Demonstrate Properly Overloading the Assignment Operator

The below example demonstartes how to properly overload the assignment operator in C++.

What Happens if Assignment Operator Does Not Return a Reference?

If we overload the assignment operator and return by value instead of by reference, several issues could arise:

  • Chained assignments like a = b = c; would not work correctly.
  • Returning by value would create temporary objects, leading to inefficiencies.
  • The overloaded assignment operator would behave differently from the built-in assignment operator, which could confuse others of our class.

In C++, when overloading the assignment operator, we must return a reference to the current object ( *this ) as it allows for assignment chaining, maintains consistency with built-in types, and avoids unnecessary object copying. By following these best practice, we can ensure that our overloaded operators are efficient, intuitive, and behave as expected, making our C++ programs more robust and maintainable.

author

Please Login to comment...

Similar reads.

  • C++-Operator Overloading

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

This browser is no longer supported.

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

Operator overloading

  • 8 contributors

The operator keyword declares a function specifying what operator-symbol means when applied to instances of a class. This gives the operator more than one meaning, or "overloads" it. The compiler distinguishes between the different meanings of an operator by examining the types of its operands.

type operator operator-symbol ( parameter-list )

You can redefine the function of most built-in operators globally or on a class-by-class basis. Overloaded operators are implemented as functions.

The name of an overloaded operator is operator x , where x is the operator as it appears in the following table. For example, to overload the addition operator, you define a function called operator+ . Similarly, to overload the addition/assignment operator, += , define a function called operator+= .

Redefinable Operators

Operator Name Type
Comma Binary
Logical NOT Unary
Inequality Binary
Modulus Binary
Modulus assignment Binary
Bitwise AND Binary
Address-of Unary
Logical AND Binary
Bitwise AND assignment Binary
Function call
Cast Operator Unary
Multiplication Binary
Pointer dereference Unary
Multiplication assignment Binary
Addition Binary
Unary Plus Unary
Increment Unary
Addition assignment Binary
Subtraction Binary
Unary negation Unary
Decrement Unary
Subtraction assignment Binary
Member selection Binary
Pointer-to-member selection Binary
Division Binary
Division assignment Binary
Less than Binary
Left shift Binary
Left shift assignment Binary
Less than or equal to Binary
Assignment Binary
Equality Binary
Greater than Binary
Greater than or equal to Binary
Right shift Binary
Right shift assignment Binary
Array subscript
Exclusive OR Binary
Exclusive OR assignment Binary
Bitwise inclusive OR Binary
Bitwise inclusive OR assignment Binary
Logical OR Binary
One's complement Unary
Delete
New
conversion operators conversion operators Unary

1 Two versions of the unary increment and decrement operators exist: preincrement and postincrement.

See General Rules for Operator Overloading for more information. The constraints on the various categories of overloaded operators are described in the following topics:

Unary Operators

Binary Operators

Function Call

Subscripting

Class-Member Access

Increment and Decrement .

User-Defined Type Conversions

The operators shown in the following table cannot be overloaded. The table includes the preprocessor symbols # and ## .

Nonredefinable Operators

Operator Name
Member selection
Pointer-to-member selection
Scope resolution
Conditional
Preprocessor convert to string
Preprocessor concatenate

Although overloaded operators are usually called implicitly by the compiler when they are encountered in code, they can be invoked explicitly the same way as any member or nonmember function is called:

The following example overloads the + operator to add two complex numbers and returns the result.

In this section

General Rules for Operator Overloading

Overloading Unary Operators

Member Access

C++ Built-in Operators, Precedence and Associativity Keywords

Was this page helpful?

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

Code With C

The Way to Programming

  • C Tutorials
  • Java Tutorials
  • Python Tutorials
  • PHP Tutorials
  • Java Projects

Mastering Operator Overloading: A Comprehensive Guide

CodeLikeAGirl

Mastering Operator Overloading: A Comprehensive Guide 🚀

Have you ever felt like you’re in a magical land where operators like +, -, or even == behave exactly the way you want them to? Well, my fellow tech enthusiasts, welcome to the whimsical world of operator overloading in C++! 🎩✨

Basics of Operator Overloading 🎯

What is operator overloading 🤔.

Let’s start from the very beginning – what on earth is this “operator overloading” that we keep hearing about? 🤷‍♀️ It’s like giving these operators a new superpower! 🦸‍♀️ Operator overloading allows you to redefine the way operators work with user-defined data types. In simple terms, you get to teach C++ some new tricks! 🎩🐇

Why Use Operator Overloading? 🤓

Now, why bother with all this operator overloading business, you ask? 💭 Well, imagine making your code more elegant and readable by using + to concatenate strings or comparing objects with ==. It’s like adding a sprinkle of magic to your code, making it more intuitive and user-friendly! ✨🪄

Implementing Operator Overloading in C++ 🛠️

Syntax for operator overloading 📝.

To dip your toes into the enchanting waters of operator overloading, you need to know the syntax! It involves creating a function with a special name, ensuring that the compiler knows how to handle those magical new tricks you’re teaching it. Ah, it’s like writing a secret incantation that only your program can understand ! 🔮✍️

Overloading Unary and Binary Operators 🔢

Unary, binary – wait, what now? Don’t worry, it’s just a fancy way of saying you can overload operators like + or – for different uses! Whether you’re working with one operand or two, operator overloading lets you redefine their behavior based on your needs. It’s like juggling different tasks with the same tool! 🤹‍♂️🔧

Best Practices for Operator Overloading 🌟

Avoiding ambiguity in operator overloading ❌.

Ah, the dreaded ambiguity – the dark side of operator overloading! To steer clear of confusion, make sure your overloaded operators are crystal clear in their intentions. You wouldn’t want your program scratching its virtual head trying to decipher your mystical code, would you? 🤯🧙‍♂️

Overloading Commonly Used Operators 💡

When in doubt, remember – stick to the classics! Overloading familiar operators like +, -, or == can make your code more intuitive and user-friendly. It’s like speaking the language of C++ fluently, with a hint of your own unique dialect! 🗣️🌐

Advanced Techniques in Operator Overloading 💡

Overloading assignment operator (=) 📚.

Ah, the humble assignment operator – the unsung hero of C++ . By overloading this operator, you can customize how your objects are assigned values. It’s like giving your programs a personalized touch, ensuring they get all dressed up in the perfect outfit! 👗👔

Overloading Increment (++) and Decrement (–) Operators 🔝

Feeling adventurous? How about tinkering with the ++ and — operators? By overloading these bad boys, you can define how your objects increment or decrement. It’s like a virtual dance, where your objects move to the beat of your custom-made drum! 🥁🎶

Common Pitfalls to Avoid in Operator Overloading 🕳️

Handling memory management in operator overloading 🧠.

Ah, memory management – the bane of many programmers! When overloading operators, be extra cautious with memory allocation and deallocation. One wrong move, and your program could be lost in a memory maze, desperately searching for a way out! 🧟‍♂️🤖

Ensuring Consistency in Overloaded Operators 🤝

Consistency is key in the magical realm of operator overloading! Make sure that similar operations behave uniformly across your code. It’s like maintaining harmony in a chaotic symphony, ensuring that every note plays in perfect unison! 🎻🎶

In Closing 🌈

Overall, mastering the art of operator overloading in C++ is like wielding a powerful magic wand in the world of programming. By understanding the basics, embracing best practices, exploring advanced techniques, and steering clear of common pitfalls, you can elevate your code to new heights of elegance and efficiency! 🚀🌟

Thank you for joining me on this enchanting journey through the realms of operator overloading. Remember, in the magical land of C++, the possibilities are as endless as the stars in the night sky! 🌌✨

Now go forth, brave coders, and may your operator overloading adventures be filled with joy, laughter, and of course, lots of magical moments! 🎉🔮

P.S. Keep coding, keep creating, and always remember – the code is strong with this one! 💪👩‍💻

Program Code – Mastering Operator Overloading: A Comprehensive Guide

### code output:, ### code explanation:.

The provided code example illustrates the essence of operator overloading in C++ .

Architecture:

At its heart, it comprises a class named ComplexNumber . This class encapsulates two private attributes: real and imaginary , representing the real and imaginary parts of a complex number, respectively.

Logic and Implementation Details:

  • Constructor Initialization: The constructor ComplexNumber initializes these two attributes. If values are not provided during object creation, it defaults to 0.0.
  • Display Method: There’s a handy display method to output the complex number in a human-readable format, i.e., ‘Complex Number: X + Yi.
  • Addition (‘+’ operator): It overloads the ‘+’ operator using the member function operator + to add two complex numbers. It takes an object of ComplexNumber as a parameter ( const ComplexNumber& obj ) representing the second operand. Inside, it creates a temporary object temp , calculates the summation of real and imaginary parts separately, and returns temp .
  • Subtraction (‘-’ operator): Very similar to addition, it also overloads the ‘-‘ operator using the member function operator - for subtracting two complex numbers. It follows a procedure analogous to addition, calculating the difference of both real and imaginary parts separately.
  • Main Function: In main() , two ComplexNumber objects c1 and c2 are instantiated with specific values. Then, leveraging our overloaded operators, we add ( c1 + c2 ) and subtract ( c1 - c2 ) these complex numbers and display the results using the display() method.

How it Achieves its Objectives:

The demonstration efficiently achieves its educational aim by intricately showing how operators can be overloaded to perform operations according to the nature of user-defined data types , in this case, complex numbers. Rather than just being confined to the built-in data types, operator overloading extends the expressiveness of C++ to accommodate complex operations in a manner that’s both intuitive and elegant for the programmer.

Frequently Asked Questions

What is operator overloading in c++.

Operator overloading in C++ allows us to redefine the way operators work for user-defined data types . This means we can use operators like +, -, *, /, etc., with custom objects just like built-in data types.

How does operator overloading work in C++?

In C++, operator overloading is achieved by defining a function to overload an operator. When an operator is used with objects of a class, the corresponding function is called to perform the operation.

Can we overload all operators in C++?

No, not all operators can be overloaded in C++. Some operators, like sizeof , :: , .* , etc., cannot be overloaded. It’s essential to understand which operators can and cannot be overloaded in C++.

What are the benefits of operator overloading?

Operator overloading can make our code more readable and intuitive by allowing us to use familiar operators with custom types. It can also lead to code that closely resembles mathematical expressions, making the code easier to understand .

What are some common mistakes to avoid when overloading operators in C++?

One common mistake when overloading operators in C++ is not handling edge cases or boundary conditions properly. It’s crucial to test the overloaded operators thoroughly to ensure they work as expected in all scenarios.

Are there any performance implications of operator overloading in C++?

Yes, there can be performance implications when using operator overloading in C++. Overloading operators can introduce overhead compared to regular function calls. It’s essential to consider the performance impact when overloading operators in performance-critical code.

How can I decide when to use operator overloading in my C++ code?

The decision to use operator overloading in C++ should be based on whether it enhances the readability and maintainability of the code. If overloading an operator makes the code more natural to read and less error-prone, it can be a good choice.

Where can I find more resources to learn about mastering operator overloading in C++?

There are plenty of online resources, tutorials, and books available to learn more about mastering operator overloading in C++. Websites like GeeksforGeeks, tutorials from cppreference.com, and books like “Effective C++” by Scott Meyers can be valuable sources of information.

You Might Also Like

The significance of ‘c’ in c programming language, c programming languages: understanding the basics and beyond, exploring the c programming language: from basics to advanced concepts, object-oriented programming: the pillar of modern software development, object-oriented coding: best practices and techniques.

Avatar photo

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Latest Posts

62 Creating a Google Sheet to Track Google Drive Files: Step-by-Step Guide

Creating a Google Sheet to Track Google Drive Files: Step-by-Step Guide

codewithc 61 Cutting-Edge Artificial Intelligence Project Unveiled in Machine Learning World

Cutting-Edge Artificial Intelligence Project Unveiled in Machine Learning World

75 Enhancing Exams with Image Processing: E-Assessment Project

Enhancing Exams with Image Processing: E-Assessment Project

73 Cutting-Edge Blockchain Projects for Cryptocurrency Enthusiasts - Project

Cutting-Edge Blockchain Projects for Cryptocurrency Enthusiasts – Project

67 Artificial Intelligence Marvel: Cutting-Edge Machine Learning Project

Artificial Intelligence Marvel: Cutting-Edge Machine Learning Project

Privacy overview.

en_US

Sign in to your account

Username or Email Address

Remember Me

cppreference.com

  • View source

Operator overloading in C++

.

Operator overloading in C++ allows us to write natural expressions like d = a + b / c ; with our own classes. The above expression could be equal to d = a. add ( b. divide ( c ) ) ; which results in hard to read code.

Operator overloading by Example

This example will add basic arithmetic operations: addition, subtraction, multiplication and division to Complex number class. These operations will use operators: +, -, *, / and their assigning counterparts +=, -=, *=, /=. Only addition will be implemented.

We will also add input/output operators to read/write from/to standard input/output. Both operators are free functions (and not class methods). Input operator operator << takes two arguments: a reference to an input stream and a constant reference to object to write, and returns a reference to the input stream. Output operator operator >> takes two arguments: a reference to an output stream and a reference to object to write, it returns as well a reference to the output stream.

Functors in C++

Functors are classes with overloaded parenthesis operator operator ( ) which can have any number of arguments.

This section is incomplete
  • Todo without reason
  • Community portal
  • Current events
  • Recent changes
  • Random page
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • This page was last modified on 9 April 2014, at 08:25.
  • This page has been accessed 30,627 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

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

Assignment Operator Overload in c++

I realize that there are examples after examples of overloading the assignment operator on the web, but I have spent the last few hours trying to implement them in my program and figure out how they work and I just can't seem to do it and any help would be greatly appreciated.

I am trying to implement an overloaded assignment operator function.

I have 3 files working, the Complex.h header file, a Complex.cpp definition file, and a .cpp file I'm using as a driver to test my Complex class.

In the Complex.h header file my prototype for the assignment operator:

And so far what I have for the definition of the overloaded operator in my .cpp file is:

And the way I'm calling my assignment operator in my functions is:

So specifically, my problem is that when I call the overloaded assignment operator with x = y -z, it doesn't assign the passed in value to x when I return the passed in value and I'm unable to figure out why from numerous examples and explanations on the web, any help would be greatly appreciated and I thank you for any help ahead of time.

  • operator-overloading
  • assignment-operator

Prog's user avatar

  • 1 Why don't you read some of those examples after examples and model your assignment operator on one that actually works? –  juanchopanza Commented Mar 28, 2015 at 16:03
  • = shouldn't probably modify its right hand operand. –  Emil Laine Commented Mar 28, 2015 at 16:03
  • @juanchopanza I tried that, and I apologize for this and sincerely appreciate your input, but my brain just doesn't work this way, I did try to read those examples and model after those working examples but it would end in recursion. –  Prog Commented Mar 28, 2015 at 16:08
  • @zenith So you're saying that by returning first I am modifying the right hand operand? –  Prog Commented Mar 28, 2015 at 16:08
  • No, he clearly does not modify the right-hand-operand. –  Puppy Commented Mar 28, 2015 at 16:09

3 Answers 3

I think you need the following operator definition

You have to return reference to the object that is assigned to. Also the parameter should be a constant reference. In this case you may bind the reference to a temporary object or you have to write also a move assignment operator.

In your implementation of the copy assignment operator you do not change the assigned object.:) You simply create a temporary and return reference to this temporary or return reference to first.

Vlad from Moscow's user avatar

  • Whilst strictly accurate, this isn't that helpful as it doesn't really explain to the OP why you've written it that way. –  Puppy Commented Mar 28, 2015 at 16:09
  • If I understand your method correctly I should assign to the real and imaginary private data members to create a new Complex object and then return the created Complex object with the address of the current (this) data member? –  Prog Commented Mar 28, 2015 at 16:15
  • @DastardlyDeedDoer No, assignment should not create a new object (unless as an intermediary implementation detail). It assigns a value to an existing one. –  juanchopanza Commented Mar 28, 2015 at 16:16
  • @juanchopanza You're saying I'm creating a new object by returning first? But isn't it already created because I called the overloaded operator with it? So I'm just returning the passed in value? Or is my understanding of this way off? –  Prog Commented Mar 28, 2015 at 16:20
  • @DastardlyDeedDoer No, I am saying you don't create an new object and you shouldn't. I mean, you in your broken code do, but the code in this answer doesn't. –  juanchopanza Commented Mar 28, 2015 at 16:21

Assignment takes in two objects, the object to be assigned to, and the object with the desired value.

Assignment should:

  • modify an existing object, the object being assigned to

Assignment should not:

  • create a new object
  • modify the object that has the desired value.

So let's say the object type we're dealing with is:

A function that performs assignment might have the signature:

And it would be used:

  • the left hand side object is modifiable, and assignment will modify it, rather than create a new object.
  • the right hand side object, the object with the desired value, is not modifiable.

Additionally, in C++ the built-in assignment operation is an expression rather than a statement; it has a value and can be used as a subexpression:

This sets j equal to k, and then takes the result of that assignment and prints it out. The important thing to note is that the result of the assignment expression is the object that was assigned to . No new object is created. In the above code, the value of j is printed (which is 10, because j was just assigned the value 10 from k ).

Updating our earlier assignment function to follow this convention results in a signature like:

S &assignment(S &left_hand_side, S const &right_hand_side);

An implementation looks like:

Note that this assignment function is not recursive; it does not use itself in the assignment, but it does use assignment of the member types .

The final piece of the puzzle is getting the syntax a = b to work, instead of assignment(a, b) . In order to do this, all you have to do is make assignment () a member function:

Replace the left_hand_side argument with *this :

And rename the function to operator= :

Another important thing to know is that the = sign is used in one place that is not assignment:

This is 'copy initialization'. It does not use operator= . It is not assignment. Try not to confuse the two.

Points to remember:

  • assignment modifies the object being assigned to
  • assignment does not modify the object being assigned from.
  • assignment does not create a new object.
  • assignment is not recursive, except insofar as assignment of a compound object makes use of assignment on all the little member objects it contains.
  • assignment returns the object after modifying its value
  • copy initialization looks sort of like assignment, but has little to do with assignment.

bames53's user avatar

  • I know this was posted awhile back - but its a really thoughtful answer and should be preserved. –  Don Shanil Commented May 7, 2021 at 11:58

An overloaded assignment operator should look like this:

You should also note, that if you overload the assignment operator you should overload the copy constructor for Complex in the same manner:

πάντα ῥεῖ's user avatar

  • This is a double fail. First, you overloaded = but made it do == , and secondly, self-assignment is for out-of-date lecturers and not for real-world use –  Puppy Commented Mar 28, 2015 at 16:06
  • I have the code for the equality operator working just fine in later code, I need to be able to modify the left hand operand (the x) when I return the value from the assignment operator function. –  Prog Commented Mar 28, 2015 at 16:09
  • @DastardlyDeedDoer "I need to be able to modify the left hand operand (the x) when I return the value from the assignment operator function." My example will exactly do this. –  πάντα ῥεῖ Commented Mar 28, 2015 at 16:11
  • @Puppy I totally agree and that is a major reason I'm here asking for help, all of the coding I do doesn't do such round about crap. But this is for a class I'm taking and I will get little credit if I don't get this too work. But mostly my reason for the use of the equality operator is to avoid self-assignment, unless I'm going about that the wrong way too. –  Prog Commented Mar 28, 2015 at 16:12
  • 1 @Puppy There is a very important use case where you simply have to check for self-assignment: Job interviews. ;-) –  Greenflow Commented Mar 28, 2015 at 19:09

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

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

  • The Overflow Blog
  • Scaling systems to manage all the metadata ABOUT the data
  • Navigating cities of code with Norris Numbers
  • 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...

Hot Network Questions

  • Finding the maximum squared distance between a pair of coordinates from a set of coordinates
  • How to cite a book if only its chapters have DOIs?
  • MOSFETs keep shorting way below rated current
  • Caulking Bathtub and Wall Surround to prevent water leak
  • How to Increase a Length in Inches by a Point without Manual Conversion?
  • What is this houseplant with a red fleshy stem and thick waxy leaves?
  • Erase the loops
  • A short story about a demon, in a modernising Japan, living in electric wires and starting fires
  • DIN Rail Logic Gate
  • tmux - How to remove delay after pressing prefix key and Up key
  • Dual UK/CAN national travelling from UK to Canada and back - which passport should I use to book tickets?
  • Cleveref, biblatex and automatic equation numbering
  • If Venus had a sapient civilisation similar to our own prior to global resurfacing, would we know it?
  • Who became an oligarch after the collapse of the USSR
  • How can I obscure branding on the side of a pure white ceramic sink?
  • Why did evolution fail to protect humans against sun?
  • Cumulative Addition of Index Switch Node Values
  • Why is my differential equation for mass-spring-damper model not converging with ode45 in MATLAB?
  • Clean up verbose code for Oracle SQL
  • Stargate "instructional" videos
  • Base change in Chriss-Ginzburg
  • Car LED circuit
  • Do "Whenever X becomes the target of a spell" abilities get triggered by counterspell?
  • Does the First Amendment protect deliberately publicizing the incorrect date for an election?

c overload addition assignment operator

IMAGES

  1. Matrix addition using operator overloading in c

    c overload addition assignment operator

  2. C++ : Overloaded Addition assignment operator in C++ for two /more than

    c overload addition assignment operator

  3. Overloading assignment operator in C++

    c overload addition assignment operator

  4. Assignment Operator Overloading in C++

    c overload addition assignment operator

  5. C++ Overloading Addition Operator and using const

    c overload addition assignment operator

  6. Assignment Operator Overloading In C++

    c overload addition assignment operator

COMMENTS

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

  2. C++ -- How to overload operator+=?

    Class& operator @= (const Class& rhs); That is, the function takes its parameter by const reference (because it doesn't modify it), then returns a mutable reference to the object. The reason you return a non-const reference is because, for historical reasons, you can write code like this: (a += b) += c; This is by no means good style, but it ...

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

  4. Assignment operators

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

  5. operator overloading

    Canonical implementations. Besides 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 ...

  6. Overloading compound assignments: +=, etc.

    The compound assignment ``add and assign'' a += b; is equivalent to a = a + b; Similarly, C++ provides operators for the compound assignments -=, *=, and /=. The function names corresponding to them are operator+=, etc. For operations between pairs of vectors, the meanings of ``add and assign'' and ``subtract and assign'' are natural.

  7. General Rules for Operator Overloading

    For example, the addition/assignment operator, +=, requires the left operand to be an l-value when applied to basic types; there is no such requirement when the operator is overloaded. Note For consistency, it is often best to follow the model of the built-in types when defining overloaded operators.

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

  9. Operator Overloading in C++

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

  10. Why Assignment Operator Overloading Must Return Reference?

    In C++, when overloading the assignment operator, we must return a reference to the current object (*this) as it allows for assignment chaining, maintains consistency with built-in types, and avoids unnecessary object copying. By following these best practice, we can ensure that our overloaded operators are efficient, intuitive, and behave as ...

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

    Overloaded operators are implemented as functions. The name of an overloaded operator is operator x, where x is the operator as it appears in the following table. For example, to overload the addition operator, you define a function called operator+. Similarly, to overload the addition/assignment operator, +=, define a function called operator+=.

  13. Mastering Operator Overloading: A Comprehensive Guide

    Main Function: In main(), two ComplexNumber objects c1 and c2 are instantiated with specific values. Then, leveraging our overloaded operators, we add ( c1 + c2) and subtract ( c1 - c2) these complex numbers and display the results using the display() method. How it Achieves its Objectives:

  14. Operator overloading in C++

    Operator overloading by Example. This example will add basic arithmetic operations: addition, subtraction, multiplication and division to Complex number class. These operations will use operators: +, -, *, / and their assigning counterparts +=, -=, *=, /=. Only addition will be implemented. We will also add input/output operators to read/write ...

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

  16. Assignment Operator Overloading in C++ Syntax Explanation

    c = (a = b); This will assign b to a and then assign the return value of the operator= call to c. As you dont want to make a unneccesary copy you return a reference to the object itself aka *this. Actually avoiding a copy is not the only reason for using a reference, but if you consider. (d = e) = f;

  17. c++

    If yes, then yes, you should overload it. The compiler does not automatically create one even if you have overloaded the operator+and assignment operator. You can implemented them in terms of each other, but they all need to be implemented. In general, the addition and assignment will do the same thing as the compound assignment, but this is ...

  18. c++ overloading assignment operator of another class

    The assignment operator can't be overloaded as a stand-alone (non-member) function. If you have control of the class, and can modify it, you can make a conversion operator: operator double() const { return todouble(); } It must still be a member function though. double is not a class and does not have members.

  19. C++ overload assignment operator

    Assignment operator overloading function will be called when you are trying to assign an object to already created object. SpecialFloat f = 1.0f; Above statement is trying to create an object. So Assignment operator overloading function won't be called in this case. answered Jan 24, 2022 at 15:17.

  20. Assignment Operator Overload in c++

    An overloaded assignment operator should look like this: Complex &Complex::operator=(const Complex& rhs) {. real = rhs.real; imaginary = rhs.imaginary; return *this; }; You should also note, that if you overload the assignment operator you should overload the copy constructor for Complex in the same manner: