I guess you are talking about the case where you want objects of two
or more different classes to put their output on the same stream?
That's not possible I think.
Well .. I think you could use the low level utilities dealing with the
underlying streambuf to sync the filepointers manually:
std:
fstream file1("junk.tmp");
std:
fstream file2("junk.tmp");
file2.seekp(file1.tellp());
but you would have to do this everytime you accessed either stream.
Also, I guess you can't (or don't want to) access both ofstream
objects at the same time, because then wouldn't need two of them,
right?
Obvious answer would be to use two pointers to
the same fstream object. You could also use two smart pointers if you were
concerned about object lifetime issues.
I think this is a generally better solution, but it would IMO be even
better to do it with a reference, if that is possible:
#include <fstream>
using std:
fstream;
class A {
ofstream& output;
public:
A(ofstream& o) : output(o) {}
// ...
};
class B {
ofstream& output;
public:
B(ofstream& o) : output(o) {}
// ...
};
int main() {
ofstream foo("junk.tmp");
A a(foo);
B b(foo);
// code using a and b
return 0;
}
Objects a and b in the example about will both put their output in
junk.tmp. AFAICT, the only place where complications might arise is
on a multithreaded system, but I know only enough about that to say
that it *might* be a problem. Of course, woe betide you if foo is
destructed before a and b.
HTH, Dave Moore