Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

assignment operator

$
0
0
I'm trying to understand why the assignment operator must return a reference.I understood why it shouldn't return void,because of the chained operations.
But this two codes work exactly the same:
#include <iostream>
using namespace std;
class fail{
	int a;
public:
	void display() {
		cout<<a<<" ";
	}
	fail (){}
	fail(int n) { a=n;}
	
	
	fail operator= (const fail& rhs){ // here difference
		a=rhs.a;
		return *this;
	}
};

int main() {
	fail one(2);
	fail two;
	fail three(9);
	two=one=three=314;
	one.display();
	two.display();
	three.display();

	cin.ignore();
	return 0;
}


#include <iostream>
using namespace std;
class fail{
	int a;
public:
	void display() {
		cout<<a<<" ";
	}
	fail (){}
	fail(int n) { a=n;}
	
	
	fail& operator= (const fail& rhs){ //here difference
		a=rhs.a;
		return *this;
	}
};

int main() {
	fail one(2);
	fail two;
	fail three(9);
	two=one=three=314;
	one.display();
	two.display();
	three.display();

	cin.ignore();
	return 0;
}

So what's the difference,why should it return a reference ?

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>