Skip to main content

Return const reference

Posted in

class Q
        Q() { x = 7;}
        int& getX() { return x; }
        int x;

Looks ok. Compiles well. But... Here is what we can do with such class Q:

  1. int main(int argc, char *argv[])
  2. {
  3.     Q q;
  5.     cout << q.getX();
  6.     q.getX() = 2;
  7.     cout << q.getX();
  9.     return 0;
  10. }

How can we solve this? You might want to make getX a const function which "promises" not to changed x.

int& getX() const { return x; }

But if you choose this solution then you have to make getX return a const reference. So it should be

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

(You are not obliged getX to be const function)

Post new comment

The content of this field is kept private and will not be shown publicly.
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
 o.OOOo.     .oOOOo.   o        OooOoo  OoooOOoO  O       o 
O `o .O o O O o o O
o O o o o O O o
O o o o O o o o
o O o O o o O o O
O o O OoO O o O O
o .O' `o .o o O O o O `o Oo
OooOO' `OoooO' O o `OooOO' OOooOooO `OoooO'O

Enter the code depicted in ASCII art style.