0

I am trying to store an ofstream pointer as a member variable and use class methods in order to manipulate the ofstream. However, when I try to access the stream outside the method where the pointer was assigned, I get read access violations.

Below is an example producing the problem. Here, it successfully writes "Test 1" in the method Open, but it fails to write "Test 2" in the method Write.

writer.h

#include <fstream>

class Writer
{
public:
    Writer();
    void Open();
    void Write();
    void Close();
private:
    std::ofstream* stream_;
};

writer.cpp

#include "writer.h"

Writer::Writer() {}

void Writer::Open(){
    std::ofstream stream("test.txt", std::ofstream::out | std::ofstream::trunc);
    stream_ = &stream;
    *stream_ << "Test 1\n";
}

void Writer::Write(){
    *stream_ << "Test 2\n";
}

void Writer::Close(){
    stream_->close();
    stream_ = nullptr;
}

main.cpp

#include "writer.h"

int main()
{
    Writer testwriter;
    testwriter.Open();
    testwriter.Write();
    testwriter.Close();
}

I am quite new to using Stack Overflow, so please let me now if I can improve the question.

bjarke15
  • 83
  • 5

0 Answers0