Assignment Operators in C++ are the symbols that are used to assign values to the variables. They perform simple value assignments and also combine with arithmetic and bitwise operators. In this article, we will discuss what an assignment operator in C++ is, its types with examples in C++, chaining assignment operators, how to overload the assignment operator in C++, limitations, and best practices.
Table of Contents:
What are Assignment Operators in C++?
The assignment operators in C++ are used to assign values to a variable. It stores the right-hand value into the left-hand variable.
Syntax:
variable = value;
C++ Assignment Operator Example:
int a;
a = 10; // Assigns the value 10 to variable a
Different Types of Assignment Operators in C++
There is a basic, simple assignment operator, and also various compound assignment operators.
1. Simple Assignment Operator (=) in C++
The simple assignment operator in C++ directly assigns the right-hand value to the left-hand variable.
Example:
Output:
The code shows how the simple assignment operator is used to assign the value 10 to the variable a and the value 20 to the variable b, and then the assigned variables are printed as a result to the console.
2. Compound Assignment Operators in C++ (+=, -=, *=, /=, etc.)
Compound assignment operators in C++ are a combination of basic arithmetic and bitwise operators with the assignment operator.
Syntax:
variable op= expression;
Here is the list of all the compound assignment operators in C++:
Operator Name | Symbol | Syntax | Description |
Add and assign | += | a += b; | Adds b to a and stores the result in a |
Subtract and assign | -= | a -= b; | Subtracts b from a and stores the result |
Multiply and assign | *= | a *= b; | Multiplies a by b and updates a |
Divide and assign | /= | a /= b; | Divides a by b and updates a |
Modulo and assign | %= | a %= b; | Computes a % b and stores the result in a |
Bitwise AND and assign | &= | a &= b; | Performs bitwise AND on a and b, updates a |
Bitwise OR and assign | | | |= | Performs bitwise OR on a and b, updates a |
Bitwise XOR and assign | ^= | a ^= b; | Performs bitwise XOR on a and b, updates a |
Left shift and assign | <<= | a <<= b; | Shifts a left by b bits and updates a |
Right shift and assign | >>= | a >>= b; | Shifts a right by b bits and updates a |
Example:
Output:
The code shows how the various compound assignment operators are used to perform basic mathematical operations and then to update a value in the same variable.
Chained Assignment Operator in C++
The chained assignment operator in C++ is referred to as assigning the same value to multiple variables in a single statement using the assignment operator(=). It works because the assignment operator gives a reference to the left-hand variable and allows further assignments.
Syntax:
a = b = c = value;
Example:
Output:
The code shows how the value 100 is first assigned to the variable c, then assigned to the variable b, and finally assigned to the variable a using chained assignment, which results in all three variables having the same value.
How to Use Assignment Operators in C++
Here are a few points with examples that help you to understand how to use assignment operators in C++:
- Assignment operators are used to assign values to variables.
- The most basic assignment operator is =, which is used to assign the right-hand value to the left-hand variable.
- You can also use compound assignment operators like +=, which adds a value to a variable: x += 5; is the same as x = x + 5;.
- Similarly, the -= operator is used to subtract a value: x -= 3; which means it reduces x by 3.
- The *= operator is used to multiply and assign.
- The /= operator is used to divide and assign, for example: x /= 4;, which means it divides x by 4.
- You can use the %= operator to assign the remainder after division, for example: x %= 3; which means that it sets x to x%3.
- The assignment operators are also used to make code shorter and easier to read when performing calculations and updating values.
Assignment Operator Overloading Between Classes in C++
Assignment operator overloading in C++ between different classes is only possible if the following conditions are met:
- There must be a compatible conversion function.
- An appropriate assignment operator is overloaded.
Let’s understand how to overload assignment operator in C++ with the help of the cases given below
Case 1: Using Conversion Constructor
In this approach, class B has a constructor that accepts an object of class A, and when an object of type A is assigned to an object of type B, then the compiler automatically calls this constructor to convert A into B.
Example:
Output:
The code shows that class B has a conversion constructor, which helps class B to be initialized from an object of class A by enabling the assignment B b = a, and then the assigned value is printed as an output.
Case 2: Overloading Assignment Operator
In this approach, class B overloads the assignment operator to accept an object of class A. It helps an existing object of class B to be assigned values from an object of class A by using the syntax b = a;, with the custom logic defined in the operator function.
Example:
Output:
The code shows how class B overloads the assignment operator to accept an object of class A, which allows the assignment b = a; to copy the data from class A into class B.
Limitations of Assignment Operators in C++
- Assignment operators are not inherited by derived classes in C++ and must be explicitly defined.
- The default assignment operator performs a shallow copy, which can lead to issues with pointers and dynamic memory.
- If the self-assignment is handled improperly, it can cause bugs or resource conflicts.
- The assignment operator must be manually overloaded for deep copying.
- An assignment between incompatible types is not allowed unless it is explicitly defined.
- Classes with the const or reference members cannot reassign those members in the assignment operator.
- If certain special member functions are defined, then the compiler may not generate a default assignment operator.
Best Practices for Writing Safe Assignment Operators in C++
- Always check for self-assignment inside overloaded assignment operators.
- You must return *this by reference to allow chained assignments.
- Always mark the assignment operator as =, and delete if your class is unable to be copied.
- You should use the copy-and-swap idiom to write safer and exception-safe assignment logic.
- You must implement a copy constructor if you have to implement a copy assignment.
- Always keep the assignment operator consistent with the copy and move semantics of the class.
- You should use the const references in the parameter to avoid unnecessary copying.
- You must ensure exception safety to prevent resource leaks during partial assignments.
Copy Assignment vs Move Assignment in C++
Here is a comparison table for copy assignment vs move assignment in C++:
Aspect |
Copy Assignment |
Move Assignment |
Purpose |
Creates a copy of the source object |
Transfers ownership of resources |
Efficiency |
Slower (involves deep copy) |
Faster (avoids deep copy) |
Resource Handling |
Allocates new memory and copies data |
Reuses and steals resources |
Use Case |
When the original object must be preserved |
When the source object is temporary |
Syntax Example |
obj1 = obj2; |
obj1 = std::move(obj2); |
Function Signature |
T& operator=(const T& other); |
T& operator=(T&& other); |
Conclusion
The assignment operator in C++ is an important operator to store values in variables. It also supports chaining and assignment between classes in C++. There are a variety of assignments that store values efficiently, but also have some limitations. So, by understanding the assignment operator and its types, assignment operator overloading in C++, limitations, and best practices, you can write efficient and maintainable C++ code.
The following articles provide a comprehensive introduction to the essential concepts and fundamentals of C++ programming.
Substring in C++ – Shows how to extract substrings in C++.
Pass objects to functions in C++ – Explains passing objects to functions in C++.
Why are not variable length arrays part of the C++ standard? – Explains why VLAs aren’t in the C++ standard.
Getline in C++ – Explains how getline() reads input lines in C++.
Array decay or array to pointer conversion in C++ – Covers how arrays convert to pointers in C++.
Read binary files in C++ – Teaches how to read binary data using C++.
ifstream get in C++ – Explores get() function from ifstream class.
istream readsome in C++ – Describes readsome() for reading available input.
Assignment Operators in C++ – FAQs
Q1. What are the assignment operators in C++?
The assignment operators in C++ are the operators that assigns the right-hand value to the left-hand variable using =.
Q2. What is a chained assignment operator in C++?
Assigning the same value to multiple variables in one statement is called a chained assignment operator in C++.
Q3. Can we assign between different classes?
Yes, we can assign between different classes using a conversion constructor and an overloaded assignment operator.
Q4. What is the risk of default assignment?
The default assignment performs a shallow copy, which can lead to issues with dynamic memory.
Q5. What is the difference between shallow copy and deep copy in assignment?
A shallow copy copies only the pointer/reference, while a deep copy creates a new copy of the actual data.
Q6. What is the difference between = and += in C++?
In C++, = assigns a value directly, while += adds a value to the variable and then assigns the result.
Q7. Can assignment operators be inherited in C++?
No, assignment operators cannot be inherited in C++; each class must define or explicitly use its own if needed.
Q8. How to avoid memory leaks while assignment operator overloading in C++?
To avoid memory leaks while assignment operator overloading in C++, properly release existing resources and perform deep copying.
Q9. Can const members be assigned using assignment operators?
No, const members cannot be assigned using assignment operators because their values cannot be modified after initialization.
Q10. How is move assignment different from copy assignment?
Move assignment transfers resources from one object to another, while copy assignment creates a duplicate of the resources.