Search code examples
c++coutofstreamostreamampersand

How to pass ostream objects?


i have a struct like this

struct X{
    ostream out;
    X() : out(cout) {}
    ...
};

and I noticed that I have to define out with the & to correctly pass cout as default parameter: ostream &out; I don't know why and I don't know if there are other possibilities keeping ostream without the &. Furthermore, when I try to set

X x;
ofstream out;
x.out = out;

the compiler found many errors... I want to be able to set X::out to cout or to an ofstream. How to do it?


Solution

  • ostreams cannot be passed by value. You have to pass by reference or pointer.

    If you want the ability to make x.out refer to different streams during its lifetime, then make it a pointer. Otherwise make it a reference.