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

前端 未结 5 790
终归单人心
终归单人心 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:21

    The instance object of class X is not const. It is merely referenced by an object which is const. Const-ness recursively applies to subobjects, not to referenced objects.

    By the alternative logic, a const method wouldn't be able to modify anything. That is called a "pure function," a concept which doesn't exist in current standard C++.

提交回复
热议问题