Search code examples
c++inheritanceifstream

C++ ifstream declared as public but compiler says its a private member that cant be accessed


Pretty new to C++ programming so be easy on me :)

I am trying to make a program for exercise reasons with C++ and design pattern for it. This are my classes i use right now:

File.cpp-

 #include "File.h"
    #include <string.h>
    File::File() {}
    File::~File(void) {}

File.h-

    #pragma once

#include <string>
#include <iostream>

using namespace std;

class File
{
    public:
        //Ctor
        File();
        //Dtor
        ~File(void);

        //Opens up the file for streaming data I/O
        //virtual bool open();

    protected:      
        string _file_name;

};

FileReader.h

#pragma once
#include <fstream>

#include "File.h"

//Handles the input of our file
class FileReader : public File
{
    public:
        FileReader(string file_name_to_open);
        ~FileReader(void);

        bool isFileOpen();
        bool open();
        ifstream _in_stream;
};

FileReader.cpp

#include "FileReader.h"


FileReader::FileReader(string file_name_to_open) { 
    _file_name = file_name_to_open;
    open();
}

FileReader::~FileReader(void) { }

bool FileReader::isFileOpen() {
    return _in_stream.is_open();
}

bool FileReader::open() {
    if(isFileOpen()) {
        try{
            _in_stream.open(_file_name , ios::in);
        } catch(exception exce) {
            return false;
        }
        return true;
    } else {
        return false;
    }

}

Now for some reason once i compile my main that has only

FileReader my_file_reader = FileReader("hello.txt");

i get an error

C2248 - 'std::basic_ofstream<_Elem,_Traits>::basic_ofstream': cannot access private member declared in class 'std::basic_ofstream<_Elem,_Traits>'

Is there a solution for this cuz i tried to so many ways to solve this but didn't found anything good so far.

Thanks


Solution

  • The problem is that in the line

    FileReader my_file_reader = FileReader("hello.txt");
    

    you try to copy FileReader. And because FileReader has a member of type ifstream, this member need to be copied then. But it cannot, because ifstreams are not copyable. (The error message from the compiler may be misleading - it does not say that you cannot copy, it says that the copy constructor is private).

    Please take more care about lifetime and copying of objects in C++. For instance, instead of

    FileReader(string file_name_to_open);
    

    you should use

    FileReader(const string& file_name_to_open);