C++ Assignment Operator Overloading
Last Updated :
03 Apr, 2025
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.
In C++, the compiler automatically provides a default assignment operator for classes. This operator performs a shallow copy of each member of the class from one object to another. This means that if we don't explicitly overload the assignment operator, the compiler will still allow us to assign one object to another using the assignment operator (=
), and it won't generate an error.
So, when we should perform assignment operator overloading?
When our class involves dynamic memory allocation (e.g., pointers) and we need to perform a deep copy to prevent issues like double deletion or data corruption.
Example
C++
#include <iostream>
using namespace std;
// Dummy class
class GfG {
public:
int val;
};
int main() {
GfG c1,c2;
c2.val = 22;
// Copying c2 object to c1
c1 = c2;
cout << c1.val;
return 0;
}
In the above program, the default assignment operator is provided to GfG class, and we can use it to copy the objects of this class to each other without any issue. But what if GfG class had dynamic resources as shown in the below example:
C++
#include <iostream>
using namespace std;
// Dummy class
class GfG {
public:
int* arr;
int _size;
GfG(int size = 3) {
arr = new int[size];
_size = size;
}
// Deleting dynamic resources
~GfG() {
delete arr;
}
};
int main() {
GfG c1,c2;
// Copying c2 object to c1
c1 = c2;
// Print the pointers to the allocated memory
cout << c1.arr << endl;
cout << c2.arr;
return 0;
}
Output
0x5c200553a2d0
free(): double free detected in tcache 2
As we can see, arr member of both the objects contains same address or points to the same memory. While copying the object c2 to c1, only the memory address is copied, not the actual data. This is called shallow copy, and it causes may cause double free error as the memory allocated is already freed when c1 goes out of scope. So, when c2 goes of scope, the same memory is again tried to be deleted.
This issue is resolved by overloading the assignment operator to not just copy the addresses but allocate new memory and copy the actual data i.e. perform deep copy.
C++
#include <bits/stdc++.h>
using namespace std;
// Dummy class
class GfG {
public:
int* arr;
int _size;
GfG(int size = 3) {
arr = new int[size];
_size = size;
}
// Overloaded assignment operator
GfG& operator=(const GfG& c) {
// self assignment check
if (this != &c) {
// Allocate new block
int* temp = arr;
arr = new(nothrow) int[c._size];
// If allocation fails
if (arr == nullptr) {
arr = temp;
}
else {
// Deallocate current block
delete [] temp;
// Copy data
_size = c._size;
memmove(arr, c.arr, _size * sizeof(int));
}
}
return *this;
}
// Deleting dynamic resources
~GfG() {
delete arr;
}
};
int main() {
GfG c1,c2;
// Initialize c2.arr with some values
for (int i = 0; i < c1._size; i++) {
c2.arr[i] = i + 10;
}
// Copying c2 object to c1
c1 = c2;
// Print the pointers to the allocated memory
cout << c1.arr << endl;
cout << c2.arr;
return 0;
}
Output0x350a5c60
0x350a5c40
Now, after copy, whatever happens to the object c2, it will not affect c1.
While managing dynamic resources, the above approach of assignment overloading have few flaws and there is more efficient approach that is recommended. See this article for more info - Copy-and-Swap Idiom in C++
Similar Reads
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Object Oriented Programming in C++ Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Inheritance in C++ The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the informatio
10 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read