Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

i'm new to c++ and have a lack of understanding 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 like "bla" are of Type const char*. At least auto i = "bla"; indicates, that i is of Type "const char*". Why is it possible to pass it to the GetString-Function, because the function expects a string and not a const char*?

like image 766
Grundkurs Avatar asked Aug 30 '12 00:08

Grundkurs


People also ask

Can you assign a const char * to a string?

You absolutely can assign const char* to std::string , it will get copied though. The other way around requires a call to std::string::c_str() .

Is a string literal a const char *?

In C++, string literals are stored in arrays of const char , so that any attempt to modify the literal's contents will trigger a diagnostic at compile time.

Can a char * be passed as const * argument?

In general, you can pass a char * into something that expects a const char * without an explicit cast because that's a safe thing to do (give something modifiable to something that doesn't intend to modify it), but you can't pass a const char * into something expecting a char * (without an explicit cast) because that's ...

What is the difference between const char * and string?

1 Answer. Show activity on this post. string is an object meant to hold textual data (a string), and char* is a pointer to a block of memory that is meant to hold textual data (a string). A string "knows" its length, but a char* is just a pointer (to an array of characters) -- it has no length information.


1 Answers

std::string has a converting constructor which takes a char const* and initialised the string with the null terminated string pointed to by the pointer. This constructor is not explicit, so it can be used in implicit conversions.

like image 191
Mankarse Avatar answered Sep 30 '22 01:09

Mankarse