Should I return const objects?

Top level cv-qualifiers on return types of non class type are ignored.
Which means that even if you write:

int const foo();

The return type is int. If the return type is a reference, of course,
the const is no longer top level, and the distinction between:

int& operator[]( int index );

and

int const& operator[]( int index ) const;

is significant. (Note too that in function declarations, like the above,
any top level cv-qualifiers are also ignored.)

The distinction is also relevant for return values of class type: if you
return T const, then the caller cannot call non-const functions on the
returned value, e.g.:

class Test
{
public:
    void f();
    void g() const;
};

Test ff();
Test const gg();

ff().f();             //  legal
ff().g();             //  legal
gg().f();             //  **illegal**
gg().g();             //  legal

Leave a Comment