-ampersand-in-the-return-type-of-a-function


how-does-ampersand-in-the-return-type-of-a-function-declaration-work

type& foo();


Hi,

It means that the function returns a reference. Be careful not to return a reference that is local to the function, as it goes out of scope as the function ends. It also often useful to return a const reference.

Hope all is well :+)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

class num {
    int v;
    public:
        explicit num(int v): v(v) {}
        num& operator += (const num& other) {
            v += other.v;
            return *this;
        }

        friend std::ostream& operator << (std::ostream& oss, const num& n) {
            oss << n.v;
            return oss;
        }
};

int main() {
    num t(9);
    t += num(5);
    std::cout << t << std::endl;
}


Ampersand is used to return a reference to an object, but as TheIdeasMan mentioned, you should make sure the object you are returning is not local to the function, i.e. was not created on the stack and inside the function
Last edited on
thanks..what syntactical ways I can use this reference? An example would be nice
Topic archived. No new replies allowed.