0
class Pointer {
private:
    int &x;
public:
    Pointer(int &y) : x(y) {}
    int getT() { return x; }

};

int main()
{
    int w = 40;
    Pointer test(w);
    std::cout << &test <<' ' << &w;
}

What is the significance of the int &x declaration in the class definition? I understand that the int &y passed as a parameter for the constructor is the value passed by reference, but what about int &x as this type of declaration is showing me an error inside the main() function?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 3
    what is the error you see? Your code as it is compiles please show a [mre] – Alan Birtles Dec 10 '21 at 18:13
  • In this context `x` is a [reference variable](https://stackoverflow.com/questions/2765999/what-is-a-reference-variable-in-c). It has similar semantics to the reference parameter `int& y`: It is a reference to another `int`. In the case of `Pointer test(w);`, `test.x` will be a reference to `w`. – Nathan Pierson Dec 10 '21 at 18:17
  • Maybe, you should try making your code `int &getT()` and outputting `std::cout << &test.getT() << ' ' << &w`. `w` in `main` points to the same location in memory as `x`. I'd also recommend renaming `x` to `t` or `getT` to `getX`. Be careful with references like these too. It's prone to error to have a private `x` point to the exact place in memory as a different variable that can be changed without `Pointer` knowing it. In this case, copying the reference to `w` is most likely the same amount of work as passing `w` by reference too since `int` is so small. – user904963 Dec 10 '21 at 19:42

1 Answers1

2

In the both cases in the constructor declaration

Pointer(int &y) : x(y) {}

and in the data member declaration

int &x;

there is declared a reference.

After calling the constructor

Pointer test(w);

the object test contains a reference to the object w passed by reference.

So for example you could write

int w = 40;
Pointer test(w);

std::cout << test.get() << '\n';

and the output will be

40

Now you can change the variable w as for example

w = 100;

and this statement

std::cout << test.get() << '\n';

will output

100

because it outputs a value of the same object stored in the object test by reference.

The reference x will be valid in the object test while the referenced object w is itself alive.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335