You are misunderstanding the syntax for the function signatures:
Why does fstream::open() expect a const String/ const char* ? The filename could be obtained from anywhere (from a user, like in the example above), and making str into a const string doesn't help in that case.
The signatures are below for reference:
void open (const char* filename, ios_base::openmode mode = ios_base::in | ios_base::out);
void open (const string& filename, ios_base::openmode mode = ios_base::in | ios_base::out);
The first overload takes a const char*
(e.g. a pointer to a constant character array).
The second overload takes a const std::string&
(e.g. a reference to a constant std::string).
It is not a const std::string
, but a reference to a string. It is stating that the function will not modify the string, and you are passing a reference to the original (instead of copying it). You can pass a non-const string to a function that requires a const string without an issue (there is no conversion/cast required).
The answer to your original question (Why does it take a const char*
?) is not all that complicated: The stream libraries and the string libraries were developed in parallel by different groups of people. In the early standards, they didn't merge the development. That has been addressed in C++11.