I'm working on C++, and had an error that I didn't know the exact reason. I've found the solution, but still want to know why.
class Base { public: void something(Base& b){} }; int main() { Base b; b.something(Base()); return 0; }
when I compile the code, I got this following error :
abc.cpp:12:20: error: no matching function for call to ‘Base::something(Base)’ abc.cpp:12:20: note: candidate is: abc.cpp:6:7: note: void Base::something(Base&) abc.cpp:6:7: note: no known conversion for argument 1 from ‘Base’ to ‘Base&’
but when I replaced b.something(Base()) into
Base c; b.something(c);
the error is gone, I'm wondering why??? aren't they have the same type? It only matters how I write it, but the meaning should be the same???
Thanks Guys!
You are passing a temporary Base
object here:
b.something(Base());
but you try to bind that to a non-const lvalue reference here:
void something(Base& b){}
This is not allowed in standard C++. You need a const
reference.
void something(const Base& b){}
When you do this:
Base c; b.something(c);
you are not passing a temporary. The non-const reference binds to c
.
In the first case you attempt to pass a (non-const)reference to a temporary as argument to a function which is not possible. In the second case you pass a reference to an existing object which is perfectly valid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With