Possible Duplicate:
C++: When to use References vs. Pointers
I’m pretty new programmer to the C/C++ languages and since I am coming from a background of C#, Java, JavaScript and a little bit of Visual Basic and Python, I am having a hard time to understand some of the things in C++.
I already know how to use reference and pointers and what they really mean, etc. But I don’t understand why and where to use them. I know that references sometimes are used like this:
int x = 2;
void Square(int &value)
{
value = value*value;
}
Square(x);
cout << x << endl;
And the output will be 4.
I thought I don’t quite understand why to do it that way and not do like this:
int x = 2;
int Square(int value)
{
value = value*value;
return value;
}
x = Square(x);
cout << x << endl;
Anyway, I hope someone may be able to help me understand why and where to use reference and pointers.
You pass references for two main reasons:
If you want the second benefit but not the first, you usually pass a
constreference to avoid mistakenly changing the object passed.In C++, pointers and references are much the same with two exceptions:
nullptr)If you want to do one of these things, you have to use a pointer.
Additionally, pointers usually point to objects created in the heap by using
new, while references usually point to objects created in the stack. This means that the lifetime of objects pointed to by pointers is usually controlled manually. You have to explicitly calldeleteon objects created bynewin order to destroy them, but the lifetime of objects created in the stack is automatically managed by the runtime (hence their name “automatic variables”).I don’t know if this is all you needed to know or you are looking for something more specific.