The problem here is that you're storing the ofstream
value rather than reference. You can make your code work by changing ANTPred
(and similarly changing ATPred) as follows:
class ANTPred {
private:
std::ofstream &outputFile;
public:
ANTPred(std::ofstream &file) : outputFile(file) {
// other construction work
}
};
While I say this will make your code work, it is not necessarily safe. Storing a reference to the ofstream
object implicitly assumes that it will outlive all ATPred
and ANTPred
instances. If the ostream is destroyed first, then the behavior of ATPred
and ANTPred
instances will be undefined and likely lead to segfaults.
A non-exhaustive list of other options include using raw pointers (leads to same lifetime issues pointed out above), shared pointers (either c++11 std::shared_ptr
, boost::shared_ptr
or some other shared pointer library), constructing a separate output stream for each object, or passing the output stream to the object instances when they are required to log data.