(I'm a newb learner) I've created the smallest possible app (below) to depict my issue which is accessing a class member ofstream object(s) from within class functions. My actual app has too many functions accessing file(s) that it doesn't really lend itself to creating an ofstream friend operator for each scenario. And I always try to stay away from global items.
So I have two specific questions,
(1) Please look at the below code and tell me why the 2nd function with the this-> ptr scenario compiles with no errors but doesn't work. No file is created or written.
(2) Please give input on any better or other ways (than the 1st function scenario) to solve this scope access issue, other than obviously creating, opening and re-opening the file object(s) repetitively from each function.
Code:
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <fstream>
#include <cstdlib>
using namespace std;
class Base{
public:
// ofstream objects
ofstream DrawDn_File;
ofstream ReVest_File;
// Class Funcs
int BaseScope1(ofstream& rFile);
int BaseScope2();
//Ctor
Base() {};
//Dtor
~Base(){};
}; // End Class declaration
//This Func opens and writes the file
int Base::BaseScope1(ofstream& rFile)
{
rFile.open("DrawDown.txt");
rFile << "writing to DrawDown.txt from Scope1 func" << endl;
cout << "Thru BaseScope1 Func" << endl;
return 0;
}
//This Func neither creates or writes the file
int Base::BaseScope2()
{
this->DrawDn_File.open("ReVest.txt"); // default overwrite
this->DrawDn_File << "writing to ReVest.txt from Scope2 func" << endl;
cout << "Thru BaseScope2 Func" << endl;
return 0;
}
int main()
{
Base BaseClass;
BaseClass.BaseScope1(BaseClass.DrawDn_File);
BaseClass.BaseScope2();
return 0;
}