1

My class structure is as follows:

Test_Camera.h:

class Test_Camera : public Camera_Interface { public: Test_Camera (string const& aName); ... 

Test_Camera.cpp

Test_Camera::Test_Camera(string const& aName) : Camera_Interface(0, 0, 0, 0), name(aName) 

In my code that instantiates a Test_Camera object I have 2 scenarios. The first compiles fine, but the second doesn't and I can't figure out why.

Test_Camera cam ("cam"); // This compiles Test_Camera& cam ("cam"); // This does not compile 

When I try to compile the second example I get an error:

error: invalid initialization of non-const reference to type 'Test_Camera&' from a temporary of type 'const char*'

I also tried:

string name = "cam"; Test_Camera& cam (name); //does not compile 
1
  • You get the same error message for ints Commented Apr 17, 2013 at 14:02

1 Answer 1

6

References should refer to an existing object:

Test_Camera cam ("cam"); Test_Camera &cam_ref = cam; 
Sign up to request clarification or add additional context in comments.

3 Comments

Why is it that when I do Test_Camera& cam (); this compiles?
@Redek: Because that's a function prototype. The compiler assumes that cam() is function returning Test_Camera&.
@phresnel Thank you, that's where my confusion was.. I thought that it was calling the no-argument constructor. Makes a lot more sense now!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.