Assigning pointer a reference

Apr 28, 2018 at 11:59pm
Hi guys

I have the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class myClass
{
private:
  std::ifstream* istream;
public:
void setStream(std::ifstream& stream)
{
  this->istream = stream;
}
}

int main()
{
  std::ifstream istream;

  istream.open("myfile.txt");

  myClass c;

  c.setStream(istream);

  return 0;
}


When i run it i get an error at the point where i assign the istream pointer to the passed in reference?

how come? how can i fix this?

Thanks
Apr 29, 2018 at 12:01am
A reference acts just like the original variable, so you need to use & to take it's address.
 
this->istream = &stream;


However, if you never want to reassign the pointer to something else then you could make it a reference and initialize it in the member-initialization-list of the constructor:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <fstream>

class myClass {
    std::ifstream& istream;
public:
    myClass(std::ifstream& str)
        : istream(str)
    {}
};

int main() {
  std::ifstream istream("myfile.txt");
  if (!istream) {
      std::cerr << "Can't open file\n";
      return 1;
  }
  myClass c(istream);
  return 0;
}

Last edited on Apr 29, 2018 at 12:06am
Apr 29, 2018 at 12:08am
The confusion probably arises because someone told you references are pointers.

References are not pointers, and that analogy is hopelessly inadequate. You will have better luck if you consider references as aliases of original objects. This is still coarse, but at least it's not entirely wrong.
Topic archived. No new replies allowed.