Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Constructors and destructors, behaving unexpectedly

Status
Not open for further replies.

tomcr

Programmer
Dec 28, 2007
2
US
I have the following constructor for a class:
Code:
Cdata::Cdata(char *input)
{
    //Try and open the input file
    ifstream ifile(input, ios::in);
    if(!ifile.is_open())
    {
         cout << &quot;The input file didn't open!&quot; << endl;
         exit(1);
    }
}
When I call the constructor to open a file for the class it opens the file and goes through all the lines happily, it doesn't enter the if statement. However the minute the constructor has finished I find that the file has been closed. I'm not sure why, I've checked with my debugger and the code does not enter the destructor, nor am I trying to use the class outside of the scope I declared it in so I can't figure out what is going on. Why is the file being closed after the constructor has finished?
 
> the minute the constructor has finished I find that the file has been closed.

Yes, that is because your file stream object is local to the constructor:

ifstream ifile(..);

Therefore it's destructor runs when your constructor finishes thereby closing the file. If you want the file to remain open you need to make the stream object a member of your class, i.e.:

class CData{
protected:
ifstream* _ifs;
}

Cdata::Cdata(char *input)
{
//Try and open the input file
_ifs = new ifstream(input, ios::in);
if(!ifs || !_ifs->is_open())
{
cout << &quot;The input file didn't open!&quot; << endl;
exit(1);
}
}
// destructor needs to delete the input stream object which
// in turn will close the file
Cdata::~Cdata(){
delete _ifs;
}

Hope this helps
-pete
 
Thanks very much!

I had ifile declared as a private (ifstream) member of the class anyway but I guess because I used the line
Code:
ifstream ifile(input, ios::in);

It overloaded the variable (so it was referring to a local ifile) or something and like you said invoked the destructor when it went out of scope.
I now simply use:
Code:
ifile.open(input, ios::in);
So that it refers directly to ifile as a member of the class, and now it all works.

Great. :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top