string a=NULL;
it gives error. Why and how can I initialize string as NULL?
but when I write
string a="foo";
this it works fine.
Actually to get an empty std::string, you just write
std::string a;
std::string's default constructor will give you an empty string without further prompting.
As an aside, using NULL in C++ is generally discouraged, the recommendation would be to either use 0 (which NULL tends to be defined to anyway) or if you have a modern enough compiler, nullptr.
nullptr will be UB, as it will try to construct a std::string from a null pointer, which is not allowed by the Standard.NULL is discouraged in pre-nullptr C++... in practice it's the same as 0 (it's guaranteed to be defined as 0), and it makes more clear that we are talking about pointers.foo(int) because I know that NULL is plain zero. But if I make the mistake and later someone else notices that the wrong overload is called he can immediately understand what I meant and add the relevant cast (otherwise he would have to ask me if I meant "integer zero" or "pointer zero"). I agree that NULL is a botch - nullptr was introduced for a reason, but I feel it's better than using 0 also for pointers. Anyway, all this is both non relevant to the question (I'm sorry for derailing it) and non relevant in general now that nullptr solves this problem.There is a difference between null and empty string (an empty string is still a valid string). If you want a "nullable" object (something that can hold at most one object of a certain type), you can use boost::optional:
boost::optional<std::string> str; // str is *nothing* (i.e. there is no string)
str = "Hello, world!"; // str is "Hello, world!"
str = ""; // str is "" (i.e. empty string)
Let's break down what you are in fact doing:
string a=NULL;
First you execute string a. This creates a new object on the stack, with default value (an empty string). Then you execute a=NULL, which calls the assignment function of the string class. But what is NULL? NULL in C++ is macro expanded into just 0. So you are attepting to assign an integer to a string variable, which of course is not possible.
string a="abc"
works, because you want to assign a char array, and the string class has the assignment operator method overloaded for char arrays, but not for integers. That's why NULL doesn't work and "abc" works.
NULL is defined as ((void*)0) but in C++ its just 0.(void*)0 - which means a pointer to 0; not am integer representation of 0. In C++ I think it largely depends on the compiler.
NULLto it, but dont forget to use properlynewanddeletestring a;?