title: C++ - Function calling when changing member value
body: <p>My goal is to fire a event receiver when a value is changed in a class. My solution to this is using get and set functions. However, I do not want any performance problems when reading the values. In the class below:</p>
  
  <pre><code>class Vertex {
   public:
    const double&amp; GetX() { return _x; } // should inline automatically
    const double&amp; GetY() { return _y; } // ' '                     ' '
    void SetX(const double&amp; x); // complex stuff in source file
    void SetY(const double&amp; y); // ' '                      ' '
   private:
    double _x, _y;
  }
  </code></pre>
  
  <p>I put the definition of the getters in the header files, because this should allow them to be inlined.</p>
  
  <p>My question is: is there any way to automatically call a function when a value is changed that does not require me to include function definitions in the header file? Or is there perhaps a visibility level that allows anyone to read the data, but only the class itself to modify it? Or maybe something else?</p>
  
  <p>I know an alternative approach would be manually calling an update function, but that looks ugly:</p>
  
  <pre><code>vertex.X = 5;
  vertex.Update();
  </code></pre>
  
  <p>Thank you in advance.</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>So far I've heard some great answers. The solution depends on your goal:</p>
  
  <ul>
  <li>Easy: getters and setters; not very clean though.</li>
  <li>Clean: property class (or proxy); implementing operators is not as easy though.</li>
  </ul>
  
  <p>However, what about efficiency?</p>
  
  <p>I just worked out a nice trick for the separate read/write-access permissions I speculated about earlier:</p>
  
  <pre><code>class Vertex {
   public:
    Vertex(double x, double y)
        : _x(x), _y(y), X(_x), Y(_y) { } // defined here for readability
    void SetX(double x) { _x = x; update(); } // defined here for readability
    void SetY(double y) { _y = y; update(); } // update would be the callback
    const double&amp; X, Y;
   private:
    double _x, _y;
  }
  </code></pre>