1

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?

2

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.