cppreference.com

Assignment operators.

Assignment operators modify the value of the object.

[ edit ] Definitions

Copy assignment replaces the contents of the object a with a copy of the contents of b ( b is not modified). For class types, this is performed in a special member function, described in copy assignment operator .

For non-class types, copy and move assignment are indistinguishable and are referred to as direct assignment .

Compound assignment replace the contents of the object a with the result of a binary operation between the previous value of a and the value of b .

[ edit ] Assignment operator syntax

The assignment expressions have the form

  • ↑ target-expr must have higher precedence than an assignment expression.
  • ↑ new-value cannot be a comma expression, because its precedence is lower.

[ edit ] Built-in simple assignment operator

For the built-in simple assignment, the object referred to by target-expr is modified by replacing its value with the result of new-value . target-expr must be a modifiable lvalue.

The result of a built-in simple assignment is an lvalue of the type of target-expr , referring to target-expr . If target-expr is a bit-field , the result is also a bit-field.

[ edit ] Assignment from an expression

If new-value is an expression, it is implicitly converted to the cv-unqualified type of target-expr . When target-expr is a bit-field that cannot represent the value of the expression, the resulting value of the bit-field is implementation-defined.

If target-expr and new-value identify overlapping objects, the behavior is undefined (unless the overlap is exact and the type is the same).

In overload resolution against user-defined operators , for every type T , the following function signatures participate in overload resolution:

For every enumeration or pointer to member type T , optionally volatile-qualified, the following function signature participates in overload resolution:

For every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signature participates in overload resolution:

[ edit ] Built-in compound assignment operator

The behavior of every built-in compound-assignment expression target-expr   op   =   new-value is exactly the same as the behavior of the expression target-expr   =   target-expr   op   new-value , except that target-expr is evaluated only once.

The requirements on target-expr and new-value of built-in simple assignment operators also apply. Furthermore:

  • For + = and - = , the type of target-expr must be an arithmetic type or a pointer to a (possibly cv-qualified) completely-defined object type .
  • For all other compound assignment operators, the type of target-expr must be an arithmetic type.

In overload resolution against user-defined operators , for every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signatures participate in overload resolution:

For every pair I1 and I2 , where I1 is an integral type (optionally volatile-qualified) and I2 is a promoted integral type, the following function signatures participate in overload resolution:

For every optionally cv-qualified object type T , the following function signatures participate in overload resolution:

[ edit ] Example

Possible output:

[ edit ] Defect reports

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

[ edit ] See also

Operator precedence

Operator overloading

  • 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 25 January 2024, at 22:41.
  • This page has been accessed 410,142 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

C++ Tutorial

C++ functions, c++ classes, c++ examples, c++ assignment operators, assignment operators.

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator ( = ) to assign the value 10 to a variable called x :

The addition assignment operator ( += ) adds a value to a variable:

A list of all assignment operators:

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

This browser is no longer supported.

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

Assignment operators

  • 8 contributors

expression assignment-operator expression

assignment-operator : one of   =   *=   /=   %=   +=   -=   <<=   >>=   &=   ^=   |=

Assignment operators store a value in the object specified by the left operand. There are two kinds of assignment operations:

simple assignment , in which the value of the second operand is stored in the object specified by the first operand.

compound assignment , in which an arithmetic, shift, or bitwise operation is performed before storing the result.

All assignment operators in the following table except the = operator are compound assignment operators.

Assignment operators table

Operator keywords.

Three of the compound assignment operators have keyword equivalents. They are:

C++ specifies these operator keywords as alternative spellings for the compound assignment operators. In C, the alternative spellings are provided as macros in the <iso646.h> header. In C++, the alternative spellings are keywords; use of <iso646.h> or the C++ equivalent <ciso646> is deprecated. In Microsoft C++, the /permissive- or /Za compiler option is required to enable the alternative spelling.

Simple assignment

The simple assignment operator ( = ) causes the value of the second operand to be stored in the object specified by the first operand. If both objects are of arithmetic types, the right operand is converted to the type of the left, before storing the value.

Objects of const and volatile types can be assigned to l-values of types that are only volatile , or that aren't const or volatile .

Assignment to objects of class type ( struct , union , and class types) is performed by a function named operator= . The default behavior of this operator function is to perform a member-wise copy assignment of the object's non-static data members and direct base classes; however, this behavior can be modified using overloaded operators. For more information, see Operator overloading . Class types can also have copy assignment and move assignment operators. For more information, see Copy constructors and copy assignment operators and Move constructors and move assignment operators .

An object of any unambiguously derived class from a given base class can be assigned to an object of the base class. The reverse isn't true because there's an implicit conversion from derived class to base class, but not from base class to derived class. For example:

Assignments to reference types behave as if the assignment were being made to the object to which the reference points.

For class-type objects, assignment is different from initialization. To illustrate how different assignment and initialization can be, consider the code

The preceding code shows an initializer; it calls the constructor for UserType2 that takes an argument of type UserType1 . Given the code

the assignment statement

can have one of the following effects:

Call the function operator= for UserType2 , provided operator= is provided with a UserType1 argument.

Call the explicit conversion function UserType1::operator UserType2 , if such a function exists.

Call a constructor UserType2::UserType2 , provided such a constructor exists, that takes a UserType1 argument and copies the result.

Compound assignment

The compound assignment operators are shown in the Assignment operators table . These operators have the form e1 op = e2 , where e1 is a non- const modifiable l-value and e2 is:

an arithmetic type

a pointer, if op is + or -

a type for which there exists a matching operator *op*= overload for the type of e1

The built-in e1 op = e2 form behaves as e1 = e1 op e2 , but e1 is evaluated only once.

Compound assignment to an enumerated type generates an error message. If the left operand is of a pointer type, the right operand must be of a pointer type, or it must be a constant expression that evaluates to 0. When the left operand is of an integral type, the right operand must not be of a pointer type.

Result of built-in assignment operators

The built-in assignment operators return the value of the object specified by the left operand after the assignment (and the arithmetic/logical operation in the case of compound assignment operators). The resultant type is the type of the left operand. The result of an assignment expression is always an l-value. These operators have right-to-left associativity. The left operand must be a modifiable l-value.

In ANSI C, the result of an assignment expression isn't an l-value. That means the legal C++ expression (a += b) += c isn't allowed in C.

Expressions with binary operators C++ built-in operators, precedence, and associativity C assignment operators

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

  • C++ Language
  • Ascii Codes
  • Boolean Operations
  • Numerical Bases

Introduction

Basics of c++.

  • Structure of a program
  • Variables and types
  • Basic Input/Output

Program structure

  • Statements and flow control
  • Overloads and templates
  • Name visibility

Compound data types

  • Character sequences
  • Dynamic memory
  • Data structures
  • Other data types
  • Classes (I)
  • Classes (II)
  • Special members
  • Friendship and inheritance
  • Polymorphism

Other language features

  • Type conversions
  • Preprocessor directives

Standard library

  • Input/output with files

Assignment operator (=)

Arithmetic operators ( +, -, *, /, % ), compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=), increment and decrement (++, --), relational and comparison operators ( ==, =, >, <, >=, <= ), logical operators ( , &&, || ), conditional ternary operator ( ), comma operator ( , ), bitwise operators ( &, |, ^, ~, <<, >> ), explicit type casting operator, other operators, precedence of operators.

  • TutorialKart
  • SAP Tutorials
  • Salesforce Admin
  • Salesforce Developer
  • Visualforce
  • Informatica
  • Kafka Tutorial
  • Spark Tutorial
  • Tomcat Tutorial
  • Python Tkinter

Programming

  • Bash Script
  • Julia Tutorial
  • CouchDB Tutorial
  • MongoDB Tutorial
  • PostgreSQL Tutorial
  • Android Compose
  • Flutter Tutorial
  • Kotlin Android

Web & Server

  • Selenium Java
  • C++ Tutorials
  • C++ Tutorial
  • C++ Hello World Program
  • C++ Comments
  • C++ Variables
  • Print datatype of variable
  • C++ If Else
  • Addition Operator
  • Subtraction Operator
  • Multiplication Operator
  • Division Operator
  • Modulus Operator
  • Increment Operator
  • Decrement Operator
  • Simple Assignment
  • Addition Assignment
  • Subtraction Assignment
  • ADVERTISEMENT
  • Multiplication Assignment
  • Division Assignment
  • Remainder Assignment
  • Bitwise AND Assignment
  • Bitwise OR Assignment
  • Bitwise XOR Assignment
  • Left Shift Assignment
  • Right Shift Assignment
  • Bitwise AND
  • Bitwise XOR
  • Bitwise Complement
  • Bitwise Left shift
  • Bitwise Right shift
  • Logical AND
  • Logical NOT
  • Not Equal to
  • Greater than
  • Greater than or Equal to
  • Less than or Equal to
  • Ternary Operator
  • Do-while loop
  • Infinite While loop
  • Infinite For loop
  • C++ Recursion
  • Create empty string
  • String length
  • String comparison
  • Get character at specific index
  • Get first character
  • Get last character
  • Find index of substring
  • Iterate over characters
  • Print unique characters
  • Check if strings are equal
  • Append string
  • Concatenate strings
  • String reverse
  • String replace
  • Swap strings
  • Convert string to uppercase
  • Convert string to lowercase
  • Append character at end of string
  • Append character to beginning of string
  • Insert character at specific index
  • Remove last character
  • Replace specific character
  • Convert string to integer
  • Convert integer to string
  • Convert string to char array
  • Convert char array to string
  • Initialize array
  • Array length
  • Print array
  • Loop through array
  • Basic array operations
  • Array of objects
  • Array of arrays
  • Convert array to vector
  • Sum of elements in array
  • Average of elements in array
  • Find largest number in array
  • Find smallest number in array
  • Sort integer array
  • Find string with least length in array
  • Create an empty vector
  • Create vector of specific size
  • Create vector with initial values
  • Copy a vector to another
  • Vector length or size
  • Vector of vectors
  • Vector print elements
  • Vector iterate using For loop
  • Vector iterate using While loop
  • Vector Foreach
  • Get reference to element at specific index
  • Check if vector is empty
  • Check if vectors are equal
  • Check if vector contains element
  • Update/Transform
  • Add element(s) to vector
  • Append element to vector
  • Append vector
  • Insert element at the beginning of vector
  • Remove first element from vector
  • Remove last element from vector
  • Remove element at specific index from vector
  • Remove duplicates from vector
  • Remove elements from vector based on condition
  • Resize vector
  • Swap elements of two vectors
  • Remove all elements from vector
  • Reverse a vector
  • Sort a vector
  • Conversions
  • Convert vector to map
  • Join vector elements to a string
  • Filter even numbers in vector
  • Filter odd numbers in vector
  • Get unique elements of a vector
  • Remove empty strings from vector
  • Sort integer vector in ascending order
  • Sort integer vector in descending order
  • Sort string vector based on length
  • Sort string vector lexicographically
  • Split vector into two equal halves
  • Declare tuple
  • Initialise tuple
  • Swap tuples
  • Unpack tuple elements into variables
  • Concatenate tuples
  • Constructor
  • Copy constructor
  • Virtual destructor
  • Friend class
  • Friend function
  • Inheritance
  • Multiple inheritance
  • Virtual inheritance
  • Function overloading
  • Operator overloading
  • Function overriding
  • C++ Try Catch
  • Math acos()
  • Math acosh()
  • Math asin()
  • Math asinh()
  • Math atan()
  • Math atan2()
  • Math atanh()
  • Math cbrt()
  • Math ceil()
  • Math copysign()
  • Math cosh()
  • Math exp2()
  • Math expm1()
  • Math fabs()
  • Math fdim()
  • Math floor()
  • Math fmax()
  • Math fmin()
  • Math fmod()
  • Math frexp()
  • Math hypot()
  • Math ilogb()
  • Math ldexp()
  • Math llrint()
  • Math llround()
  • Math log10()
  • Math log1p()
  • Math log2()
  • Math logb()
  • Math lrint()
  • Math lround()
  • Math modf()
  • Math nearbyint()
  • Math nextafter()
  • Math nexttoward()
  • Math remainder()
  • Math remquo()
  • Math rint()
  • Math round()
  • Math scalbln()
  • Math scalbn()
  • Math sinh()
  • Math sqrt()
  • Math tanh()
  • Math trunc()
  • Armstrong number
  • Average of three numbers
  • Convert decimal to binary
  • Factorial of a number
  • Factors of a number
  • Fibonacci series
  • Find largest of three numbers
  • Find quotient and remainder
  • HCF/GCD of two numbers
  • Hello World
  • LCM of two numbers
  • Maximum of three numbers
  • Multiply two numbers
  • Sum of two numbers
  • Sum of three numbers
  • Sum of natural numbers
  • Sum of digits in a number
  • Swap two numbers
  • Palindrome number
  • Palindrome string
  • Pattern printing
  • Power of a number
  • Prime number
  • Prime Numbers between two numbers
  • Print number entered by User
  • Reverse a Number
  • Read input from user
  • ❯ C++ Tutorial
  • ❯ C++ Operators
  • ❯ Assignment Operators

C++ Assignment Operators

In this tutorial, we will learn about different Assignment Operators available in C++ programming language and go through each of these Assignment Operations in detail, with the help of examples.

C++ Assignment Operators are used to optionally perform an action with given operands and assign the result back to given variable (left operand).

The syntax of any Assignment Operator with operands is

Operator Symbol – Example – Description

The following table specifies symbol, example, and description for each of the Assignment Operator in C++.

1. Simple Assignment

In the following example, we assign a value of 2 to x using Simple Assignment Operator.

2. Addition Assignment

In the following example, we add 3 to x and assign the result to x using Addition Assignment Operator.

3. Subtraction Assignment

In the following example, we subtract 3 from x and assign the result to x using Subtraction Assignment Operator.

4. Multiplication Assignment

In the following example, we multiply 3 to x and assign the result to x using Multiplication Assignment Operator.

5. Division Assignment

In the following example, we divide x by 3 and assign the quotient to x using Division Assignment Operator.

6. Remainder Assignment

In the following example, we divide x by 3 and assign the remainder to x using Remainder Assignment Operator.

7. Bitwise AND Assignment

In the following example, we do bitwise AND operation between x and 3 and assign the result to x using Bitwise AND Assignment Operator.

8. Bitwise OR Assignment

In the following example, we do bitwise OR operation between x and 3 and assign the result to x using Bitwise OR Assignment Operator.

9. Bitwise XOR Assignment

In the following example, we do bitwise XOR operation between x and 3 and assign the result to x using Bitwise XOR Assignment Operator.

10. Left-shift Assignment

In the following example, we left-shift x by 3 places and assign the result to x using Left-shift Assignment Operator.

11. Right-shift Assignment

In the following example, we right-shift x by 3 places and assign the result to x using Right-shift Assignment Operator.

In this C++ Tutorial , we learned what Assignment Operators are, and how to use them in C++ programs, with the help of examples.

Popular Courses by TutorialKart

App developement, web development, online tools.

Assignment operators

Assignment operators modify the value of the object.

Explanation

copy assignment operator replaces the contents of the object a with a copy of the contents of b ( b is not modified). For class types, this is a special member function, described in copy assignment operator .

move assignment operator replaces the contents of the object a with the contents of b , avoiding copying if possible ( b may be modified). For class types, this is a special member function, described in move assignment operator . (since C++11)

For non-class types, copy and move assignment are indistinguishable and are referred to as direct assignment .

compound assignment operators replace the contents of the object a with the result of a binary operation between the previous value of a and the value of b .

Builtin direct assignment

The direct assignment expressions have the form

For the built-in operator, lhs may have any non-const scalar type and rhs must be implicitly convertible to the type of lhs .

The direct assignment operator expects a modifiable lvalue as its left operand and an rvalue expression or a braced-init-list (since C++11) as its right operand, and returns an lvalue identifying the left operand after modification.

For non-class types, the right operand is first implicitly converted to the cv-unqualified type of the left operand, and then its value is copied into the object identified by left operand.

When the left operand has reference type, the assignment operator modifies the referred-to object.

If the left and the right operands identify overlapping objects, the behavior is undefined (unless the overlap is exact and the type is the same)

In overload resolution against user-defined operators , for every type T , the following function signatures participate in overload resolution:

For every enumeration or pointer to member type T , optionally volatile-qualified, the following function signature participates in overload resolution:

For every pair A1 and A2, where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signature participates in overload resolution:

Builtin compound assignment

The compound assignment expressions have the form

The behavior of every builtin compound-assignment expression E1 op = E2 (where E1 is a modifiable lvalue expression and E2 is an rvalue expression or a braced-init-list (since C++11) ) is exactly the same as the behavior of the expression E1 = E1 op E2 , except that the expression E1 is evaluated only once and that it behaves as a single operation with respect to indeterminately-sequenced function calls (e.g. in f ( a + = b, g ( ) ) , the += is either not started at all or is completed as seen from inside g ( ) ).

In overload resolution against user-defined operators , for every pair A1 and A2, where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signatures participate in overload resolution:

For every pair I1 and I2, where I1 is an integral type (optionally volatile-qualified) and I2 is a promoted integral type, the following function signatures participate in overload resolution:

For every optionally cv-qualified object type T , the following function signatures participate in overload resolution:

Operator precedence

Operator overloading

Learn C++

21.12 — Overloading the assignment operator

The copy assignment operator (operator=) is used to copy values from one object to another already existing object .

Related content

As of C++11, C++ also supports “Move assignment”. We discuss move assignment in lesson 22.3 -- Move constructors and move assignment .

Copy assignment vs Copy constructor

The purpose of the copy constructor and the copy assignment operator are almost equivalent -- both copy one object to another. However, the copy constructor initializes new objects, whereas the assignment operator replaces the contents of existing objects.

The difference between the copy constructor and the copy assignment operator causes a lot of confusion for new programmers, but it’s really not all that difficult. Summarizing:

  • If a new object has to be created before the copying can occur, the copy constructor is used (note: this includes passing or returning objects by value).
  • If a new object does not have to be created before the copying can occur, the assignment operator is used.

Overloading the assignment operator

Overloading the copy assignment operator (operator=) is fairly straightforward, with one specific caveat that we’ll get to. The copy assignment operator must be overloaded as a member function.

This prints:

This should all be pretty straightforward by now. Our overloaded operator= returns *this, so that we can chain multiple assignments together:

Issues due to self-assignment

Here’s where things start to get a little more interesting. C++ allows self-assignment:

This will call f1.operator=(f1), and under the simplistic implementation above, all of the members will be assigned to themselves. In this particular example, the self-assignment causes each member to be assigned to itself, which has no overall impact, other than wasting time. In most cases, a self-assignment doesn’t need to do anything at all!

However, in cases where an assignment operator needs to dynamically assign memory, self-assignment can actually be dangerous:

First, run the program as it is. You’ll see that the program prints “Alex” as it should.

Now run the following program:

You’ll probably get garbage output. What happened?

Consider what happens in the overloaded operator= when the implicit object AND the passed in parameter (str) are both variable alex. In this case, m_data is the same as str.m_data. The first thing that happens is that the function checks to see if the implicit object already has a string. If so, it needs to delete it, so we don’t end up with a memory leak. In this case, m_data is allocated, so the function deletes m_data. But because str is the same as *this, the string that we wanted to copy has been deleted and m_data (and str.m_data) are dangling.

Later on, we allocate new memory to m_data (and str.m_data). So when we subsequently copy the data from str.m_data into m_data, we’re copying garbage, because str.m_data was never initialized.

Detecting and handling self-assignment

Fortunately, we can detect when self-assignment occurs. Here’s an updated implementation of our overloaded operator= for the MyString class:

By checking if the address of our implicit object is the same as the address of the object being passed in as a parameter, we can have our assignment operator just return immediately without doing any other work.

Because this is just a pointer comparison, it should be fast, and does not require operator== to be overloaded.

When not to handle self-assignment

Typically the self-assignment check is skipped for copy constructors. Because the object being copy constructed is newly created, the only case where the newly created object can be equal to the object being copied is when you try to initialize a newly defined object with itself:

In such cases, your compiler should warn you that c is an uninitialized variable.

Second, the self-assignment check may be omitted in classes that can naturally handle self-assignment. Consider this Fraction class assignment operator that has a self-assignment guard:

If the self-assignment guard did not exist, this function would still operate correctly during a self-assignment (because all of the operations done by the function can handle self-assignment properly).

Because self-assignment is a rare event, some prominent C++ gurus recommend omitting the self-assignment guard even in classes that would benefit from it. We do not recommend this, as we believe it’s a better practice to code defensively and then selectively optimize later.

The copy and swap idiom

A better way to handle self-assignment issues is via what’s called the copy and swap idiom. There’s a great writeup of how this idiom works on Stack Overflow .

The implicit copy assignment operator

Unlike other operators, the compiler will provide an implicit public copy assignment operator for your class if you do not provide a user-defined one. This assignment operator does memberwise assignment (which is essentially the same as the memberwise initialization that default copy constructors do).

Just like other constructors and operators, you can prevent assignments from being made by making your copy assignment operator private or using the delete keyword:

Note that if your class has const members, the compiler will instead define the implicit operator= as deleted. This is because const members can’t be assigned, so the compiler will assume your class should not be assignable.

If you want a class with const members to be assignable (for all members that aren’t const), you will need to explicitly overload operator= and manually assign each non-const member.

guest

The Addition Assignment Operator and Increment Operator in C++

  • The Addition Assignment Operator and …

Addition Assignment Operator += in C++

Postfix increment and decrement operators ++ in c++, the difference between += and ++ operators in c++.

The Addition Assignment Operator and Increment Operator in C++

The article will discuss the concept and usage of addition assignment operators += and increment operators ++ in C++.

The += addition assignment operator adds a value to a variable and assigns its result. The two types of operands determine the behavior of the += addition assignment operator.

The operators appear after the postfix expression. The result of using the postfix increment operator ++ is that the value of the operand increases by one unit of the corresponding type.

Please note that the postfix increment or decrement expression evaluates its value before applying the corresponding operator.

Suppose the postfix operator is applied to the function argument. In that case, the increment or decrement of the argument value will not necessarily be performed before it is passed to the function.

An example of a postfix increment operator is shown below.

Both += and ++ operators increase the value of n by 1 .

The difference is that the return is the pre-increment value in the post-increment operator ++ . In contrast, the addition assignment operator += case returns the post-increment value.

First Case: post-increment ++ operator.

Second Case: addition assignment += operator.

Related Article - C++ Operator

  • Unary Negation Operator in C++
  • How to Overload the Bracket Operator in C++
  • How to Overload Input and Output Stream Insertion Operators in C++
  • How to Overload the Addition Operator in C++
  • How to Overload the == Operator in C++
  • Arrow Operator vs. Dot Operator in C++
  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
  • C++ Ternary or Conditional Operator
  • C++ Logical Operators
  • C++ Relational Operators
  • Increment (++) and Decrement (--) Operator Overloading in C++
  • Types of Operator Overloading in C++
  • How to Overload the Function Call Operator () in C++?
  • C++ Program For Iterative Quick Sort
  • How to Create Custom Assignment Operator in C++?
  • Constants in C++
  • Operators in C++
  • Typecast Operator Overloading in C++
  • How to Use the Not-Equal (!=) Operator in C++?
  • dot (.) operator in C++
  • How to Overload == Operator in C++?
  • Bitwise Operators in C++
  • C++ Arithmetic Operators
  • Increment Operator Behavior When Passed as Function Parameters in C++
  • How to Lock Window Resize C++ sfml?
  • Casting Operators in C++

C++ Assignment Operator Overloading

Prerequisite: 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.
  • Only a non-static member function should be used to overload the assignment operator.

We can’t directly use the Assignment Operator on objects. The simple explanation for this is that the Assignment Operator is predefined to operate only on built-in Data types. As the class and objects are user-defined data types, so the compiler generates an error.

here, a and b are of type integer, which is a built-in data type. Assignment Operator can be used directly on built-in data types.

c1 and c2 are variables of type “class C”. Here compiler will generate an error as we are trying to use an Assignment Operator on user-defined data types.

The above example can be done by implementing methods or functions inside the class, but we choose operator overloading instead. The reason for this is, operator overloading gives the functionality to use the operator directly which makes code easy to understand, and even code size decreases because of it. Also, operator overloading does not affect the normal working of the operator but provides extra functionality to it.

Now, if the user wants to use the assignment operator “=” to assign the value of the class variable to another class variable then the user has to redefine the meaning of the assignment operator “=”.  Redefining the meaning of operators really does not change their original meaning, instead, they have been given additional meaning along with their existing ones.

Please Login to comment...

  • cpp-operator
  • cpp-operator-overloading
  • 10 Best Free Social Media Management and Marketing Apps for Android - 2024
  • 10 Best Customer Database Software of 2024
  • How to Delete Whatsapp Business Account?
  • Discord vs Zoom: Select The Efficienct One for Virtual Meetings?
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. 3- The Assignment statement in c++

    assignment statement in cpp

  2. Pointer Expressions in C with Examples

    assignment statement in cpp

  3. Assignment Operators in C++

    assignment statement in cpp

  4. C++ Assignment Operator and Statement

    assignment statement in cpp

  5. C/C++ 中的赋值运算符

    assignment statement in cpp

  6. cpp_sample

    assignment statement in cpp

VIDEO

  1. Assignment Statement ll python ll Animation ll class-6 ll

  2. GOTO statement in Cpp Programming

  3. unconditional statement in Cpp program

  4. C++ Program

  5. CPP-Panay 44th NPA anniversary statement

  6. CPP Lect08: Compound Assignment Statement

COMMENTS

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

  2. Assignment Operators In C++

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

  3. 1.4

    Variable assignment. After a variable has been defined, you can give it a value (in a separate statement) ... One downside of assignment is that it requires at least two statements: one to define the variable, and another to assign the value. These two steps can be combined. When an object is defined, you can optionally give it an initial value.

  4. When would you want to assign a variable in an if condition?

    The issue isn't with your answer - I think it's about the best possible factual discussion of the history of the "assignment in an if-statement" style came about. The problem is your answer was referred by someone who utterly missed your characterization of GCC's hack and actually used your answer as a defense of that hack. I was pointing out ...

  5. C++ Assignment Operators

    Assignment Operators. Assignment operators are used to assign values to variables. In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x: Example. int x = 10;

  6. Assignment operators

    The built-in assignment operators return the value of the object specified by the left operand after the assignment (and the arithmetic/logical operation in the case of compound assignment operators). The resultant type is the type of the left operand. The result of an assignment expression is always an l-value.

  7. Operators

    This statement assigns to variable x the value contained in variable y.The value of x at the moment this statement is executed is lost and replaced by the value of y. Consider also that we are only assigning the value of y to x at the moment of the assignment operation. Therefore, if y changes at a later moment, it will not affect the new value taken by x.

  8. CUED

    4. Assignment of variables Assignment of statements. It is essential that every variable in a program is given a value explicitly before any attempt is made to use it. It is also very important that the value assigned is of the correct type. The most common form of statement in a program uses the assignment operator, =, and either an expression or a constant to assign a value to a variable:

  9. C++ Assignment Operators

    C++ Assignment Operators. C++ Assignment Operators are used to optionally perform an action with given operands and assign the result back to given variable (left operand). The syntax of any Assignment Operator with operands is. operand1 operator_symbol operand2.

  10. Assignment operators

    Assignment operators. Assignment operators modify the value of the object. 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 ...

  11. 21.12

    21.12 — Overloading the assignment operator. Alex November 27, 2023. The copy assignment operator (operator=) is used to copy values from one object to another already existing object. As of C++11, C++ also supports "Move assignment". We discuss move assignment in lesson 22.3 -- Move constructors and move assignment .

  12. In C++ what causes an assignment to evaluate as true or false when used

    An assignment statement evaluates to the new value of the variable assigned to (barring bizarre overloads of operator=). If the assignment happens in a boolean context it will then depend on the type of that value how it is treated. If the value is a bool, it is of course treated as a bool. If the value is a numeric value, a non-zero value is ...

  13. The Addition Assignment Operator and Increment Operator in C++

    The article will discuss the concept and usage of addition assignment operators += and increment operators ++ in C++. Addition Assignment Operator += in C++. The += addition assignment operator adds a value to a variable and assigns its result. The two types of operands determine the behavior of the += addition assignment operator. Example:

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

  15. Use of assignment operators inside an 'if' condition in C++

    In all the cases you've shown, it's still true that you've provided an expression that eventually is convertible to bool.If you look at the << operator of std::cout and similar ostreams, you'll see they all return a reference to the same stream. This stream also defines a conversion to bool operator, which is implicitly called in a context where a bool is expected.

  16. Assignment expression in C++ for-loop update expression

    Assignment expression in C++ for-loop update expression. According to cppreference.com the update expression, or iteration expression, of a for cycle in C++ language can be. any expression, which is executed after every iteration of the loop and before re-evaluating condition. //loop statements. However, the results I obtain at the end of the ...

  17. c++

    Requirements. VULTURE IS V, OWL IS O, EAGLE IS E... A for loop to input the data each bird watcher has collected.; inside the for loop, a do ... while loop to input and process the data collected by one bird watcher.; inside the do ... while loop a switch statement is used to calculate the number of eggs for each type of bird. the default option, which does nothing, is used when an x is entered.