Hi. I am wondering if a log file can be created in a header which is associated with a try-catch block. Below is my stripped down code for the log_header.h and log_test.cpp

Here is log_header.h

#include<fstream>
#include<iostream>
using namespace std;

class thrower{
    fstream myfile2;
public:
    void errormessage();
};

void thrower::errormessage(){
    cout<<"Thrower works\n";
    ///////These are log commnands////////
    myfile2.open("C:\\error2.txt",ios::out);
    myfile2<<"Message 2\n"<<endl;
    myfile2.close();
    ////////////////////////////////////////
};

Here is log_test.cpp

#include"log_header.h"
#include<fstream>

#include<iostream>
using namespace std;

thrower t;
int main(){

    fstream myfile;

    try{
        int y=4;
        if (y<5){
            throw t;
        }
    }
    catch(thrower tt){
        tt.errormessage();
        myfile.open("C:\\error.txt",ios::out);
        myfile<<"Message \n"<<endl;
        myfile.close();
    }
    return 0;
}   

If I comment out all of the log_header.h lines that contain "myfile2", then the "myfile" object in the log_test.cpp gets updated and the error message from the errormessage method is printed. It would be more elegant if the log file creation was contained in the header. Please assist.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.