JohnnyFaldo
JohnnyFaldo

Reputation: 4161

Why does C++ allow a char array as an argument when it's expecting a string?

I have the following code:

#include <iostream>
#include <string>

using namespace std;


string combine(string a, string b, string c);

int main() {

    char name[10]   = {'J','O','H','N','\0'};
    string age      = "24";
    string location = "United Kingdom";


    cout << combine(name,age,location);

    return 0;

}

string combine(string a, string b, string c) {
    return a + b + c;
}

This compiles fine with no warnings or errors despite the combine function expecting a string and receiving a char array, is this because a string is stored as a char array?

Upvotes: 1

Views: 140

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361252

Why does C++ allow a char array as an argument when it's expecting a string?

Because std::string has such a conversion constructor, which supports implicit conversion of char const* into std::string object.

This is the constructor which is responsible for this conversion:

basic_string( const CharT* s, const Allocator& alloc = Allocator());

Have a look at the documentation and other constructors.

Upvotes: 5

john
john

Reputation: 87944

It's because there is an automatic conversion from a char array to a string.

string has a constructor like this (simplified)

class string
{
public:
    string(const char* s);
    ...
};

This constructor can be called automatically, so your code is equivalent to this

cout << combine(string(name),age,location);

Upvotes: 1

Related Questions