43

I have this class

class CamFeed {
public:
    // constructor
    CamFeed(ofVideoGrabber &cam); 
    ofVideoGrabber &cam;

};

And this constructor:

CamFeed::CamFeed(ofVideoGrabber &cam) {
    this->cam = cam;
}

I get this error on the constructor: Constructor for '' must explicitly initialize the reference member ''

What is a good way to get around this?

clankill3r
  • 9,146
  • 20
  • 70
  • 126
  • 3
    You must initialize a reference immediately because it cannot be null like a ptr – aaronman Oct 24 '13 at 20:57
  • 9
    Think carefully about what this line of code means, it's not what you think: `this->cam = cam;` This wouldn't re-target the reference. It would call `operator=` on `this->cam` -- which hasn't been initialized yet. – David Schwartz Oct 24 '13 at 20:59

1 Answers1

66

You need to use the constructor initializer list:

CamFeed::CamFeed(ofVideoGrabber& cam) : cam(cam) {}

This is because references must refer to something and therefore cannot be default constructed. Once you are in the constructor body, all your data members have been initialized. Your this->cam = cam; line would really be an assignment, assigning the value referred to by cam to whatever this->cam refers to.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480