0

what is the difference between initializing the string in the following ways?

string s = "Hello World"; 

and

string s[] = {"Hello World"}; 

From what i understand the former is a class? And the latter an array? Moreover, are there any other ways apart from these two?

3
  • 3
    The title has nothing to do with the content of the question... Commented Dec 15, 2015 at 13:16
  • std::string s[] - is an array of strings. The two lines are not equivalent. Commented Dec 15, 2015 at 13:18
  • I think you meant std::string s = "hello world"; and std::string s { "hello world" }; the latter is brace initializer and an encouraged way in modern C++. The first one will trigger move assignment (if available) the latter one will use appropriate constructor. Commented Dec 15, 2015 at 13:44

3 Answers 3

6

In the first example, you define one object of class string. In the second, you declare an array of strings of undefined length (computed by compiler, based on how many objects you define in the initializer list) and you initialize one string object with "Hello World." So You create an array of size 1.

string s = "Hello World"; string s2[] = {"Hello World"}; 

After this, s and s2[0] contains strings with identical characters in them.

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

2 Comments

is string s[] = {"Hello World"} the same as char* s = "Hellow World" and char s[] = {"Hello World"}?
@mur It is not. You should read some beginner info about std::string and how it differs from C strings (char* and const char*)
1

Statement

string s = "Hello World"; 

creates an object of class std::string from a string literal, while

string s[] = {"Hello World"}; 

creates an array (of length 1) of std::string objects.

Other ways to construct a string from a string literal are the following:

string s("Hello World"); // using old style constructor call string s {"Hello World"}; // using new brace initializer (preffered way) 

Comments

0
#include <string> #include <iostream> using namespace std; int main(void) { // C-style string; considered "deprecated", better use string class char *s1 = "Hello World"; cout << s1 << endl; // Copy constructors string s2 = "Hellow World"; cout << s2 << endl; string s3("Hello World"); cout << s3 << endl; string s4{"Hello World"}; // C++11, recommended cout << s4 << endl; // Move constructor; C++11 string s5 = move("Hello World"); cout << s5 << endl; return 0; } 

This defines an array of type string and contains exactly one string element representing the Hello World character sequence.

string s[] = {"Hello World"}; // array of string; not a string by itself 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.