Vihaan Verma
Vihaan Verma

Reputation: 13143

what are arguments defined in quotes

In some function calls I see stuff like this.

function(variable1, "someValue");

I have some questions based on this

1) How does c++ treat the second argument ?

2) if some function takes a cstring then why do we get error when we do the following

functionTakingCString(stringVariable.c_str() + "someValue");

Is there some way around instead of declaring a const char variable? Please correct me if I m wrong some where.

Upvotes: 2

Views: 131

Answers (4)

Paul Rubel
Paul Rubel

Reputation: 27222

The second argument is a const char*. In some cases you may be able convert from one type to another if you have a special converting constructor of the desired type that takes in the given type. The compiler can do this for you in some cases.

In this example string has a constructor that takes in a const char* so the compiler can turn a const char* into a string for you under the covers. If you want to stop this kind of behavior look into the explicit keyword.

The char* type isn't actually an class so it doesn't have a + operator that works for strings. However,

(stringVariable + "someValue").c_str()

will work because stringVariable is a string and it's plus operator can cooerce a char* into a string.

Upvotes: 0

Mahesh
Mahesh

Reputation: 34625

  1. const char*

  2. Binary operator + cannot be applied on const char* operand types. If one is a std::string, then it works because of operator overloading.

Upvotes: 1

Vikdor
Vikdor

Reputation: 24134

2) if some function takes a cstring then why do we get error when we do the following

That's because the '+' operator is not overloaded for char * type. You could concatenate it to stringVariable of type string for which the + operator has been overloaded to concatenate two strings, and then get the c_str() to pass to a function accepting char * or const char *.

Upvotes: 2

Tony The Lion
Tony The Lion

Reputation: 63200

They are called string literals and if you want to take an argument that is a string literal like that you normally pass a const std::string& or a const char*, depending on what your API requires.

Upvotes: 3

Related Questions