ofstream as a data member

okay so I have a class & I want all it's member functions to be able to access an ofstream object... i.e

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class myclass
{
 public:
    myclass(string filename)
    {
        openfile(string filename)
    }
    void openfile(string filename)
    {
        m_file(filename);
    }
    void writetofile()
    {
        m_file << "lalalal" << endl;
    }
private:
    ofstream m_file;
};

this is just meant to show an example not the real code...
i've tried a few things and it's not working so help would be appreciated, thx
the openFile function looks like it is trying to call the constructor on the stream but it is already constructed. You need to call the open member function on the stream object at this point. You'll need to have some basic checking in some of these functions to check if it needs to be opened. You'll also want to close the file in the destructor. Also, the other member functions can access the object directly so you don't need to wrap every filestream operation with an additional member function unless you want users of myclass to call them.
kempo i just typed this up in the post real quick it isn't my actual program i just wanna give an idea of what i'm trying to do... i just want the ofstream object to be accesible throughout my class
Okay well like I said, line 10 is an invalid call. You have to call the open member function.
m_file.open(fileName); // specify the second argument if you want to specify modes
thanks kempo... i was trying to open file like when u init the ofstream object
i.e. ofstream file("..")
thanks=)
Topic archived. No new replies allowed.