A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/cpp/cpp-assignment-operator-overloading/ below:

C++ Assignment Operator Overloading - GeeksforGeeks

C++ Assignment Operator Overloading

Last Updated : 23 Jul, 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.

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;
}

Output
0x350a5c60
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++



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4