Assignment Operator Overloading in C++

What are the Overloading Assignment Operators in C++?

Explanation

"=" is the overloading assignment operator. Here class type will be same for the source and destination. This operator creates a similar object, just like the copy constructor. Below example shows you how to overload the assignment operator for a particular class.

Example :




#include <iostream>
using namespace std;
class Opeatorr
{
private:
int ft; // 0 to infinite
int in; // 0 to 12
public:
// required constructors
Opeatorr(){
ft = 0;
in = 0;
}
Opeatorr(int f, int i){
ft = f;
in = i;
}
void operator=(const Opeatorr &D )
{
ft = D.ft;
in = D.in;
}
// method to display distance
void displayOpeatorr()
{
cout << "F: " << ft << " I:" << in << endl;
}
};
int main()
{
Opeatorr D1(1, 2), D2(3, 4);
cout << "First Opeator : ";
D1.displayOpeatorr();
cout << "Second Opeator :";
D2.displayOpeatorr();
// use assignment operator
D1 = D2;
cout << "First Opeator :";
D1.displayOpeatorr();
return 0;
}


Result :


First Opeator : F: 1 I:2
Second Opeator :F: 3 I:4
First Opeator :F: 3 I:4


In the above example, using the assignment operator got two variables as an input from the users and displayed the values.

C++ Tutorial


Ask Questions

Ask Question