why two const in one function

J

Jianli Shen

in a *.h file, there is a declaration:

const ClassName *functionName() const {return oneVar;}


I was confused by the two const there.
can anybody help explain why we need the first const.
why we need the second const here ?

Thanks
 
J

Jerry Coffin

Jianli said:
in a *.h file, there is a declaration:

const ClassName *functionName() const {return oneVar;}

Look at each part separately -- the "stuff" before the name of the
function is (mostly) the return type, while what comes after the name
refers to the function itself.

const ClassName *

That much is talking about the function's return value -- it returns a
pointer to a const ClassName.

function() const

That means the function itself is const -- i.e. that it's a member of a
class, and when it's invoked, 'this' points to a const X (X=whatever
its class type is).
 
S

Sumit Rajan

Jianli Shen said:
in a *.h file, there is a declaration:

const ClassName *functionName() const {return oneVar;}


I was confused by the two const there.
can anybody help explain why we need the first const.
why we need the second const here ?


The case of the first const:
Here, functionName is a function that returns a pointer to a const
ClassName. See:
http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.4 and
http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.5

The reason for the second const is also covered by the FAQ:
http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.10

Regards,
Sumit.
 

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
474,202
Messages
2,571,057
Members
47,662
Latest member
sxarexu

Latest Threads

Top