Why const reference string

Hi everyone,
I just wrote this piece of code to test something, but it didn't go through the GCC-compiler because of the following error:

C:\Project\TESTS\QtCreator_Pro\Constructers\main.cpp:22: ERROR: invalid initialization of non-const reference of type 'std::__cxx11::string& {aka std::__cxx11::basic_string<char>&}' from an rvalue of type 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}'
Person pers{"Manu", 2500};




class Person{
public:
Person(std::string &n, double sal): name{n}, salary{sal}
{

}
private:
std::string name;
double salary;
};


int main()
{
Person pers{"Manu", 2500};
return 0;
}


Please consider the first parameter of the constructor. It is a non-const. the code would not work unless I turn this parameter to const reference: Person(const std::string &n, double sal) or
I declare it just as a value, not as a reference: Person(std::string n, double sal).
But why ist that so? although readed the error-massage it is still not obvious to me why I need a const reference to string in my constructor in order to make my object like shown in the main function: Person pers{"Manu", 2500};
can anyone teach me about this issue or about constructors, references, or strings in this particular contex?

Thanks a lot.
Last edited on
is not why you need a const reference, but why do you need a non-const reference
when you write void function(Foo &object); you are saying to the user (the programmer) that you will modify `object', that whatever function() does it will affect its parameter
now, ¿why does the Person constructor want to modify `n'?

your error is similar to int &n = 42; you can't create a non-const reference to a temporary
Topic archived. No new replies allowed.