AIM: Write a C++ program to illustrate assignment operator overloading.
THEORY:
An assignment operator is the operator used to assign a new value to a variable, property, event or indexer element in C# programming language. Assignment operators can also be used for logical operations such as bitwise logical operations or operations on integral operands and Boolean operands.
Unlike in C++, assignment operators in C# cannot be overloaded directly, but the user-defined types can overload the operators like +, -, /, etc. This allows the assignment operator to be used with those type
The following are the characteristics of assignment operators:
- When using the “=” operator for an assignment with the left operand as the property or indexer access, the property or indexer must have a set accessor.
- Overloading a binary operator implicitly overloads its corresponding assignment operator (if any).
- The different assignment operators are based on the type of operation performed between two operands such as addition (+=), subtraction, (-=), etc. The meaning of the operator symbol used depends on the type of the operands.
- Assignment operators are right-associative, which means they are grouped from right to left
- nment using assignment operator (a += b) achieves the same result as that without ( =a +b), the difference between the two ways is that unlike in the latter example, “a” is evaluated only once.
- The assignment operator usually returns a reference
SOURCE CODE:
#include<iostream>
using namespace std;
class A
{
public:
int a,b;
A(){ a=b=0; }
A (int m,int n)
{
a=m;
b=n;
}
void operator=(A ob)
{
a=ob.a;
b=ob.b;
}
void show()
{
cout<<“a= “<<a<<“\t b= “<<b<<endl;
}
};
int main()
{
int a,b;
cout<<“Enter two values:\n”;
cin>>a>>b;
A ob1(a,b),ob2;
cout<<“Values of first object are:\n”;
ob1.show();
cout<<“Values of second object before assign:\n”;
ob2.show();
ob2=ob1;
cout<<“Values of second object after assign:\n”;
ob2.show();
}
OUTPUT:
Enter two values:
85 63
Values of first object are:
a=85 b=63
Values of second object before assign:
a=0 b=0
Values of second object after assign:
a=85 b=63