Why can I call a non-const member function pointer from a const method?

前端 未结 5 791
终归单人心
终归单人心 2020-12-11 05:42

A co-worker asked about some code like this that originally had templates in it.

I have removed the templates, but the core question remains: why does this compile O

5条回答
  •  星月不相逢
    2020-12-11 06:42

    In this context object is a reference to a X, not a reference to a const X. The const qualifier would be applied to the member (i.e. the reference, but references can't be const), not to the referenced object.

    If you change your class definition to not using a reference:

    // ...
    private:
        X object;
    // ...
    

    you get the error you are expecting.

提交回复
热议问题