stillQuestioning
stillQuestioning

Reputation: 153

Issue with ofstream class instance not compiling

I'm encountering an issue with writing to a file using ofstream within a C++ class. I've created a minimal example to illustrate the problem:

#include <iostream>
#include <fstream>

class Aclass {
private:
    std::ofstream historyFile;

public:
    Aclass() {
        historyFile.open("test.txt");

        if (!historyFile.is_open()) {
            std::cerr << "Error: Unable to open file for writing: test.txt" << std::endl;
        }
    }

    void writeFile() const {
        historyFile << "sometext";
        historyFile.close();
    }

    void writeFile2() const{
        std::ofstream ofs ("test.txt");
        ofs << "sometext";
        ofs.close();
    }
};

int main() {
    Aclass instance;
    instance.writeFile();
    std::cout << "Finished writing to file" << std::endl;
    return 0;
}

writeFile complains

no operator "<<" matches these operands -- operand types are: const std::ofstream << const char [9]

and

the object has type qualifiers that are not compatible with the member function "std::basic_ofstream<_CharT, _Traits>::close [with _CharT=char, _Traits=std::char_traits]" -- object type is: const std::ofstream

for the subsequent line

I am using g++ (Ubuntu 9.4.0-1ubuntu1~20.04.2) 9.4.0

Why does the second implementation compile and run and not the first? It seems like both should be equivalent?

Upvotes: 0

Views: 39

Answers (0)

Related Questions