Public Group

# C++ Reference (&)

This topic is 5060 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I'm working with a custom templated Array class that handles various array operations (bound checking, inserts, deletes, etc). One of the other things it does is overloads the [] when using arrays like so: Datatype& operator[] ( int p_index ) { return m_array[p_index]; } So this allows you to actually modify values in the array. For example: Array<int> intarray(10); //Array is templated class containing above intarray[5] = 42; So because of the operator function above I can actually modify my array since it returns a reference instead of a pointer. But will I be able to do something like this: int i = intarray[5]; or do I have to make i a reference as well? int& i = intarray[5]; TIA!

##### Share on other sites
int i = intarray[5]; is fine.

For micro-optimization purposes, you can also make a const accessor:
const Datatype& operator[] ( int p_index ) const
{
return m_array[p_index];
}

##### Share on other sites
Validate that the index is within bounds.

##### Share on other sites
Quote:
 Original post by Promitint i = intarray[5]; is fine.For micro-optimization purposes, you can also make a const accessor:const Datatype& operator[] ( int p_index ) const{return m_array[p_index];}

Alright thanks for the tip. Why is it that you can assign a reference of an int to a plain old int? I mean I know you can:

int i = 5;
int &r;
r = i;
r++; // i now equals 6

So it would be alright to do this:

int i = 5;
int j = 4;
int &r;
r = j;
i = r; // i = 4 ?

Quote:
 Validate that the index is within bounds.

Yes the code exists I just cut it out for this post.

Thanks guys.

##### Share on other sites
AFAIK, you can't declare a reference and not initialize it. But yea,

int i = 5;
int j = 4;
int &r = j;
i = r;

Everything now equals 4.

##### Share on other sites
Quote:
 Original post by HughGWhy is it that you can assign a reference of an int to a plain old int?
A reference isn't a distinct type; it's an alias to an existing variable of a given type. Consequently, you can manipulate the original variable via the reference:
int i = 6;int &ref = i; // creates an aliasint j = ref;  // performs a copy++j;          // j is now 7--ref;        // i is now 5, so ref is also 5

Quote:
 int &r;
References can only be initialized, not declared or instantiated. ie
int &r = i;
In the absence of the assignment, the statement is invalid, and a compile-time error.

1. 1
2. 2
Rutin
19
3. 3
4. 4
5. 5

• 9
• 9
• 9
• 14
• 12
• ### Forum Statistics

• Total Topics
633303
• Total Posts
3011280
• ### Who's Online (See full list)

There are no registered users currently online

×