How do you intialize a reference to a pointer

I wrote this simple program.
I get an error saying that the member variable 'value' is not initialized, so how do I initialize it.
Secondly, I'd really appreciate any tips on improving the code. I really want to develop my C++ skills.

Thanks :)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream.h>
#include <conio.h>

class Multiples
{
 public:
  Multiples(int);
  ~Multiples();
  void Double();
  void Triple();
  void Multiple(int);
  void setValue(int);
  int getValue();
 private:
  int*& value;
};

Multiples::Multiples(int number)
{
 int* i(number);
 value= i;
}

Multiples::~Multiples()
{
}

void Multiples::Double()
{
  *value = *value*2;
}

void Multiples::Triple()
{
 *value = *value*3;
}

void Multiples::Multiple(int i)
{
 *value = *value * i;
}

void Multiples::setValue(int i)
{
 *value = i;
}

int Multiples::getValue()
{
 return *value ;
}

int main()
{
clrscr();
Multiples* m(5);
m->Double();
cout<<"5 doubled is: "<<m->getValue()<<endl;
m->setValue(2);
m->Multiple(10);
cout<<"Two ten times is: "<<m->getValue()<<endl;
getch();
return 0;
}
References have to be initialized in the constructor's initializer list.

1
2
3
4
Multiples::Multiples(int*& number) // the param would need to be the same type
  : value(number)   // value needs to be constructed in the initializer list
{
}


But you have bigger conceptual problems here.

- Why are you using pointers everywhere? 'value' has no reason to be a pointer. Neither does 'm'.

- You can't have a non-const reference to '5'. The whole point of having a reference is that it's an alias for another variable name. What you're trying to do is similar to this:

1
2
3
4
int& myref = 5;  // nonsense

myref = 10;  // this line is the same as saying "5 = 10;"
  // it's trying to change the value of the literal 5.  Not possible... 5 is 5, it cannot be 10 


Really, I don't see the need for pointers or references anywhere in this code. 'value' should just be a normal int. 'm' should be an object, not a pointer. Everywhere you're using m-> should change to m., and everywhere you're using *value should change to value.
Last edited on
Topic archived. No new replies allowed.