Alex Rivera | Logout

C++ cannot convert 'const char*' to 'std::string*'

Asked 2011-05-13T13:55:02.880
11

I have this code below and I'm getting the error upon compilation:

error: cannot convert 'const char*' to 'std::string*' for argument '1' to 'void sillyFunction(std::string*, int)'

#include <iostream>
#include <string>

using namespace std;
int counter = 0;

void sillyFunction(string * str, int cool=0);

int main(){
    sillyFunction("Cool");
    sillyFunction("Cooler", 1);
    return 0;
}

void sillyFunction(string * str, int cool){
    counter++;
    if (cool){
        for (int i=0; i<counter; i++) cout << *str << endl;
    } else {
        cout << *str << endl;
    }
}
Edit
Report

1 Answer

1

You can acheive that by changing the prototype to:

void sillyFunction(string const &str, int cool=0);

char const * could be implicitly converted to a temporary std::string, which in turn could be passed by reference (std::string const &). There's no implicit conversion to a pointer (std::string *), that's why you get the error.

answered 2011-05-13T13:58:13.550

Your Answer