3

How come when using the string object for variables and parameters you need to have #include <string>, but you don't need it for string literals? For example, you can say cout << "This is a string literal"; without #include <string>.

I am learning C++ using a Deitel Brothers book and came up with this question when learning character arrays.

4
  • The library provides an overloaded binary operator << for std::ostream& and const char * (which, btw, can sometimes rear unexpectedly). Commented Jun 9, 2019 at 21:09
  • Sidenote: Deitel father and son if I remember correctly. Commented Jun 9, 2019 at 21:11
  • 10
    String literals are not strings. They are constant arrays of characters. Commented Jun 9, 2019 at 21:12
  • ...and std::cout is designed to print arrays of characters as strings. Commented Jun 9, 2019 at 21:14

2 Answers 2

9

A string literal is not a std::string object, it's an array of const char.
"This is a string literal" has the type const char[25].

In most situations – including this one – an array implicitly decays into a pointer to its first element, and there is an operator<< overload for const char*.

It's pretty confusing that "string" means several different things in C++, but after a while (and pulling of hair and gnashing of teeth) the intended meaning will be clear from context.

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

2 Comments

Fwiw, you can use "foo"s to get string, string literal
@NathanOliver yes, but to use that syntax, you need C++14 or later, and still require #include <string>
3

A string literal like "This is a string literal" is of type const char[25], not of type std::string. Statement cout << "This is a string literal" actually calls operator <<(ostream&, const char*), and the string literal parameter decays to type const char*. There isn't any std::string involved in this case.

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.