basic string question

P

pauldepstein

string word = 'a' ; is illegal code.

However, string word;
word = 'a';

is legal.

What is the difference? The 2nd one doesn't even generate a warning on
my bloodshed dev c++ compiler, set on maximum warning level.

I understand why the first example is illegal. But I'm surprised at
the legality of the second one.

(By the way, I'm not sure what to make of Red Floyd's earlier
read-the-FAQ message. Is anything wrong with any of my postings?)

Thank you,

Paul Epstein
 
F

Frederick Gotham

posted:
string word = 'a';


This is an initialisation. It's equivalent to:

string word( string('a') );

which, depending on whether the type has a public copy-constructor, might
be equivalent to:

string word('a');

string word;
word = 'a';


This is assignment -- a different animal altogether.

Your question is basically this:

How come I can assign a char to a string, but yet I can't use a char to
initialise a string?

The answer is:

Because that's just the way "string" was designed.

Perhaps someone else would like to explain why such a design was chosen
(I'd do so myself but I've very little experience with string, vector,
etc.)
 
T

tolgaceylanus

Because basic_string does not have a constructor which takes a char.
However, it
does have an assignment operator that takes a single char. I guess this
is
some sort of minor design inconsistency since we do have an single char
assignment
operator, but not a single char constructor.

Hope this helps,

Tolga Ceylan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top