1

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?

  • 1
    You should show Init() also, consider not doing work in your constructor and add an Init to Y that would then call Init on its X (http://stackoverflow.com/questions/293967/how-much-work-should-be-done-in-a-constructor) – emartel Nov 13 '12 at 17:30
  • Does the error persist if you do a clean rebuild? – ecatmur Nov 13 '12 at 17:30
  • 1
    side bar: identifiers (variable names, types, macro definitions, etc.) with leading underscores are reserved by the implementation you're compiling against. I.e. `_x` is a bad habit and you should break it now while you're learning. `x_`, `x`, etc. are all perfectly fine. – WhozCraig Nov 13 '12 at 17:57
  • Also, just for kicks, if you need to do that in your constructor, then declare the default constructor for X private so you can't accidentally create an X with an invalid FILE* in there. – rutgersmike Nov 13 '12 at 22:06

0 Answers0