Constructors and reference parameters

I wrote a simple code that passes a parameter to constrcutor as a reference,but i'm getting compile time erros

// TestConstructor.c++
#include <iostream>

class base{
public:
base(int &a)
{
std::cout << "single param constructor";
}

base(const base &a)
{
std::cout << "copy constructor";
}

};
int main(){
base b(2); // shows error
base b1(b);
}

I'm using g++ compiler and it throws following errors:
TestConstructor.c++: In function ‘int main()’:
TestConstructor.c++:17: error: no matching function for call to base::base(int)’
TestConstructor.c++:10: note: candidates are: base::base(const base&)
TestConstructor.c++:6: note: base::base(int&)

I'm able to fix the error by changing first constructor to

base(const int &a)
{
std::cout << "single param constructor";
}

but i can't understand why compiler complained at the first place? and why is my modified code working?
There was just a template error thread like this the other day. You can't pass a non-const reference to a temporary (or literal).

1
2
int n = 2;
base b(n); // should work 

Last edited on
You can't have a non-const reference to an rvalue because you can't change its value. Incidentally, for very small objects such as an int, there's nothing to gain by passing by reference.
The code works with base(const int &a) because the compiler is able to implicitly construct an int for the 'const & int' param from the literal value '2'. The reason it's able to do this is that the 'const' guarantees the int referenced won't actually be modified. Without that, the compiler has to expect that the value of the passed in integer might be modified in the constructor, such that saying

 
a = 5;

is similar to saying

 
2 = 5;


--Rollie
Thanks for the answers and the explanation.
Topic archived. No new replies allowed.