Search code examples
c++operator-overloadingofstream

Overloading << to output into a file


So I have:

in my .h:

friend std::ofstream & operator <<(std::ofstream & output, myClass & s);

and in my .cpp

 std::ofstream & operator <<(std::ofstream & output, myClass & s)
{
    ofstream ofile << ("output.txt");
    output << "Test" << endl;
    return output;
}

I get errors:

expected initializer before '<<' token

at `std::ofstream & operator <<(std::ofstream & output, myClass & s)

and

no match for 'operator<<' (operand types are 'std::ofstream {aka std::basic_ofstream}' and 'const char [5]')

at ofstream ofile << ("output.txt");

Whats the poblem?`

`


Solution

  • It is usually a bad idea to restrict a function to std::ofstream when it may as well work with any kind of std::ostream. It also looks highly suspicious when you pass a non-const reference to a print function. This means that you officially allow printing to have side effects which modify the printed object!

    For those reasons, you should change this:

    std::ofstream & operator <<(std::ofstream & output, myClass & s);
    

    To this:

    std::ostream & operator <<(std::ostream & output, myClass const& s);
    

    You don't need to create a stream instance in the implementation of the operator, either. You receive a reference to one as the first argument. So just do this (and while we're at it, avoid endl unless you know exactly what you are doing):

    std::ostream & operator <<(std::ostream & output, myClass const& s);
    {
        output << "Test\n";
        // output << s.some_member << "\n";
        return output;
    }
    

    You can now just pass an std::ofstream object to that function and will write into the file. You just need to create the object, passing the filename to its constructor:

    myClass s;
    std::ofstream os("output.txt");
    os << s;