2

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
    ... // ?
}
user2410243
  • 187
  • 3
  • 12

2 Answers2

1

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) { }
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • So how can I open with it, when it try this->file.open it gives me errors – user2410243 Dec 21 '13 at 15:15
  • You would do `file.open("filename");` in the constructor, but you're better off using the initialisation list instead. – Joseph Mansfield Dec 21 '13 at 15:23
  • But it's a class, it's not a constant file – user2410243 Dec 21 '13 at 15:35
  • @user2410243 What do you mean by a "constant file"? Are you just asking why there is no `this->`? Doing `this->` is just not necessary in most cases; it would work with or without it. – Joseph Mansfield Dec 21 '13 at 15:36
  • This isn't what I asked. When I decelerate the ifstream - it's in the class and it should be by the path that I get in the constructor. I get a path that I should open the file with it. – user2410243 Dec 21 '13 at 15:46
0

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.

Community
  • 1
  • 1