0

I am facing one issue while passing file object using structure and the code is

#include <iostream>
#include<fstream>
using namespace std;
typedef struct abc
{
    ofstream &t;

}stabc;

class dc
{
    public:
    static void fun(stabc *ad);
    static stabc ab;

};
int main()
{
    ofstream str;
    str.open("hello.csv",ios::app);
    str<<"hellllooo"<<endl;
    dc d;
    d.ab.t=str;
    dc::fun(&d.ab);
    cout << "Hello world!" << endl;
    return 0;
}
void dc::fun(stabc *ad)
{
    ofstream& st=ad->t;
    st<<"kikiki"<<endl;

}

It gives uninitialized reference member abc::t. Please tell me where i am wrong?

Amit
  • 33
  • 2

2 Answers2

3

You need to initialize the reference t in the member initializer list.
References are special construct which need to be initialized at the time of creation. Since you do not initialize the member reference the compiler emits the diagnostic.

Member references must to be initialized in the member initializer list.

Online Sample:

#include <iostream>
#include <fstream>
using namespace std;
struct stabc
{
    ofstream &t;
    stabc(ofstream &obj):t(obj){}
};

int main()
{
    ofstream obj2;
    stabc obj(obj2);
    return 0;
}

Also note in C++(unlike C) you do not need to typedef a structure in order to use it without the keyword struct. You can simply use the structure name without pre-pending the struct.

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
1

You cannot re-seat references. They have to be initialized and there is no "default" value for a reference. So you would need to construct an instance of an abc using the reference to the file stream object:

struct abc
{
    std::ofstream &t;
};

then

abc myabc = {str};

or give abc a constructor and use the constructor initialization list:

struct abc
{
  abc(std::ofstream& o) : t(o) {}
  std::ofstream &t;
};

abc myabc(str);
juanchopanza
  • 223,364
  • 34
  • 402
  • 480