Operator overloading question

If we look at the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class test_class
{
public:
	struct variables
	{
		int var_1;
		float var_2;
	} _data;

	test_class();
	~test_class();
	
	test_class& operator=(test_class& obj_arg);
};

test_class::test_class()
{
}

test_class::~test_class()
{
}
test_class & test_class::operator=(test_class& obj_arg)
{
	this->_data.var_1 = obj_arg._data.var_1;
	this->_data.var_2 = obj_arg._data.var_2;

	return *this;
}

...

test_class instance_1, instance_2;

...

instance_1 = instance_2;


The overloaded = operator will copy the data from instance_2 to instance_1, so the operator function will be called in instance_1 with instance_2 as its arg. If my analogy is correct this far, the question is why does it return *this. I've seen multiple snippets of code do the same and I don't understand the reason for the return value, can't it just be voided?
Last edited on
This is necessary for chaining assignments.

For example, make your assignment operator void, create three instances then assign the last to the other two in a one-liner. It fails: https://ideone.com/bCizR4

Returning a reference to your object allows this to happen. Same code with reference returned (and an obligatory self-assignment check!) : https://ideone.com/z1ZELL
Last edited on
Ah, I understand now.

Thank you very much :)
Last edited on
Topic archived. No new replies allowed.