A little question about &

Hi,
I have a little doubt with this:

1
2
Whatever y(...);
Whatever& x = y;


With that code, x will act as a pointer to y??

Thanks in advance!
not quite, x is a reference to a Whatever object

http://cplusplus.com/doc/tutorial/pointers/
Basically yeah.

Another way to think of it is that x "is" y. Just another name for the same object.
Oh! Ok!!

Thanks a lot!
Example..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
void MyFunction(int, int &);

int main()
{
	int number, value;
	std::cout << "Please enter a number: ";
	std::cin >> number;
	std::cout << "How much would you like to multiply it by: ";
	std::cin >> value;
	
	MyFunction(value, number);
	
	std::cout << "Your multiplied number is: " << number;
	return 0;
}

void MyFunction(int value, int &rNumber)
{
	rNumber *= value;
}


This will allow you to change a parameter in a function outside of it's scope.
I've got another doubt:

Having something like this:
1
2
3
4
5
6
class A {
  private:
     Whatever& x;
  public:
      A(const A& y);
};


I want to create another copy of x from the copy constructor, as if I typed:
x = new Whatever( y.GetX() )

However, this won't compile. Is there a way to do this? I think x should be Whatever* instead of Whatever& .
Is that so?

Thanks!

I want to create another copy of x from the copy constructor, as if I typed:
x = new Whatever( y.GetX() )


What exactly do you want x to refer to?

I think x should be Whatever* instead of Whatever& .
Is that so?


Well pointers and references are almost the same thing although in some situations references are just a little cleaner syntax-wise, but anyhing you can do with a reference you can do with a pointer. Although thats not always true the other way around...

What exactly do you want x to refer to?


I want a local copy of class member x, so I can modify its values without changing the ones of y::x[i].

So, when typing [i]x = new Whatever( y.GetX() );
x is pointing to a new copy of y::x.

What I'm asking if its possible to achieve the same as above using Whatever& x instead of
Whatever* x directly.

I tried to explain it as clearly as I could, so my apologies if its still unclear :D

Thanks!
A reference is assigned to when you initialize it, the first time. And it can never be changed again. Ever. For instance:
1
2
3
4
int x = 5;
int y = 7;
int& z = x; //z is now the same variable as x
z = y; //x and z now equal y, but neither is the same variable as y 
Last edited on
I think that I get it now. Thanks to everyone!
Topic archived. No new replies allowed.