Vasile Turcu Vasile Turcu - 3 months ago 8
C++ Question

C++ const function error

I am quite new to oop in c++ and I came across the following piece of code while surfing the net:

#include<iostream>
using namespace std;

class cls
{int x;
public:
cls(int i=3) {x=i;}

int &f() const{ return x;}
};
int main()
{
const cls a(-3);
int b=a.f();
cout<<b;
return 0;
}


And when I try to run the code, it crashes due to the f function. Now I am not quite sure what is going on there and why it crashes, so I would need someone to enlighten me a little bit on the subject.

Answer

As your function is declared as const you can't return a non const reference to a member variable unless you mark it as mutable.

To fix your code write either

class cls
{ 
    mutable int x;
 // ^^^^^^^
public: 
    cls(int i=3) {x=i;}

    int &f() const{ return x;}
};

or return a const reference.

class cls
{ 
    int x;
public: 
    cls(int i=3) {x=i;}

    const int &f() const{ return x;}
 // ^^^^^
};

Using mutable needs to be taken with a grain of salt, it would break up the encapsulation of your class, and allow your class internals to be changed via the reference you handed out.