简体   繁体   中英

Understanding const in C++

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.

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

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.

-> 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM