reference returing funiton

Where we can use reference returning function . and how?
like defined.
1
2
3
4
5
6
7
8
9
10
 inr& REFFUN(int jak){

return jak;
}
or 

object & refobjfun(object obj){

return obj;
}
Both of your examples are returning a reference to a function's local variable, which doesn't exist when the function ends, that's really bad.

A better example might be:
1
2
3
4
5
6
7
8
9
10
11
12
class my_char_vector {
    size_t m_size;
    char* m_array;

public:
    my_char_vector(size_t size) : m_size(size), m_array(new char[size]) {}
    ~my_char_vector() { delete [] m_array; }
    char& front() { return &m_array[0]; }
    char& back() { return &m_array[m_size - 1]; }
    char& operator[](size_t idx) { return &m_array[idx]; }
    //...
};


front() and back() are returning references to parts of the object's internal array. And you can use it like this.
1
2
3
4
5
6
7
int main()
{
    m_char_vector v(80);
    v.front() = 'C';  // update v.m_array[0];
    v.back() = '\0'; // update v.m_array[79];
    v[3] = 'A'; // random access into v
}
Last edited on
Topic archived. No new replies allowed.