0

I am not able to understand what is being returned from function in following code (pointer or value) .

#include<iostream>
using namespace std;
class safearay
{
    int a[10];
public:
    int& operator [](int n)
    {
        if(n<0 || n>5 )
        {
            cout<<"Exceeded bounds"<<endl;
        }
        return a[n];
    }
};
int main()
{
    safearay sa1;
    for (int j=0;j<10;j++)
    {
        sa1[j]=j*j;
    }
    for (int j=0;j<10;j++)
    {
        int u=sa1[j];
        cout<<u<<endl;
    }
}

Please explain

vishal
  • 2,258
  • 1
  • 18
  • 27
Deepak Kumar
  • 109
  • 1
  • 1
  • 12
  • 1
    it returns a reference to the nth element. – vishal Oct 24 '15 at 05:33
  • 3
    Possible duplicate of [What are the differences between a pointer variable and a reference variable in C++?](http://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in) – Cahit Gungor Oct 24 '15 at 05:54

2 Answers2

1

Pay attention that in your code you do this:

 safearay sa1;
sa1[j]=j*j;

Normally you cannot access the object values like this. The method you're asking about is the operator overload method, that defines what whould the object do on such an access.

int& operator [](int n)
    {
        if(n<0 || n>5 )
        {
            cout<<"Exceeded bounds"<<endl<<;
        }
        return a[n];
    }

means

return the reference to the value in the n'th place of the array a in object safearay if n is in range The return value is passed by reference, therefore you can assign to it and the change will be in a[i]

You can read more about operator overload here

More about passing values by reference here

Roman Pustylnikov
  • 1,937
  • 1
  • 10
  • 18
1
int& operator [](int n)  

returns a reference to an int.
Essentially, you can use it as int, but changes will affect a[n] in the class too (because it's returned). It's like a pointer without all the *, except you can't change the address where it points to.

deviantfan
  • 11,268
  • 3
  • 32
  • 49
  • Does the following statement makes sense :: A function that returns a reference , is treated as if it were a variable . It returns alias to a variable, namely the variable in the function's return statement . So it can be used on the left side of an assignment operator . – Deepak Kumar Oct 24 '15 at 05:47
  • `A function that returns a reference , is treated as if it were a variable.` Not the function itself is treated as variable, but what it returns. Else, everything is true. – deviantfan Oct 24 '15 at 05:53