Use of 'const' in C++ functions

  • Context: C/C++ 
  • Thread starter Thread starter JesseC
  • Start date Start date
  • Tags Tags
    C++ Functions
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
2 replies · 2K views
JesseC
Messages
247
Reaction score
2
The use of 'const' in functions seems to be an endless source of confusion. Am I right in thinking that in this case:

double functionName(class const & parameter) {...}

the const specifies that the reference to the class being fed into the function may not be modified?

And that in this case (where the function is a member function of a class):

double functionName(class const & parameter) const {...}

the two const's specify that the reference to the class being fed in may not be modified AND that any member data may also not be modified?
 
Physics news on Phys.org
JesseC said:
Am I right in thinking that in this case:

double functionName(class const & parameter) {...}

the const specifies that the reference to the class being fed into the function may not be modified?

No, it means that the class (object) may not be modified via that reference. You cannot substitute another object for it via an assignment statement, nor can you pass it to another function via a non-const parameter, nor can you invoke a member function which is not 'const'.

And that in this case (where the function is a member function of a class):

double functionName(class const & parameter) const {...}

the two const's specify that the reference to the class being fed in may not be modified AND that any member data may also not be modified?

The first 'const' has the same meaning as above. The second 'const' indicates that this member function will not modify the member data of the object that the member function is "attached" to. If you try to write the member function so that it does modify any member data, the compiler will give you an error message.

Here's a good guide to "const correctness":

http://www.parashift.com/c++-faq-lite/const-correctness.html
 
Last edited by a moderator: