tags:

views:

174

answers:

3

Further in my code, I check to see check if an object is null/empty. Is there a way to set an object to null?

+9  A: 

An object of a class cannot be set to NULL; however, you can set a pointer (which contains a memory address of an object) to NULL.

Example of what you can't do which you are asking:

Cat c;
c = NULL;//Compiling error

Example of what you can do:

Cat c;
//Set p to hold the memory address of the object c
Cat *p = &c;
//Set p to hold NULL
p = NULL;
Brian R. Bondy
as an aside for whoever wants to bring it up, yes you can overload operator= but this is not what the OP wants.
Brian R. Bondy
The 1st could work with `Cat::operator=(...)`. Anyway, looks like OP really wants to check a pointer. So, +1.
jweyrich
@jweyrich: I knew someone would say that so see my comment before your comment :)
Brian R. Bondy
@Brian: sorry, I didn't update the page before posting my comment. It was just for the sake of completeness. Glad you mentioned :)
jweyrich
+2  A: 

You can set any pointer to NULL, though NULL is simply defined as 0 in C++:

myObject *foo = NULL;

Also note that NULL is defined if you include standard headers, but is not built into the language itself. If NULL is undefined, you can use 0 instead, or include this:

#ifndef NULL
#define NULL 0
#endif

As an aside, if you really want to set an object, not a pointer, to NULL, you can read about the Null Object Pattern.

Justin Ardini
+1  A: 

Hi John,

You want to check if an object is NULL/empty. Being NULL and empty are not the same. Like Justin and Brian have already mentioned, in C++ NULL is an assignment you'd typically associate with pointers. You can overload operator= perhaps, but think it through real well if you actually want to do this. Couple of other things:

  1. In C++ NULL pointer is very different to pointer pointing to an 'empty' object.
  2. Why not have a bool IsEmpty() method that returns true if an object's variables are reset to some default state? Guess that might bypass the NULL usage.
  3. Having something like A* p = new A; ... p = NULL; is bad (no delete p) unless you can ensure your code will be garbage collected. If anything, this'd lead to memory leaks and with several such leaks there's good chance you'd have slow code.
  4. You may want to do this class Null {}; Null _NULL; and then overload operator= and operator!= of other classes depending on your situation.

Perhaps you should post us some details about the context to help you better with option 4.

Arpan

Fanatic23
"Why not have a bool IsEmpty() method ..." - there are some good reasons not to. The most important one is that it's typically contex-dependent whether it makes sense. A more robust solution is to use `boost::optional<T>` to indicate whether you have a valid T object or not. This will prevent you from calling `x.foo()` when `x.IsEmpty()==true`
MSalters