pacific
pacific

Reputation: 15

Initializing an ifstream variable in constructor of class

How do I initialize an ifstream variable in a constructor of class? Given below is the class and the constructor. I am using Initialization List to Initialize the ifstream variable. The below code works.

class A
{
public:
A(ifstream& in1);  // constructor

private:
ifstream& input;  // reference to the input stream
};

A::A(ifstream& in1) :input(in1)
{
//counstructor used to initialise the member variables. Initialization list     used to initialize.
}

Why doesn't the below code work?

A::A(ifstream& in1) 
{
input=in;
}

Upvotes: 1

Views: 1939

Answers (2)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145279

A reference can't be initialized with an assignment. Once it's initialized it's just an alias for whatever it refers to. An assignment to it is an assignment to what it refers to, and a std::ifstream is not copyable.

Upvotes: 2

user93353
user93353

Reputation: 14039

References have to be initialized at declaration.

A::A(ifstream& in1) :input(in1)

This initializes it at declaration. The member initializer list is the way to initialize references in a constructor.

input=in;

This doesn't.

Upvotes: 2

Related Questions