I would like to create child classes like StdoutWriter, FileWriter, etc. by simply inheriting from the writer class and initializing the std::ostream object according to what the class should do:
1 2 3 4 5
class StdoutWriter : public Writer
{
public:
StdoutWriter() : Writer(std::cout) {}
};
As you can imagine, this is fairly easy with std::cout, but gets more complicated when I need a std::fstream object. How could I solve this?
@Peter87: I don't think that's a safe thing to do, because the constructor will run before the stream gets constructed, meaning it could be used in an unconstructed state.
I actually have run into this issue myself, and I think it's just a hole in the C++ language. You can't pass a member of a derived class to a parent class constructor.
Create a structure holding member you need to intialize befor base class, then inherit privately from it, placing it before public inheritance. Base classes are initializated in order of declaration, so that "member" would be initialized before Writer class. Edit: Peter87 link is exact same solution.