user1203499
user1203499

Reputation: 267

c++ function parameter char pointer and string

void callme(string a)
{
  cout<<"STRING CALLED"<<endl;
}

void callme(char * a)
{
  cout<<"char pointer called"<<endl;
}

int main()
{
   callme("ASDADS");
   return 0;
}

why is it that the char* will be called? and why when I comment out the function with the char* parameter, the other function will be called instead?

Upvotes: 4

Views: 5766

Answers (4)

Kerrek SB
Kerrek SB

Reputation: 477660

The type of a string literal (like "abc") is "array of const char". However, as a special rule, C++ allows a (deprecated!) standard conversion to char *. Such a conversion is preferred over the user-defined conversion furnished by the constructor string::string(const char *). Thus the char* overload wins during overload resolution (zero user-defined conversions for char* as opposed to one user-defined conversion for string).

(I can't actually find a standard reference for this; on the contrary, C.1.1 says explicitly that char * p = "abc"; is "invalid in C++". Any further input is appreciated. Edit: It seems like this is a change from C++03 to C++11, and in C++11 this is indeed flat-out illegal.)

Upvotes: 3

Tejas Patil
Tejas Patil

Reputation: 6169

By default "ASDADS" is referenced by a char pointer. So 2nd version of callme() is used. If that is commented, compiler will try to match it with string and hence 1st version of callme() is used.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258688

That's because "ASDADS" is convertible to char *. The compiler thus generates code for the first function it can match the argument to.

If you remove the prototype with char *, the compiler will look for functions that accept a parameter with an implicit cast from char * to the parameter type.

Take the following for example:

class A
{
public:
    A() {}
    A(int x) {}
};

//void foo(int x) {}
void foo(A x) {}

int main(int argc, char* argv[])
{
    int x = 3;
    foo(x);
}

if you comment out foo(int x), the other function will be called.

However, if you declare the constructor as explicit, you'll get an error:

class A
{
public:
    A() {}
    explicit A(int x) {}
};

Upvotes: 4

perreal
perreal

Reputation: 98118

When you have both functions there are two alternatives to pick from and (char *) fits better to your argument "ASDADS". If you remove the (char *) function then there is a single function that wants a string. So the compiler creates a string using a string constructor that takes a char *.

http://www.cplusplus.com/reference/string/string/string/

Upvotes: 0

Related Questions