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?
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.
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.
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.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With