user2410243
user2410243

Reputation: 187

ifstream variable in class

I have my class which has to have ifstream file in it.

I dont know how to present it in the class header

A:

class MyClass
{
    ...
    ifstream file;
    ...
}

B:

class MyClass
{
    ...
    ifstream& file;
    ...
}

I know that ifstream has to get path in the decaleration, so how do I do it?

Also how do I open a file with it?

EDIT:

I want the first way, but how do I use it SYNTAX-ly?

let's say this is the header(part of it)

class MyClass
{
    string path;
    ifstream file;
public:
    MyClass();
    void read_from_file();
    bool is_file_open();
    ...

}

funcs

void MyClass::read_from_file()
{
    //what do I do to open it???
    this->file.open(this->path); //Maybe, IDK
    ... // ?
}

Upvotes: 2

Views: 4671

Answers (2)

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

You more than likely want the first option. The second is a reference to some other ifstream object, rather than an ifstream that belongs to MyClass.

You don't need to give an ifstream a path immediately. You can later call the ifstream's open function and give that a path. However, if you want to open the ifstream immediately on initialisation, you need to use the constructor's initialisation list:

MyClass() : file("filename") { }

If you need the constructor to take the file name, simply do:

MyClass(std::string filename) : file(filename) { }

Upvotes: 1

user1804599
user1804599

Reputation:

Initialise it in the constructor:

class my_class {
public:
    my_class(char const* path) : file(path) {

    }

    my_class(std::string const& path) : my_class(path.c_str()) {

    }

private:
    std::ifstream file;
};

Also see The Definitive C++ Book Guide and List.

Upvotes: 0

Related Questions