1

I want to keep a file as member of following class:

class MyClass
    {
    public:
        MyClass();
        ~MyClass();

    private:
        // why this line is OK   
        std::ifstream fileOK = ifstream("..\\abc.txt");
        // why this line is NOT OK  
        std::ifstream fileNotOK("..\\abc.txt");

    };

However if i write that same error line inside any member function then it works:

MyClass::MyClass()  {
        std::ifstream fileNotOK("..\\abc.txt");
    }

also, I notice that, there is No constructor of std::ifstream that has only one parameter like: ifstream (const char* filename)

So How single parameter constructor works and why it cant instantiate member file object like c++ from class declaration.

user5005768Himadree
  • 1,375
  • 3
  • 23
  • 61
  • 2
    `std::ifstream fileNotOK("..\\abc.txt");` [as member declaration] is parsed as function declaration, because of [most vecxing parsing](https://stackoverflow.com/questions/14077608/what-is-the-purpose-of-the-most-vexing-parse). You can use `std::ifstream fileNotOK{"..\\abc.txt"};` instead. – Lukas-T Sep 02 '20 at 07:10
  • @churill however this creates local variable that shadows class wide one with the same name. The constructors initializer list might be what he wants. – KIIV Sep 02 '20 at 07:12
  • @KIIV I was talking about the one in the first snippet, have clarified it :) – Lukas-T Sep 02 '20 at 07:15
  • 1
    Your second question: there is `explicit ifstream (const char* filename, ios_base::openmode mode = ios_base::in);` - second parameter has a default value, so `ifstream("xxx");` is a valid CTor call – pptaszni Sep 02 '20 at 07:55

0 Answers0