Proper way to create ostream to file or cout
<p>I am trying to create a Log class for my project at school.  It needs to either be able to write information to the stdout or to a file depending on the parameters it is passed.  I was looking into how to do this and I stumbled upon a thread with a similar question here: <a href="http://stackoverflow.com/questions/366955/obtain-a-stdostream-either-from-stdcout-or-stdofstreamfile">Obtain a std::ostream either from std::cout or std::ofstream(file)</a></p>

<p>The only difference between this thread and my own is that I want to do it inside of a class.  Looking at the solution though they use <code>std::ostream out(buf)</code> and construct the ostream on the fly with buf.  How can i declare this properly in my Log class to be able to construct the "out" object only once i enter my Log constructor?</p>

<p>I took a quick stab at it below but I am not sure if it is correct or if I am on the right track. Appreciate any help, thanks.</p>

<p>EDIT: I want to be able to do <code>out &lt;&lt; "Some string" &lt;&lt; endl;</code> after i get this Log class working properly.</p>

<p>EDIT2: An error I am now receiving with the new code below <code>error : 'std::basic_ostream&lt;_CharT, _Traits&gt;::basic_ostream() [with _CharT = char, _Traits = std::char_traits&lt;char&gt;]' is protected</code></p>

<pre><code>// log.h
#include &lt;string&gt;
#include &lt;fstream&gt;

#ifndef LOG_H_
#define LOG_H_

class Log 
{
    public:
        enum Mode { STDOUT, FILE };

        // Needed by default
        Log(const char *file = NULL);
        ~Log();

        // Writing methods
        void write(char *);
        void write(std::string);
    private:
        Mode mode;
        std::streambuf *buf;
        std::ofstream of;
        std::ostream out;
};

#endif


// log.cpp
#include "log.h"
#include &lt;iostream&gt;
#include &lt;stdlib.h&gt;
#include &lt;time.h&gt;

Log::Log(const char *file)
{
    if (file != NULL)
    {
        of.open(file);
        buf = of.rdbuf();
        mode = FILE;
    }
    else
    {
        buf = std::cout.rdbuf();
        mode = STDOUT;
    }

    // Attach to out
    out.rdbuf(buf);
}

Log::~Log()
{
    if (mode == FILE)
        of.close();
}

void Log::write(std::string s)
{
    out &lt;&lt; s &lt;&lt; std::endl;
}

void Log::write(char *s)
{
    out &lt;&lt; s &lt;&lt; std::endl;
}
</code></pre>
