Open In App

Default Assignment Operator and References in C++

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

We have discussed assignment operator overloading for dynamically allocated resources here. In this article, we discussed that when we don’t write our own assignment operator, the compiler creates an assignment operator itself that does shallow copy and thus causes problems. The difference between shallow copy and deep copy becomes visible when the class has pointers as member fields. However, there is no difference when pointers are not used. What happens when we have references in our class and there is no user-defined assignment operator. 

For example, predict the output of the following program,

CPP




// CPP program to demonstrate  references in a class and
// there is no user defined assignment operator
#include <iostream>
using namespace std;
  
class Test {
    int x;
    int& ref;
  
public:
    Test(int i)
        : x(i)
        , ref(x)
    {
    }
    void print() { cout << ref; }
    void setX(int i) { x = i; }
};
  
// Driver Code
int main()
{
    Test t1(10);
    Test t2(20);
    t2 = t1;
    t1.setX(40);
    t2.print();
    return 0;
}


Output:

Compiler Error: non-static reference member 'int& Test::ref', 
             can't use default assignment operator

The compiler doesn’t create default assignment operator in the following cases:

1. Class has a non-static data member of a const type or a reference type. 
2. Class has a non-static data member of a type that has an inaccessible copy assignment operator. 
3. Class is derived from a base class with an inaccessible copy assignment operator.

When any of the above conditions is true, the user must define the assignment operator. For example, if we add an assignment operator to the above code, the code works fine without any error.

CPP




// CPP Program to demonstrate assignment operator
#include <iostream>
using namespace std;
  
class Test {
    int x;
    int& ref;
  
public:
    Test(int i)
        : x(i)
        , ref(x)
    {
    }
    void print() { cout << ref; }
    void setX(int i) { x = i; }
    Test& operator=(const Test& t)
    {
        x = t.x;
        return *this;
    }
};
  
int main()
{
    Test t1(10);
    Test t2(20);
    t2 = t1;
    t1.setX(40);
    t2.print();
    return 0;
}


Output

10


Last Updated : 27 Dec, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads