title: C++: initialize reference to ofstream in initialization list
body: <p>I have read multiple questions and answers on that topic, but unfortunately none of them helped yet. I want to use the same debug file ouput in two classes A and B, where an instance of A creates an instance of B. I have something like:</p>
  
  <pre><code>class A {
  public:
      A() : debug("debug.txt") { };
  private:
      std::ofstream debug;
  }
  
  class B {
  public:
      B(std::ofstream &amp;ofs) : debug(ofs) { };
  private:
      std::ofstream &amp;debug;
  }
  </code></pre>
  
  <p>and create an instance of it with</p>
  
  <pre><code>B *b = new B(debugUnderlying);
  </code></pre>
  
  <p>which works quite well. However, I now want to have an additional constructor to be able to use it without an ofstream. The object shall then open a new file. I got the point that, as I have a reference, I need to initialize it in the initialization list. I tried multiple things:</p>
  
  <pre><code>B() : debug() { debug.open("debug2.txt"); };
  
  error: invalid initialization of non-const reference of type ‘std::ofstream&amp; {aka std::basic_ofstream&lt;char&gt;&amp;}’ from an rvalue of type ‘const char*’
  </code></pre>
  
  <p>or</p>
  
  <pre><code>B() : debug("debug2.txt") { };
  
  error: value-initialization of reference type ‘std::ofstream&amp; {aka std::basic_ofstream&lt;char&gt;&amp;}’
  </code></pre>
  
  <p>or (quite clear, since I have a temporary object)</p>
  
  <pre><code>error: invalid initialization of non-const reference of type ‘std::ofstream&amp; {aka std::basic_ofstream&lt;char&gt;&amp;}’ from an rvalue of type ‘std::ofstream {aka std::basic_ofstream&lt;char&gt;}’
  </code></pre>
  
  <p>How can I do this? Thanks for any suggestions!</p>