1

We were given a semantically and syntactically correct method that looks like this:

const Foo & bar( const Bim & bam ) const; 

We are supposed to explain what is meant by each of the three const calls. I am new to C++ and don't know what they mean. I understand (roughly) that the const at the end means that the method can only be called upon const variables and promises not to propagate changes. However, I do not understand the other two. Please correct me if I was wrong on the last one.

4
  • I believe that bam is a constant call by reference of type Bim. Commented Feb 12, 2013 at 5:57
  • Worth reading: parashift.com/c++-faq/const-correctness.html Commented Feb 12, 2013 at 5:58
  • 2
    Indicating that your problem is solved is done by clicking on the check mark next to the best answer, not by changing the post title. Commented Feb 12, 2013 at 6:09
  • Somebody else deleted the word "SOLVED" from the title. I changed "constants" to "const", since "const" and "constant" actually mean two quite different things in C++ (roughly, "const" means "read-only", and "constant" means "able to be evaluated at compile time"). Commented Feb 12, 2013 at 6:12

3 Answers 3

5

See below for explanation

(1)const Foo & bar( (2)const Bim & bam ) (3)const; 
  1. The method is returning a reference of type Foo that is immutable.
  2. The methods parameter of type Bim will not be modified by the method. This means that you can pass into this method objects that are const and non-const. Either way the method will not modified the object or is only able to call methods on that object that are const.
  3. This means that this method does not alter the object in any way.

PS: For 3 there is ways around this if you are a naughty boy

Sign up to request clarification or add additional context in comments.

1 Comment

Ah! Awesome. Thanks a ton. That makes sense when combined with David Saxon's answer. Great help!
0

I understand (roughly) that the const at the end means that the method can only be called upon const variables and promises not to propagate changes.

Half right. The function can be called on const or non-const objects, and promises not to modify the state(non-mutable members) of the object or to call any non-const member functions. It's okay to call on non-const objects, but the reverse is not true. That is to say, if the trailing const was not there, then it could not be called on const objects.

Comments

0

-> For int func1 () const; When you specify constant at a end of function this means this function is read only, you can't modify object for which this function is called. -> For func (const bim); constant in the argument of the function as you understood will not allow to change that particular object. -> And for const func2(); means this function's return type is constant.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.