Divya Aggarwal
Divya Aggarwal

Reputation: 61

How to initialize an ifstream object in class constructor?

I am aware that I can initialize an object of type ifstream like : std::ifstream ifs ("test.txt", std::ifstream::in);

But let's say I have a class which needs to have ifstream object as a member of the class:

class A
{
private:
std::ifstream file;
}

How should I go about initializing this object in the classes' constructor?

Upvotes: 2

Views: 590

Answers (1)

Sid S
Sid S

Reputation: 6125

Add a constructor with an initializer list :

class A
{
    private:
        std::ifstream file;

    public:
        A()
        : file("test.txt", std::ifstream::in)
        {
        }
};

Upvotes: 3

Related Questions