Hi,

This is my first post in daniweb!

I've two questions:

First question:
I'm currently studying about classes, and could get '=' overloading format:

​T& T::operator =(const T& b);​

Why we set it to return reference? what's the use?

Why couldn't simply be:

​void T::operator =(const T& b);​

I've used it and worked fine. So why they keep return a reference in almost every example I've seen about '=' overloading, even in Wikipedia!

---

Second question is: What's the point of returning a reference in functions? What's the use?

---


Thank you in advance!

Member Avatar for embooglement

You can chain together assignments, like "a = b = c;", in which case c would get assigned to b, and then b would get assigned to a, leaving a and b equal to c at the end. If an overloaded = didn't return anything, it couldn't be chained together like this.

So far as the reason for returning by reference, that means that the variable you're getting is an l-value. Basically, that means it's a non-temporary variable, you can take it's address, change it's value, etc. So if you had something like this,

class SomeClass
{
private:
   int someNum;
public:
   int& GetNum() { return someNum; }
};

You could do "someInstance.GetNum() = 5;" and that would set someInstance.someNum to 5. If it returned by value (i.e. "int GetNum() ..."), you couldn't set the value, because the thing returned by the function would be a temporary variable, and therefore it gets destroyed at the end of the line, and the semicolon.

Thank you! Your explanation is so clear, especially:

you couldn't set the value, because the thing returned by the function would be a temporary variable, and therefore it gets destroyed at the end of the line, and the semicolon

Thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.