I have a class declared like this (only relevant parts shown):
class X
{
public:
X(int x);
private:
FILE *stream;
int _x;
}
The constructor opens a file:
X::X(int x) : _x(x)
{
int err = fopen_s(&stream, "myfile.txt", "w");
fputs("some text", stream);
...
}
It is used in another class like so:
class Y
{
public:
Y();
private:
X myX;
}
In the constructor of Y, myX is initialized via the initialization list and a method is invoked upon it:
Y::Y() : myX(100)
{
myX.init();
}
When I step through the constructor of X, the stream is allocated and written to without error. If I put a breakpoint at the opening brace of the constructor of Y, stream has the same value as during the constructor of X. When I step into the body of Y's constructor, however, the value of stream changes and the next use of it (e.g. in init()) causes an access violation. Everything works fine if I change Y to store a pointer to X instead of a direct reference and allocate X on the heap. I suspect it has something to do with where fopen_s is allocating the FILE*, but I cannot confirm this. Can anyone explain why this fails?