PDA

View Full Version : checking for null



drkbkr
10th March 2006, 21:53
This may be a ridiculous question. And it may be just a C++ question. But I am totally lost here.

I would think that if I have declared an object, say a QListView, in a header file, but have not yet initialized that object, I could test for that declared but not initialized state with


if(sequenceList == NULL)

where sequenceList is the name of my QListView. But it is always returning false, whether initialized or not. I've also tried:


if(sequenceList == null)

and


if(sequenceList == 0)

What am I doing wrong here? Any help would be greatly appreciated.

Thanks,
Derek

fullmetalcoder
10th March 2006, 22:04
This may be a ridiculous question. And it may be just a C++ question. But I am totally lost here.

I would think that if I have declared an object, say a QListView, in a header file, but have not yet initialized that object, I could test for that declared but not initialized state with


if(sequenceList == NULL)

where sequenceList is the name of my QListView. But it is always returning false, whether initialized or not. I've also tried:


if(sequenceList == null)

and


if(sequenceList == 0)

What am I doing wrong here? Any help would be greatly appreciated.

Thanks,
Derek

Depends on your compiler but pointers are rarely set to 0. You've got to do it in the constructor:



SomeClass::SomeClass(...)
: sequenceList(0)
{
//other stuff
}


which is the same as :



SomeClass::SomeClass(...)
{
sequenceList = 0;
//other stuff
}

yop
10th March 2006, 23:11
Depends on your compiler but pointers are rarely set to 0.It is undefined to what value they will be set. They could be zero or not there is no default value.

which is the same as :It's not exactly the same, better initialize to rather than assign the default values http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6

Bojan
11th March 2006, 00:11
Strictly speaking, in C++, a null pointer is 0, not 0l, 0L, null, or NULL. It's just something to be aware of, since 0 is usually the convention, and also some people feel pretty strongly about it. :/

Bojan

Michiel
13th March 2006, 11:12
NULL is simply a macro that will be replaced with 0 by the preprocessor. I think it's more clear. Pointers can be NULL. Integers can be the numeric value 0.

dublet
13th March 2006, 11:42
Strictly speaking, in C++, a null pointer is 0, not 0l, 0L, null, or NULL. It's just something to be aware of, since 0 is usually the convention
Depends which books you read. I always use NULL.

And holy wars have started about less. ;)

duanehebert
13th March 2006, 22:54
In c++ a pointer is only 0 if you set it to 0. You can do this in the initializer list.
You would also need to do it after any delete.

Qt provides a QPointer that starts "nulled", gets "nulled" after a delete
and has a member isNull().