Reputation: 19
What is the difference between these two string initializations in c++? i get the same output in both the programs. Program 1
void main(){
string a = "hello";
cout<<a;
}
program 2
void main(){
string a = (char *)"hello";
cout<<a;
}
Upvotes: 1
Views: 236
Reputation: 512
std::string
is a typedef for a specialization of basic_string
class templated on a char
(objects that represent sequences of characters).
The expression string a = "hello"
corresponds to a stream of characters whose size is allocated statically.
Short, simple and typesafe std::cout
is a typedef of ostream
class templated on standard objects (provides support for high-level output operations).
cout
means "the standard character output device", and the verb <<
means "output the object".
cout << a;
sends the string like a stream to the stdout
.
char *
are special pointers to a constant character, they point to ASCII strings e.g.:
const char * s = "hello world";
The expression (char *)"hello"
corresponds to a char *
pointer, where you are casting away const
, but then the constructor immediately puts the const
back on the call.
cout
, therefore, will print a string because it has a special operator for char *
wich it will treat as a pointer to (the first character of) a C-style string that outputs strings.
char*
or const char*
, cout
will treat the operand as a pointer to (the first character of) a C-style string, and prints the contents of that string:
Upvotes: 0
Reputation: 19757
"hello"
is a string literal. Its type is
const char[N]
, whereN
is the size of the string [...] including the null terminator.
So in this case, the type is const char[6]
. Note the const
.
Now std::string
can be constructed (constructor 5 in the link) from a const char*
. Again, note the const
.
In C++, you can pass a non-const
object into a function that expects a const
. In your case, your cast (char *)
removes the const
, but then immediately puts the const
back on in the constructor call.
So basically, no difference. They will compile to exactly the same thing.
A few additional notes:
const
-ness is very dangerous. If you had actually tried to change anything in the char
array, your program would have had Undefined Behaviour.using namespace std;
is widely considered to be bad practice.void main()
is not a valid signature for the main
function; it must return an int
.C
-style casts in C++
can also be considered a bad practice - it is harder to spot in code, and C++
provides safer equivalents for more specific situations: const_cast
, static_cast
, dynamic_cast
, and (the most dangerous) reinterpret_cast
.Upvotes: 5
Reputation: 12732
Nothing actually, that additional char *
type casting is not needed.
In both the cases copy initialization is done.
string (const char* s);
read more on copy initialization
Upvotes: 4