Simple inheritance question

Hello all!

I would like to ask for your opinion on possible solutions for my problem :)
I have a class like this:

1
2
3
4
5
6
7
  class Writer
  {
  public:
    Writer(std::ostream & o);
  private:
    std::ostream & o_;
  };


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?

Thanks for any suggestions! :)
Make the std::fstream object a member of the class and pass it to the Writer constructor like you do with cout.
@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.
Last edited on
One solution I thought about is to change Writer class to look like:

1
2
3
4
5
6
7
  class Writer
  {
  public:
    Writer(std::ostream * o);
  private:
    std::ostream * o_;
  };


Then I can make FileWriter like this:

1
2
3
4
5
class FileWriter : public Writer
{
public:
  FileWriter() : Writer(new std::ofstream()) {}
};


But then of course the object would have to be deleted in destructor, but I cannot do that for std::cout...

LB is of course right, but if the Writer constructor promise not to do anything with the stream object inside the constructor it should be safe.

Otherwise I found a workaround that you could use: https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Base-from-Member
Last edited on
@Beju: prefer to use smart pointers, e.g. std::unique_ptr and std::make_unique

@Peter87: that's clever, I wouldn't have thought to do that.
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.
Last edited on
Thank you all for the suggestions! :) The "Base from Member" solution looks interesting, I will try it out!

@LB: how would you use smart pointer in this case?
Topic archived. No new replies allowed.