Modifying reference member from const member function in C++

后端 未结 3 1107
走了就别回头了
走了就别回头了 2020-12-06 03:57

I am working on const-correctness of my code and just wondered why this code compiles:

class X
{
    int x;
    int& y;
public:
    X(int& _y):y(_y)
         


        
3条回答
  •  自闭症患者
    2020-12-06 04:53

    As additional information for the accepted answer, I want to say, in fact one can change variables in X.

    Because you are not changing any variable in X.

    #include 
    #include 
    #include 
    using namespace std;
    
    class Bar {
    public:
        void funcA() const {
            c++;
        }
    
        int b = 3;
        int &c = b;
    };
    
    int main()
    {
        Bar b;
        b.funcA();
        cout << b.b << endl;  //4
    }
    

    So the main idea for this problem is:

    It modifies what the member refers to, it does not modify the member.

    This also applies for pointer members.

    See here Why can reference members be modified by const member functions?

提交回复
热议问题