Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to set an object to null?

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?

like image 323
John Avatar asked Jun 13 '10 02:06

John


People also ask

Can I set an object to null Java?

Firstly, you never set an object to null. That concept has no meaning. You can assign a value of null to a variable, but you need to distinguish between the concepts of "variable" and "object" very carefully.

Does null mean no object?

Description. The value null is written with a literal: null . null is not an identifier for a property of the global object, like undefined can be. Instead, null expresses a lack of identification, indicating that a variable points to no object.

How do you give null in C++?

We can use nullptr to explicitly initialize or assign a pointer a null value. In the above example, we use assignment to set the value of ptr2 to nullptr , making ptr2 a null pointer. Use nullptr when you need a null pointer literal for initialization, assignment, or passing a null pointer to a function.


2 Answers

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; 
like image 109
Brian R. Bondy Avatar answered Sep 17 '22 18:09

Brian R. Bondy


While it is true that an object cannot be "empty/null" in C++, in C++17, we got std::optional to express that intent.

Example use:

std::optional<int> v1;      // "empty" int std::optional<int> v2(3);   // Not empty, "contains a 3" 

You can then check if the optional contains a value with

v1.has_value(); // false 

or

if(v2) {     // You get here if v2 is not empty } 

A plain int (or any type), however, can never be "null" or "empty" (by your definition of those words) in any useful sense. Think of std::optional as a container in this regard.

If you don't have a C++17 compliant compiler at hand, you can use boost.optional instead. Some pre-C++17 compilers also offer std::experimental::optional, which will behave at least close to the actual std::optional afaik. Check your compiler's manual for details.

like image 29
Baum mit Augen Avatar answered Sep 20 '22 18:09

Baum mit Augen