I know that we can't return a local variable by reference since it would go out of scope. I am a bit confused when it comes to returning passed references though. For instance is the below example legal or would it lead to undefined behaviour?
classobject &function(classobject &obj) {
return obj;
}
That's absolutely fine, and in fact it's very often how non-member operator<< and the like are implemented, to allow you to chain the operator.
The key thing to think about is object lifetime, and as you know the object is passed in by reference, it has to outlive the function call. This makes it safe to return the same reference.