Reputation: 77
I am still a beginner in C++, and I am supposed to find the errors in the following code.
1 class Thing
2 {
3 public:
4 char c;
5 int *p;
6 float& f;
7 Thing(char ch, float x) { c = ch; p = &x; f = x; }
9 };
I understand that in the sixth line there is an error: reference f need to be initialized. But I am confused about the seventh line. It looks like a constructor, but I cannot make sure p = &x; is correct? Also, If I want to correct the error of the reference initialization, how can I do it?
Upvotes: 0
Views: 165
Reputation: 206567
p = &x;
is not right since p
is of type int*
and &x
is of type float*
.
f = x;
is most likely not what you intended. You probably want to f
to be a reference to x
. The above line does not do that. It assigns the value of x
to the object referenced by f
.
If you want f
to be a reference to x
, you need to initialize it as:
Thing(char ch, float& x) : f(x) { ... }
// ^^^ different from your signature
Using
Thing(char ch, float x) : f(x) { ... }
is problematic since f
will be a dangling reference once the function returns.
Upvotes: 0
Reputation: 881153
The best thing to do to find out if there are errors is simply to compile it (1).
If you do that, you'll find at least two problems:
(1) As per this transcript:
$ g++ -c -o prog.o prog.cpp
prog.cpp: In constructor ‘Thing::Thing(char, float)’:
prog.cpp:7:7: error: uninitialized reference member in ‘float&’ [-fpermissive]
Thing(char ch, float x) { c = ch; p = &x; f = x; }
^
prog.cpp:6:14: note: ‘float& Thing::f’ should be initialized
float& f;
^
prog.cpp:7:43: error: cannot convert ‘float*’ to ‘int*’ in assignment
Thing(char ch, float x) { c = ch; p = &x; f = x; }
^
Upvotes: 3