Masao Liu
Masao Liu

Reputation: 769

Initializing ofstream in class

I don't want to construct ofstream in main(). Here is what I do but it does not compile:

#include <fstream>
using namespace std;
class test
{
private:
    ofstream &ofs;
public:
    test(string FileName);
    void save(const string &s);
};
//----------------
test::test(string FileName)
    : ofs(ofstream(FileName.c_str(),ios::out))
{
}
//----------------
void test::save(const string &s)
{
    ofs << s;
}
//----------------
//Provide file name and to-be-written string as arguments.
int main(int argc,char **argv)
{
    test *t=new test(argv[0]);
    t->save(argv[1]);
    delete t;
}

test.cpp: In constructor ‘test::test(std::string)’:
test.cpp:13: error: invalid initialization of non-const reference of type ‘std::ofstream&’ from a temporary of type ‘std::ofstream’

How to fix the code?

Upvotes: 1

Views: 12328

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361802

The expression ofstream(FileName.c_str(),ios::out)) creates a temporary object which cannot be bound to non-const reference.

Why dont you do this instead (read the comments as well):

class test 
{
    private:
        ofstream ofs; //remove & ; i.e delare it as an object
    public:
        test(string const & FileName); // its better you make it const reference
        void save(const string &s);
};

test::test(string const & FileName)  // modify the parameter here as well
    : ofs(FileName.c_str(),ios::out) // construct the object
{

}

Hope that helps.

Upvotes: 6

Kemin Zhou
Kemin Zhou

Reputation: 6901

Only in special situations you use a reference to another object as a class data member. Usually you want a lifetime dependency of your class on the member object. Usually, your class will be limited in copying and assignment. If you do need a reference, the object must have been created.

Caller:

ofstream ouf("someFileName.txt");
test testObj(ouf)

Your class header:

test::test(ofstream& ous) : ofs(ous) { }

Upvotes: 0

Related Questions