Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

about c++ conversion : no known conversion for argument 1 from ‘[some_class]' to ‘[some_class]&’

Tags:

c++

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!

like image 240
user430926 Avatar asked Nov 27 '13 16:11

user430926


2 Answers

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.

like image 129
juanchopanza Avatar answered Sep 24 '22 09:09

juanchopanza


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.

like image 38
Ivaylo Strandjev Avatar answered Sep 22 '22 09:09

Ivaylo Strandjev