What's the difference between a const member function and a non-const member function?

后端 未结 5 1932
清歌不尽
清歌不尽 2020-11-29 11:17

I am very confused about the const version and non-const version member function like below:

value_type& top() { return this.item }
const value_type&         


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 12:03

    If you have

    class Foo
    {
        value_type& top() { return this.item }
        const value_type& top() const { return this.item }
    }
    

    If you have

    Foo foo;
    const Foo cfoo;
    

    The return types when you call top() are as follows:

    value_type& bar = foo.top();
    const value_type& cbar = cfoo.top();
    

    In other words - if you have a constant instance of your class, the const version of the function is chosen as the overload to call.

    The reason for this (in this particular case) is so that you can give out references to members (like item in this case) from a const instance of a class, and ensure that they too are const - thus unmodifiable and therefore preserving the const-ness of the instance they came from.

提交回复
热议问题