0

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?

alsjinus
  • 77
  • 1
  • 10

2 Answers2

3

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:

  • references should be initialised; and
  • you can't assign a float-pointer to and int-pointer.

(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; }
                                           ^
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • Since x here: Thing(char ch, float x) is passed by value, I am still able to access the address of x? – alsjinus Oct 19 '15 at 01:21
  • @Aria, no, and that will become clear as you clean up each problem and try to recompile :-) The object `x`, as an formal rather than actual parameter, will disappear once the function returns so setting up a reference to it that will itself survive function exit is a no-no. – paxdiablo Oct 19 '15 at 01:40
0
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.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Can I just change this line: Thing(char ch, float x) { c = ch; p = &x; f = x; } in to Thing(char ch, float x) { c = ch; &f = x; }, and also delete the sixth line? – alsjinus Oct 19 '15 at 01:17
  • No, you cannot. Your question convinces me that you don't understand how reference types in C++ work. Try http://stackoverflow.com/questions/2765999/what-is-a-reference-variable-in-c. – R Sahu Oct 19 '15 at 01:21