Be a Supporter!
Momo-the-Monkey
Momo-the-Monkey
  • Member since: Oct. 15, 2005
  • Offline.
Forum Stats
Member
Level 45
Musician
C++ char* s help Mar. 14th, 2013 @ 08:38 PM Reply

I'm having a little difficulty understanding why this is the way it is in C++.

char *s;
s = "some string";
cout <<	 s;

Why doesn't the assignment in the second or the reference in the third line need the * like regular pointers? Thanks in advance.


Hello, from the past!
[ PHP: Main ]

BBS Signature
Momo-the-Monkey
Momo-the-Monkey
  • Member since: Oct. 15, 2005
  • Offline.
Forum Stats
Member
Level 45
Musician
Response to C++ char* s help Mar. 14th, 2013 @ 08:44 PM Reply

So I understand that the compiler replaces the string with a pointer, which explains the second line, but I still don't understand why the third line doesn't need the *.


Hello, from the past!
[ PHP: Main ]

BBS Signature
Diki
Diki
  • Member since: Jan. 31, 2004
  • Offline.
Forum Stats
Moderator
Level 13
Programmer
Response to C++ char* s help Mar. 14th, 2013 @ 09:40 PM Reply

At 3/14/13 08:38 PM, Momo-the-Monkey wrote: Why doesn't the assignment in the second or the reference in the third line need the * like regular pointers? Thanks in advance.

Because you only need to use * when you are declaring a pointer, not when you are assigning a value.
When you are doing:

char *s;

You're declaring a char pointer with the name "s", and when you do:

s = "somestring";

The compiler already knows that "s" is a char pointer, so it will accept any char pointer as an r-value for the assignment operator, which is precisely what is being given.

At 3/14/13 08:38 PM, Momo-the-Monkey wrote: cout << s;

This is actually a function, not an assignment; cout is just a variable, and is an instantiation of the ostream class.
In that example cout is using << as an overloaded operator like this:

void ostream::operator << (const char *str) {
  // Do fancy stuff with the string
}

So when you use << on cout that function ends up being called, and the r-value is passed to that function.

Momo-the-Monkey
Momo-the-Monkey
  • Member since: Oct. 15, 2005
  • Offline.
Forum Stats
Member
Level 45
Musician
Response to C++ char* s help Mar. 15th, 2013 @ 12:10 AM Reply

Somehow I knew that I just didn't make the connection, haha. Thanks for clearing that up Diki.


Hello, from the past!
[ PHP: Main ]

BBS Signature