What is the role of “&” and “*” on operator overloading?

I have been reading about Overloading Operators.
And I found two ways of using it. Like in 1) and 2).


In 1) we use "&" on Pareja& and "*" on return *(...

But in 2) we don't use it.

When have I to use this keywords and when not?

Thanks you very much.


1)
1
2
3
Pareja& operator+ (const Pareja &parametro1, const Pareja &parametro2) {
	return *(new Pareja(parametro1.a + parametro2.a, parametro1.b + parametro2.b));
}

2)
1
2
3
4
complejo operator +(complejo a, complejo b)  { 
   complejo temp = {a.a+b.a, a.b+b.b}; 
   return temp; 
}
The glib answer as that they play the same role here as they play anywhere else.

In line 1, the '&' symbols denote that the arguments are being passed in as references, and the result is being returned as a reference.

In line 2, the * is de-referencing the pointer that points to the object dynamically allocated by new.

So, in your first example, the arguments to the operator are passed by reference. The result is dynamically allocated, and a reference to the dynamically allocated result is returned. This, incidentally, is not a good way to do it, as it leaves the calling code responsible for freeing up the memory. There's potential for a memory leak here.

In the second exampke, the arguments are passed by value, and the result is returned by value.
Last edited on
Topic archived. No new replies allowed.