Pistax Pistax - 2 months ago 5
C++ Question

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.

Answer

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;
}
Comments