Assignment Operators Overloading in C++
Assignment
Operator is Used to assign value to an variable. Assignment operator is denoted
by equal to sign. Assignment operator
have Two values L-Value and R-value. Operator copies R-Value into L-Value. It
is a binary operator. C++ Overloading
assignment operator can be done in object oriented programming. Assignment
operator must be overloaded by a non-static member function only. If the
overloading function for the assignment operator is not written in the class,
the compiler generates the function to overload the assignment operator.
Fig:Assignment Operators Overloading in C++ |
Syntax:
Return_type operator=(const class_name,&)
Program:
#include<iostream.h>
#include<conio.h>
class Distance
{
private:
int feet;
int inches;
public:
Distance()
{
feet=0;
inches=0;
}
Distance(int f,int i)
{
feet=f;
inches=i;
}
void operator=(const Distance &D)
{
feet=D.feet;
inches=D.inches;
}
void displayDistance()
{
cout<<”F: “<<feet<< “
I:”<<inches<<endl;
}
};
void main()
{
Distance
D1(11,10), D2(5,11);
cout<<”first distance”;
D1.displayDistance();
cout<<”second
distance”;
D2.displayDistance();
D1=D2;
cout<<”first
distance”;
D1.displayDistance();
getch();
}
Output:
First Distance: F:11 I:
10
Second Distance: F:5
I:11
No comments:
Post a Comment