title: Const method that modifies *this without const_cast
body: <p>The following pattern has arisen in a program I'm writing.  I hope it's not too contrived, but it manages to mutate a <code>Foo</code> object in the const method <code>Foo::Questionable() const</code>, without use of any const_cast or similar.  Basically, <code>Foo</code> stores a reference to <code>FooOwner</code> and vice versa, and in <code>Questionable()</code>, <code>Foo</code> manages to modify itself in a const method by calling <code>mutate_foo()</code> on its owner.  Questions follow the code.</p>
  
  <pre><code>#include "stdafx.h"
  #include &lt;iostream&gt;
  using namespace std;
  
  class FooOwner;
  
  class Foo {
      FooOwner&amp; owner;
      int data;
  
  public:
      Foo(FooOwner&amp; owner_, int data_)
          : owner(owner_),
            data(data_)
      {
      }
  
      void SetData(int data_)
      {
          data = data_;
      }
  
      int Questionable() const;       // defined after FooOwner
  };
  
  class FooOwner {
      Foo* pFoo;
  
  public:
      FooOwner()
          : pFoo(NULL)
      {}
  
      void own(Foo&amp; foo)
      {
          pFoo = &amp;foo;
      }
  
      void mutate_foo()
      {
          if (pFoo != NULL)
              pFoo-&gt;SetData(0);
      }
  };
  
  int Foo::Questionable() const
  {
      owner.mutate_foo();     // point of interest
      return data;
  }
  
  int main()
  {
      FooOwner foo_owner;
      Foo foo(foo_owner, 0);      // foo keeps reference to foo_owner
      foo_owner.own(foo);         // foo_owner keeps pointer to foo
  
      cout &lt;&lt; foo.Questionable() &lt;&lt; endl;  // correct?
  
      return 0;
  }
  </code></pre>
  
  <p>Is this defined behavior?  Should <code>Foo::data</code> be declared mutable?  Or is this a sign I'm doing things fatally wrong?  I'm trying to implement a kind of lazy-initialised 'data' which is only set when requested, and the following code compiles fine with no warnings, so I'm a little nervous I'm in UB land.</p>
  
  <p>Edit: the <code>const</code> on Questionable() only makes immediate members const, and not the objects pointed to or referenced by the object.  Does this make the code legal?  I'm confused between the fact that in <code>Questionable()</code>, <code>this</code> has the type <code>const Foo*</code>, and further down the call stack, <code>FooOwner</code> legitimately has a non-const pointer it uses to modify <code>Foo</code>.  Does this mean the <code>Foo</code> object can be modified or not?</p>
  
  <p>Edit 2: perhaps an even simpler example:</p>
  
  <pre><code>class X {
      X* nonconst_this;   // Only turns in to X* const in a const method!
      int data;
  
  public:
      X()
          : nonconst_this(this),
            data(0)
      {
      }
  
      int GetData() const
      {
          nonconst_this-&gt;data = 5;    // legal??
          return data;
      }
  };
  </code></pre>