phoganuci
phoganuci

Reputation: 5064

Passing ofstream object from main program to a class

Here is what I am trying to do:
1) Open an ofstream object in my main body. I can do this no problem.
2) Associate this object with a filename. No problem.
3) Pass this object to a class and send output within this class. I can't do this.
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;
}

Upvotes: 4

Views: 10487

Answers (2)

anon
anon

Reputation:

It is worth mentioning, that in c++0x you will have another options (besides passing by reference or by pointer):

  1. std::move. Streams are not copyable, but you will be able to move them into another place (it depends if streams will implement the move operator, but they probably will).
  2. unique_ptr. Streams are not copyable. When using pointers, a risk of resource leak arises. Using shared_ptr incorporates unnecessary costs when you want to have streams stored in a collection, and nowhere else. Unique_ptr solves this. You will be able to store streams in a collection in safe and efficient way.

Upvotes: 2

anon
anon

Reputation:

You must pass stream objects by reference:

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

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

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

Upvotes: 9

Related Questions