How to declare a varibale as null

I have a program where when I first initialize a CString varibale I want it to be null. I put this:

 
CString temp = "";


Will this make it null. Because when I put the code below, I get errors:

 
CString temp = NULL;

closed account (zwA4jE8b)
I believe your first way is correct. The empty string. I don't know about the CString datatype but when comparing strings you don't really compare NULL or not you compare to empty.
If you want to store a NULL value, you need to use pointers. There is no such thing as a NULL object (or reference) in C++.
In case you can overload the copy constructor for CString with arguments of a const char *. Inside that function, check if the passed argument is NULL or not, if it's NULL then initialize it with "" otherwise initialize it with the string provided.
How about something like this:

1
2
3
#define STR_NULL ""

std::string name = STR_NULL;
closed account (z05DSL3A)
TnGraham wrote:
I have a program where when I first initialize a CString varibale I want it to be null
What exactly do you mean by this? What do you believe null to be or signify?
I believe if you are a Java programmer, the null reserved keyword is a familiar term but in C++ I don't think so. I have seen code where C++ coder try to "simulate" by doing a #define null 0

Actually long long time ago the NULL macro exist correct? I use to do if (ptr!=NULL) ... where ptr is a pointer variable. Then later on I have seen code like if (ptr) ...

So are below two statements valid C++ code ?

if (ptr!=NULL)...

if (ptr)...
Yes, assuming NULL is defined. It is a standard macro, IIRC, defined as 0. Don't quote me on that though. In C++0x, I recall the nullptr keyword or something similar being introduced.
Actually just for curiosity sake, can it happen when the ptr variable do point to the memory address location 0 and there is valid value in that "space" then all hell break loose isn't ?

Unless for most OSes, certain memory address are off-limits to user programs which I believe will include 0x000000....

Hmmm... food for thought.
Assigning a pointer in C++ to be 0 doesn't need to be address 0x0 specifically, just any implementation-defined way such that it'll cause an error when dereferenced.
closed account (z05DSL3A)
What I was after (from the OP) is if the aim is to have an CString object with an empty string, in which case the default constructor should suffice i.e. CString temp; .

Or if they are thinking in terms of C# et al String str = null and they are delaying the instantiation of the object to a later time, in which case they would need a point to a CString set to null.
Last edited on
Topic archived. No new replies allowed.