0

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.

Vasile Turcu
  • 153
  • 11

2 Answers2

4

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.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • 3
    int f() const{ return x;} also ok –  Aug 30 '16 at 15:44
  • 2
    @KenmanTsang yes in _this_ case it is ok and, in fact, it's probably advisable (copying an `int` is easy). But returning a copy isn't always a good idea or even possible. – Nik Bougalis Aug 30 '16 at 15:46
1

You can't return a non const reference to a const. The const member function makes the variable x non const when it accesses it.

There seems no need to return a reference, and in fact it is a bad practice. If you need to change your internal int it makes more sense to add a setter:

class cls
{
    int x;
public: 
    cls(int i=3) { set(i); }
    void set (const int val) { x=val; }
    int f() const{ return x; }
};
Glenn Teitelbaum
  • 10,108
  • 3
  • 36
  • 80