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

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

    The constness of execute() only affects the this pointer of the class. It makes the type of this a const T* instead of just T*. This is not a 'deep' const though - it only means the members themselves cannot be changed, but anything they point to or reference still can. Your object member already cannot be changed, because references cannot be re-seated to point to anything else. Similarly, you're not changing the F member, just dereferencing it as a member function pointer. So this is all allowed, and OK.

    The fact that you make your instance of CX const doesn't change anything: again, that refers to the immediate members not being allowed to be modified, but again anything they point to still can. You can still call const member functions on const objects so no change there.

    To illustrate:

    class MyClass
    {
    public:
        /* ... */
    
        int* p;
    
        void f() const
        {
            // member p becomes: int* const p
            *p = 5;   // not changing p itself, only the thing it points to - allowed
            p = NULL; // changing content of p in const function - not allowed
        }
    };
    
    0 讨论(0)
  • 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++.

    0 讨论(0)
  • 2020-12-11 06:38

    You are calling foo on object, not on this.

    Since object is declared as an X&, in a constant CX, it is actually an X& const (which is not the same as const X&) allowing you to call non const methods on it.

    0 讨论(0)
  • 2020-12-11 06:39

    One helpful way of thinking about it might be that your X object is not a member of CX at all.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题