C++ cannot convert 'const char*' to 'std::string*'
Don't take your parameter in as a string *
try just using a const string &
instead
EDIT:
std::string
and const char*
are different types. the std::string
already has a conversion from string literals (ex: "Cool"
) to the actual string object. So by passing in the string literal "Cool"
you are in a sense passing in a std::string
object, not a pointer to one.
The reason I chose to use a const string &
is mostly from personal coding practices. This minimizes stack memory usage, and since you are passing in a constant string literal, there is no need for the parameter to be modify-able.
Also don't forget if you change from a string *
that you no longer need to dereference it in your cout
:
if (cool){
for (int i=0; i<counter; i++) cout << str << endl;
} else {
cout << str << endl;
}
change
void sillyFunction(string * str, int cool){
counter++;
if (cool){
for (int i=0; i<counter; i++) cout << *str << endl;
} else {
cout << *str << endl;
}
}
to
void sillyFunction(const char* str, int cool){
counter++;
if (cool){
for (int i=0; i<counter; i++) cout << str << endl;
} else {
cout << str << endl;
}
}
To explain what the problem actually is...
While the compiler will happily arrange for a char *
/C-string to be "converted" to a std::string
via the appropriate std::string
constructor, that's not what you've asked for.
You have asked for a pointer to an existing std::string
object. By definition, what is passed to your function must be the address of an already existing std::string
(or descendant) object.
You must understand pointers as a distinct type -- your function takes a pointer-to-std::string
"object". While a std::string
can be accessed via a pointer to std::string
, the pointer itself is not a std::string
, nor can it be "converted" to a std::string
, nor can it be treated as a pointer-to-char (or vice-versa).
The easiest alternative is indeed a const reference to a std::string
(const std::string &
). const, in this case, because you're not doing anything to modify the string. If you were, that would be a different matter, and you'd have to consider carefully whether you intend for the caller to see your changes.
By doing this, you're saying you want a std::string
object (remember, a reference to an object is that object, see C++ FAQ 8.5 in particular), which allows the compiler to invoke the appropriate constructor to create a std::string for you when the function is called with a char *
(const or not).
At the same time, if someone passes you an actual std::string
, the constructor is avoided and you get the same efficiency as if you had taken a pointer-to-std::string
. Win-win.
Alternatively, of course, you can just take a plain std::string
, but in that case you always get a copy of the string being passed in, whether it's a C-string or a std::string
. Sometimes that's desirable, sometimes not. In your case, you don't do anything but print the string out, making the overhead unnecessary.