Reputation: 15
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
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
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