Skip to main content

Return const reference

Posted in

class Q
{
    public:
        Q() { x = 7;}
 
        int& getX() { return x; }
    private:
        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;
  4.  
  5.     cout << q.getX();
  6.     q.getX() = 2;
  7.     cout << q.getX();
  8.  
  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.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
tes__monial: