title: C++ - Run a function before initializing a class member
body: <p>I have 2 resource managing classes <code>DeviceContext</code> and <code>OpenGLContext</code> both are members of <code>class DisplayOpenGL</code>. The resource lifetimes are tied to <code>DisplayOpenGL</code>. Initialization looks like this (pseudo code):</p>
  
  <pre><code>DeviceContext m_device = DeviceContext(hwnd);
  m_device.SetPixelFormat();
  OpenGLContext m_opengl = OpenGLContext(m_device);
  </code></pre>
  
  <p>The problem is the call to SetPixelFormat(), since I can't do that in the initializer list of the <code>DisplayOpenGL</code> c'tor:</p>
  
  <pre><code>class DisplayOpenGL {
  public:
      DisplayOpenGL(HWND hwnd)
      : m_device(hwnd),
        // &lt;- Must call m_device.SetPixelFormat here -&gt;
        m_opengl(m_device) { };
  private:
      DeviceContext m_device;
      OpenGLContext m_opengl;
  };
  </code></pre>
  
  <p>Solutions that I can see:</p>
  
  <ul>
  <li>Inserting <code>m_dummy(m_device.SetPixelFormat())</code> - Won't work as SetPixelFormat() has no retval. (should you do this if it had a retval?)</li>
  <li>Use <code>unique_ptr&lt;OpenGLContext&gt; m_opengl;</code> instead of <code>OpenGLContext m_opengl;</code>.<br>
  Then initialize as <code>m_opengl()</code>, call SetPixelFormat() in the c'tor body and use <code>m_opengl.reset(new OpenGLContext);</code></li>
  <li>Call <code>SetPixelFormat()</code> from <code>DeviceContext</code> c'tor  </li>
  </ul>
  
  <p>Which of these solutions is preferable and why? Anything I am missing?</p>
  
  <p>I'm using Visual Studio 2010 Express on Windows, if it matters.</p>
  
  <p><strong>Edit:</strong> I'm mostly interested in the tradeoffs involved in deciding for one of these methods. </p>
  
  <ul>
  <li><code>m_dummy()</code> doesn't work and seems inelegant even if it would</li>
  <li><code>unique_ptr&lt;X&gt;</code> is interesting to me - when would I use it instead of a "normal" <code>X m_x</code> member? The two methods seem to be functionally more or less equivalent, except for the initialization issues.</li>
  <li>Calling <code>SetPixelFormat()</code> from <code>DeviceContext</code> c'tor certainly works but feels unclean to me. <code>DeviceContext</code> should manage the resource and enable its use, not impose some random pixel format policy on users.</li>
  <li><a href="https://stackoverflow.com/a/13311398/25097">stijn's</a> <code>InitDev()</code> looks like the cleanest solution.</li>
  </ul>
  
  <p>Do I pretty much always want a smart pointer based solution in such cases anyway?</p>