• Advertisement
Sign in to follow this  

C++ Reference (&)

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
Share on other sites
Quote:
Original post by Promit
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];
}


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 this post


Link to post
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 this post


Link to post
Share on other sites
Quote:
Original post by HughG
Why 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 alias
int 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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement