C ++: passing a string literal of type const char * to a string parameter

I am new to C ++ and don't understand why this code works well:

string GetString(string promt)
{
    cout << promt << ": ";
    string temp;
    getline(cin, temp); 
    return temp; 
}

int main()
{
    string firstName = GetString("Enter your first name"); 
    string lastName = GetString("Enter your last name");

    cout<< "Your Name is: " << firstName << " " << lastName; 


    cin.ignore(); 
    cin.get(); 

    return 0;
}

String literals of type "bla" are of type const char *. At least auto i = "bla"; indicates that I have type "const char *". Why can I pass it to the GetString function because the function expects a string and not a char * constant?

+5
source share
2 answers

std::stringhas a conversion constructor that takes char const*and initializes a string with a null terminated string that the pointer points to. This constructor is not explicit, so it can be used in implicit conversions.

+8
source

std::string. , , , const char * convrt const char * to std::string. , const std::string& prompt.

+1

All Articles