2

I have a class that I want to give an output stream as a member to, to wit:

class GameBase {
protected:
    ofstream m_OutputWriter;
...
}

There is a method in this class that takes a string argument and opens m_OutputWriter to point to that file, so data may be output to that file by using the standard << operator;

However, what I would like is to make the stream point to cout by default, so that if the output path is not specified, output goes to the console output instead of to a file, and it will be completely transparent by the calling class, who would use

m_OutputWriter << data << endl;

to output the data to the predetermined destination. Yet, I have tried a couple of the other examples here, and none of them exactly seem to fit what I'm trying to do.

What am I missing here?

Charles
  • 577
  • 2
  • 7
  • 16
  • possible duplicate of [Obtain a std::ostream either from std::cout or std::ofstream(file)](http://stackoverflow.com/questions/366955/obtain-a-stdostream-either-from-stdcout-or-stdofstreamfile) – GWW Aug 20 '11 at 01:48

2 Answers2

3

Why does the stream need to be a member?

struct GameBase {
    void out(std::ostream& out = std::cout);
    // ...
};
wilhelmtell
  • 57,473
  • 20
  • 96
  • 131
2

In addition to having an std::ofstream as a member, I would use a function that returns an std::ostream&.

For example:

class GameBase {
    std::ofstream m_OutputWriter;
protected:
    std::ostream& getOutputWriter() {
         if (m_OutputWriter)
             return m_OutputWriter;
         else
             return std::cout;
    }
    ...
}

A fully-functioning example:

#include <iostream>
#include <ostream>

std::ostream& get() {
    return std::cout;
}

int main() {
    get() << "Hello world!\n";
}
Cactus Golov
  • 3,474
  • 1
  • 21
  • 41
  • And how do I use a pointer to an output stream with the "<<" operator? GetOutputWriter() << "Hello, World\n"; does not compile when I try it. – Charles Aug 20 '11 at 02:05
  • @Charles - And none the less, that is the correct syntax; see the example I've attached. You'll have to provide mre information on why it might not compile (Perhaps because it is not `const`? You can hardly avoid that, unless you mark `m_OutputWriter` as `mutable`.). – Cactus Golov Aug 20 '11 at 02:09
  • Okay, I found the problem, I was trying something foolish because m_OutputWriter had a non-null value. I changed the test to "if (m_OutputWriter.is_open())" and it works just fine now. The empty parentheses drive me nuts because I do so love my properties in C#, but I guess it beats not having it work. Thanks for your help! – Charles Aug 20 '11 at 02:19