In this chapter we shall learn about below topics:
1. Introduction
2. Syntax:
3. Need for user defined assignment operator.
4. User defined assignment operator example
1. Introduction:
A user defined copy assignment operator is used to create a new object from an existing one by initialization.
The compiler creates a default copy constructor and assignment operators for every class.
If there are no pointer as data member, then there is no need to create a user defined copy assignment operator.
2. Syntax:
A::operator=(A)
Need for user defined assignment operator.
Below is the example for a class without user defined copy assignment operator.
#include <iostream>
// for more tutorial in C++ visit www.prodevelopertutorial.com
using namespace std;
class MyClass
{
int *ptr;
public:
MyClass (int i = 0)
{
ptr = new int(i);
}
void setValue (int i)
{
*ptr = i;
}
void print()
{
cout << *ptr << endl;
}
};
int main()
{
MyClass obj1(5);
MyClass obj2;
obj2 = obj1; // calling default assignement operator
obj2.print(); // printing the value
obj1.setValue(10); // change the value for obj1
obj2.print(); // printing the value
return 0;
}
Output:
5
10
As you can see in above example, the default assignment operator has made a shallow copy of the objects.
It means both of the object now point to the same memory location.
Hence if you change the pointer value of one object, the other object value will be changed.
Hence we need user defined assignment operator.
User defined assignment operator example
#include <iostream>
// for more tutorial in C++ visit www.prodevelopertutorial.com
using namespace std;
class MyClass
{
int *ptr;
public:
MyClass (int i = 0)
{
ptr = new int(i);
}
void setValue (int i)
{
*ptr = i;
}
void print()
{
cout << *ptr << endl;
}
MyClass & operator = (const MyClass &t)
{
// Check for self assignment
if(this != &t)
*ptr = *(t.ptr);
return *this;
}
};
int main()
{
MyClass obj1(5);
MyClass obj2;
obj2 = obj1; // calling default assignement operator
obj2.print(); // printing the value
obj1.setValue(10); // change the value for obj1
obj2.print(); // printing the value
return 0;
}
Output:
5
5