Passing an object from the main program to the class

Here is what I am trying to do:
1) Open the outstream object in my main body. I can do it without a problem.
2) Associate this object with the file name. No problems.
3) Pass this object to the class and send the output in this class. I can not do it. Here is my code. I would appreciate any help. Thanks!

#include <fstream> #include <iostream> using namespace std; typedef class Object { public: Object(ofstream filein); } Object; Object::Object(ofstream filein) { filein << "Success"; } int main (int argc, char * const argv[]) { ofstream outfile; outfile.open("../../out.txt"); Object o(outfile); outfile.close(); return 0; } 
+4
source share
2 answers

You must pass the stream objects by reference:

 Object::Object( ofstream & filein ) { filein << "Success"; } 

And why are you using typedef for the class? It should look like this:

 class Object { public: Object(ofstream & filein); }; 
+9
source

It is worth noting that in C ++ 0x you will have other parameters (in addition to passing by reference or by pointer):

  • stand :: move. Streams are not copied, but you can move them to another place (this depends on whether the streams will implement the move operator, but they will probably be).
  • unique_ptr. Streams are not copied. Using pointers runs the risk of leaking resources. Using shared_ptr involves unnecessary overhead when you want to have streams stored in a collection and nowhere else. Unique_ptr solves this. You can safely and efficiently save streams to collections.
+2
source

All Articles