Bilal Sheikh
Bilal Sheikh

Reputation: 119

Why passing value-returning function works fine on operator function to overload = operator and not on others?

Look at this code:

class test
{
    int x;
 
 public:
    test ()
    {
        x = 3;
    }
};
test returnObj (test &obj)
{
    return obj;    
}

int main ()
{
    test object;
    returnObj (returnObj (object)); // line A
    return 0;
}

This code will give error at line A because we are passing return by value function as an actual parameter where it accepts only reference. So far so good. It makes sense.

Assume that we have overloaded = and + operator for class test. Now look at this:

test a, b;
test d = a + b; 

This code will create two object of type test, add them and assign the result to object d. But the prototype of operator function to overload + operator is :

test operator+ (const test&) const;

That means a + b will return the resultant object by value which is then to be passed to the operator function which overloads = operator, whose prototype is:

test& operator= (const test&);

Which clearly shows that it accepts only reference. So why does the compiler not give error here. (btw please tell what returning an object by value actually means)

Upvotes: 0

Views: 29

Answers (1)

john
john

Reputation: 87959

The difference is the word const. The rule in C++ is that you cannot bind a non-const reference to a temporary.

That's why the first example doesn't work. Return values from functions are one kind of temporary and the returnObj function parameter is a non-const reference. If you change test returnObj (test &obj) to test returnObj (const test &obj) it will compile.

But in the second example operator= takes a const reference, and that makes all the difference.

Returing an object by value just means a function whose return type is not a reference.

Upvotes: 1

Related Questions