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?
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(constint &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