Hi,
I'm looking into C++ more and more and I came across references. What the heck are they useful for?? I mean why create a reference when you can just work with the original?
Thanks,
Printable View
Hi,
I'm looking into C++ more and more and I came across references. What the heck are they useful for?? I mean why create a reference when you can just work with the original?
Thanks,
You use references for the same reason you use pointers: the ability to keep track of objects in memory. Sometimes working with the original object isn't feasible. This is really evident with dynamic instantiation were the only method for accessing objects is through pointers.
When you first learn about them, references and pointers aren't immediately useful. If you want to get frighteningly familiar with pointers, check out some of the linked list tutorials on the web.
A basic use for using references is this: suppose I have a function that verifies that all the data in my array is ok, but doesn't change it.
When I call CheckArray(), the contents of "myArray" will be copied into "array". This can take a lot of time. By using references, I can simply use the same array that I have in main(), and by marking it const, show that I'm not going to change it inside the function:Code:bool CheckArray(vector<int> array)
{
// ....
}
//
int main()
{
vector<int> myArray = CreateReallyBigArray();
// not good. myArray is copied.
if (CheckArray(myArray)) { // .... };
}
Code:bool CheckArray(const vector<int>& array)
{
// ....
}
//
int main()
{
vector<int> myArray = CreateReallyBigArray();
// array is a reference to myArray. Only it's address on the stack / in memory is passed.
if (CheckArray(myArray)) { // .... };
}
references are a form of indirection, they're useful for the same reason links are useful on the web
Exactly! Wouldn't want the entire internet being copied to your computer if you just one to look at one page.
I want the internet copied to my computer :(Quote:
Originally posted by Dreamlax
Exactly! Wouldn't want the entire internet being copied to your computer if you just one to look at one page.