efaj
efaj

Reputation: 944

Function with reference argument not working with value returned from other function

I have Messageable::receiveMessage(Message&). When I use it, I'd expect to to be able to pass it a Message, I pass it a Message returned from a function, but when I do I get

error: no matching function for call to 'Messageable::receiveMessage(Message)'
no known conversion for argument 1 from 'Message' to 'Message&'

It only works when I use my overloaded << (because it returns a Message&, ie: receiveMessage(myMsg<<value); )

What could I be/am I likely doing wrong, or is it just not in the standard to allow a value returned from a function? I thought that when you declared a reference argument, you could use the object itself and it's automatically casted (only difference, that it isn't copied), and I fail to see a difference on whether it comes from a function or not.

(I'm aware this question is likely answered before, but my searches only came up with the linker error "undefined reference")

The code at fault was receiveMessage( action->second->message() );

Upvotes: 0

Views: 103

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254741

What could I be/am I likely doing wrong?

You're not posting the code that causes the error, meaning that we can only guess what's wrong.

Most likely, you're trying to pass a temporary object - the result of a function call or other expression - to the function. The function takes a non-const lvalue reference, which can't be bound to a temporary.

Solutions:

  • Change the function to take a reference to const: receiveMessage(Message const &). This is only an option if the function doesn't need to change it.
  • Pass a named variable rather than a temporary object.

Upvotes: 2

Related Questions