50

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!

user430926
  • 4,017
  • 13
  • 53
  • 77

2 Answers2

45

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.

urelement
  • 103
  • 2
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
2

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.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176