Null character and string object

This is a discussion on Null character and string object within the C++ Programming forums, part of the General Programming Boards category; Hi folks, Just a quick question: what is so illegal about the following line of code? That is, why would ...

  1. #1
    Registered User
    Join Date
    Oct 2003
    Posts
    9

    Null character and string object

    Hi folks,

    Just a quick question: what is so illegal about the following line of code? That is, why would it throw an exception?

    Code:
    std::string someStr='\0';
    If I define someStr first, and then assign the null character second, I have no problem. Why is this? Aren't the two equivalent, but I've just shifted the assignment down a bit?

    Thanks,
    -Jeb.

  2. #2
    Registered User
    Join Date
    Sep 2003
    Posts
    135
    You can't initialise an std::string with a character in that way. If you really need to you should be able to do the following:

    std::string someStr(1,'\0');

    Note that in C++ initialisation and assignment are two very different things.

  3. #3
    Disturbed Boy gustavosserra's Avatar
    Join Date
    Apr 2003
    Posts
    244
    The assignment operator is overloaded to receive a string as parameter. Is like having a function:
    void f(char *str);
    and use it passing a char.
    Nothing more to tell about me...
    Happy day =)

  4. #4
    Registered User
    Join Date
    Oct 2003
    Posts
    9
    Omnius: Thankyou, what you told me coupled with a bit of research of my own answered my question.

    gustavosserra: That's true, but after reading the definition for std::string I found that it's also overloaded for char, which would explain why I had no problems assigning the character later.

    Thanks for the help, both of you. Much appreciated.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. New string functions
    By Elysia in forum C Programming
    Replies: 11
    Last Post: 03-28-2009, 06:03 AM
  2. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 10:11 AM
  3. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  4. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 11:03 AM
  5. lvp string...
    By Magma in forum C++ Programming
    Replies: 4
    Last Post: 02-27-2003, 12:03 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21