the use of returning const &

M

maadhuu

what is the use of returning "const & "from a function in C++ ?? Is it used
somewhere at all ??

thank you,
Ranjan.
 
A

Alf P. Steinbach

* maadhuu:
what is the use of returning "const & "from a function in C++ ??

What's with the double question mark?

Anyway, re the question, a reference means this is an object that exists
somewhere (not a copy), and const prevents the client code from calling
non-const member functions or directly modifying data members.

Both are guarantees: the existence guarantee is a guarantee the function gives
the client code, so that no checking of existence is needed, and the constness
is a guarantee the function gives about the object.

Is it used somewhere at all ??

Yes. A simple example is a singleton function returning a reference to a
static object. A perhaps less simple, but more often occurring, example, is
the 'at' or operator[] member function of a container such as std::vector.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,800
Messages
2,569,657
Members
45,417
Latest member
BonitaNile
Top