39

Is there a way to pass output stream as argument like

void foo (std::ofstream dumFile) {}

I tried that but it gave

error : class "std::basic_ofstream<char, std::char_traits<char>>" has no suitable copy constructor

Shibli
  • 5,879
  • 13
  • 62
  • 126

3 Answers3

53

Of course there is. Just use reference. Like that:

void foo (std::ofstream& dumFile) {}

Otherwise the copy constructor will be invoked, but there is no such defined for the class ofstream.

Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135
  • 2
    Just a note: once constructed it typically doesn't matter what kind of stream you got and it tends to be preferable to use `std::ostream&` (note the absense of `f`). – Dietmar Kühl Mar 11 '12 at 21:39
  • Or even more generic: `template … std::basic_ostream&` – Philipp Mar 11 '12 at 22:09
  • If I do `void foo (const std::ofstream& dumFile)` what does it do, does it write to `dumFile` and cannot change it's address, or it cannot write into it? – thedarkside ofthemoon Mar 05 '14 at 13:50
14

You have to pass a reference to the ostream object as it has no copy constructor:

void foo (std::ostream& dumFile) {}
strpeter
  • 2,562
  • 3
  • 27
  • 48
Joel Falcou
  • 6,247
  • 1
  • 17
  • 34
10

If you are using a C++11 conformant compiler and standard library, it should be ok to use

void foo(std::ofstream dumFile) {}

as long as it is called with an rvalue. (Such calls will look like foo(std::ofstream("dummy.txt")), or foo(std::move(someFileStream))).

Otherwise, change the parameter to be passed by reference, and avoid the need to copy/move the argument:

void foo(std::ofstream& dumFile) {}
Mankarse
  • 39,818
  • 11
  • 97
  • 141
  • 2
    Given that `std::ofstream` has a move constructor, it works to pass a temporary object to a function declared as `void foo(std::ofstream)` using e.g. `foo(std::ofstream("file"))`. Note that gcc's standard library hasn't implemented this constructor, yet, while clang's standard library has (i.e. the above code compiles with clang but not with gcc; gcc is wrong). – Dietmar Kühl Mar 11 '12 at 21:56