C++ stream reference as class member

c++, reference, stl, stream

Solution

You can't bind a reference to a different object after it has already been bound. That's one of the fundamental differences between using pointers and using references. Given this, it would be more appropriate for you to use a pointer.

I prefer to use references as I like the fact that they warrantee you that they won't have invalid values

This isn't true. If the object a reference is bound to is destroyed, then it references an invalid object, just as with pointers.

Problem

I have a class which is sort of like this: ``` #include <iostream> class A { public: A (std::istream& is): _is(is) {} void setInputSource (std::istream& is) { _is = is; } A& operator>> (int& x) { _is >> x; return *this; } private: std::istream& _is; }; ``` And I want the `_is` member to act just as a reference. I mean, it has to "point" to an external `std::istream` and I don't want the `setInputSource()` method to copy the stream that is passed as argument. The problem is that the program won't compile because that method that I mentioned is trying to access the `operator=` of the class `std::basic_istream<char>`. My goal is to get the class behave as expected in a program like this: ``` int main() { int a, b; std::ifstream ifs("myfile.txt"); A myA(std::cin); myA >> a; myA.setInputSource(ifs); myA >> b; return 0; } ``` I thought to use pointers instead, but I prefer to use references as I like the fact that they warrantee you that they won't have invalid values and it seems to me that it's a more elegant approach.

Original source