5

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*?

1
  • 1
    String literals are of type const char(&)[N], but since C can't copy an array to the local variable, auto makes the local const char* anyway. Commented Aug 30, 2012 at 0:23

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Look at the std::string constructors. What happens is that compiler found a constructor that accepts your const char* and used it to automatically convrt const char* to std::string. BTW I would suggest using const std::string& prompt instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.