Search code examples
c++objectvariablesofstream

ofstream object as variable


I am trying to create multiple files according to a filename in cpp. Using ofstream for that, I could not achieve it for now.

I'd appreciate if anyone can help me with that.

I am writing down here:

static std::ofstream text1;
static std::ofstream text2;

class trial{
public:
  if(situation == true) {
    document_type = text1;
  }
  if(situation == false) {
    document_type = text2;
  }

  document_type << "hello world" << "\n";
}

ofstream object as variable.


Solution

  • Assignment copies the objects, and it's not possible to create copies of streams. You can only have reference to streams, and you can't reassign references.

    Instead I suggest you pass a reference to the wanted stream to the trial constructor instead, and store the reference in the object:

    struct trial
    {
        trial(std::ostream& output)
            : output_{ output }
        {
        }
    
        void function()
        {
            output_ << "Hello!\n";
        }
    
        std::ostream& output_;
    };
    
    int main()
    {
        bool condition = ...;  // TODO: Actual condition
    
        trial trial_object(condition ? text1 : text2);
        trial_object.function();
    }
    

    Also note that I use plain std::ostream in the class, which allows you to use any output stream, not only files.