Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an object confusion

I've been learning C++ but I'm having trouble understanding the way objects are returned by a member function/method. I'm following the 'Teach yourself C++ in 21 days' book.

So, I understand classes and objects, just not much about returning an object. I'll provide an example (currently learning operator overloading).

const Counter& Counter::operator++()
{
    ++itsVal;
    return *this;
}

I'm just really confused about the return type. This method says it should return a reference to a counter object, but when the object is dereferenced with

return *this;

Aren't we just returning an object of the class Counter? Why does the function header say we're returning a reference to a counter object? Why doesn't the method header just say that the return type is an object of type Counter? This is where I get confused :\

The way I'm thinking about it is that since a reference is basically an alias to something, returning a dereferenced pointer would be like returning the objects alias as objects have names which help us identify them. I dont really know, I hope someone here can explain this to me.

like image 421
Pistax Avatar asked Jan 05 '23 10:01

Pistax


2 Answers

Aren't we just returning an object of the class Counter?

Yes, we're returning an object. But, it's returned by reference, or by value, is determined by the return type in function declaration, we can't determine (or distinguish) them in return statement.

const Counter& Counter::operator++() // return by reference (to const)
{
    ++itsVal;
    return *this;
}

Counter Counter::operator++()        // return by value. Note the body of function is the same.
{
    ++itsVal;
    return *this;
}

BTW: Returning by reference to const (and by value, the above sample is just used for illustration) for prefix operator++ doesn't make sense. It should return reference to non-const actually. Such as

Counter& Counter::operator++() // return by reference (to non-const)
{
    ++itsVal;
    return *this;
}
like image 141
songyuanyao Avatar answered Jan 14 '23 04:01

songyuanyao


The way I'm thinking about it is that since a reference is basically an alias to something, returning a dereferenced pointer would be like returning the objects alias

Yes, that is exactly right. The function returns an alias to the object the function was called on. It does not make a copy of that object to return.

The calling code might look like:

Counter c;
do_something( ++c + 5 );

Since ++c returned an alias to c, this code will behave like:

++c;
do_something( c + 5 );

without making any unnecessary copies of c.

like image 27
M.M Avatar answered Jan 14 '23 04:01

M.M