0

I'm trying to understand how this type of function works and how you would use it.

I assume there's some class we'll call it test.

class Test {

}

I saw this type of function in a header file and I'm trying to figure out what it does. And how to use it properly.

Test& testFunction();

Appreciate the help.

1 Answer 1

2

What's in front of the function name is the type that the function will return. In this case, testFunction is returning a Test object. The & in this case (reference) means that it will return a Test-reference. This is important if you wish to modify the returned object when you call the function. Or use it in some way not possible with "return-by-value".

Your code doesn't tell us much about what you're going to be doing with the return value, but here is a good example that's used quite commonly:

Test & T::f() {
    // do something

    return *this;
}

*this here is the actual object on which its method .f is being called. What's special here is that since we are returning a reference, we can chain calls while maintaining the original object. *this will be the same *this every time. With return-by-value we aren't able to do this. For example:

By reference:

Test & T::f() {

    this->x++;

    return *this;

}


int main() {

    Test t;

    t.x = 5;

    t.f().f();

    std::cout << t.x; // 7 as we expect

}

By value:

Test T::f() { ... } // notice the omission of &

int main() {

    Test t;

    t.x = 5;

    t.f().f();

    std::cout << t.x; // 6

}

t is changed only once because the object is lost on the next call.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.