Is it possible to set an object to null? - c++

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?

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" 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 should behave at least close to the actual std::optional. Check your compiler's manual for details.

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.

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:
In C++ NULL pointer is very different to pointer pointing to an 'empty' object.
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.
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.
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

"an object" of what type?
You can certainly assign NULL (and nullptr) to objects of pointer types, and it is implementation defined if you can assign NULL to objects of arithmetic types.
If you mean objects of some class type, the answer is NO (excepting classes that have operator= accepting pointer or arithmetic types)
"empty" is more plausible, as many types have both copy assignment and default construction (often implicitly). To see if an existing object is like a default constructed one, you will also need an appropriate bool operator==

Related

What is the most efficient way to test if a pointer is null?

What is most efficient between the two ways of testing pointer nullity : if(pointer==NULL) or if(!pointer).
MyObject* p;
[...]
// Solution 1
if ( p )
{ // Do something
}
// Solution 2
if ( p!=NULL )
{ // Do something
}
It makes no difference what so ever. It's purely a style issue what you prefer.
By the way, you should use nullptr rather than NULL if you use C++11 or later.
I prefer if (ptr) because:
It is short and clear
It doesn't depend on NULL keyword. Which have to be nullptr on C++11 or later as Jesper Juhl mentioned.
From SoapBox's comment on stackoverflow:
They are compatible with C++ classes such as auto_ptr that are objects that act as pointers and which provide a conversion to bool to enable exactly this idiom. For these objects, an explicit comparison to NULL would have to invoke a conversion to pointer which may have other semantic side effects or be more expensive than the simple existence check that the bool conversion implies.
Those are same. It makes no change in your program whatever you use.
I'd rather prefer the if (p!=NULL) as it prevents form accidental errors like casting the p in other thing, like an int for instance, between the declaration and the use of it.
Here the compiler should warn as int differ form NULL (initially NULL=(void*)0)
Furthermore i prefer to declare like this :
MyObject* p=NULL;
because you cannot assure that p wont have a value different of zéro. If you miss to instantiate it between declaration and use.
And it is less misleading than the
if (p==NULL){} else {} which may occur in an accidental assignment (only one =)
Off course in the C++11 or later this could involve some changes in your code even if the call of NULL is still working but deprecated.

return by reference or pointer and check for null?

I have a class :
class A
{
private:
vector<int> x;
public:
const vector<int>& immutable_data() {
return x;
}
vector<int>* mutable_data() {
return &x;
}
}
Now if i use this class , in my code , do i have to check if the pointer returned by the mutable_data() is null or not (given that i know the structure of this class). Personally i think i don't have to because i know there exist a secondary api which returns a const reference and so my pointer can never be null (I can't imagine of a scenario where this function would return me null ,even if it somehow does returns null, what would be the behavior of the const ref version in that case). Or should i say that i know its an address of an existing object on stack , so it cannot be null ? Is this the correct way to think or reason about this ? If any one thinks the other way , please give some example code.
For a more common case scenario in production code : if i use protocol buffers , i already know the generated code for my message templates (for eg: repeatedfields which are like stl containers), but do i still need to do null check every time i want to use the mutable api because they always return either by pointer or const reference.
returning by reference is not what i am looking for.
do i have to check if the pointer returned by the mutable_data() is null or not (given that i know the structure of this class)
In general, design elements like "have to check the pointer" depends on one of two things:
Does your design need to be provably safe?
If not, then does the design of A::mutable_data() dictate that it won't return null?
If (1), then you should invest in the kind of SAT-solver based tools which can test statically that your code won't access invalid memory.
If (2), I recommend that you consider the concept of Design by Contract -- it is a powerful one. If A::mutable_data()'s interface is specified not to return null, then it returning null would be a design defect in A::mutable_data().
Returning a null pointer usually means "I don't have any data for you". If the class will always have data, then, by design, the function will never return a null pointer. If that's the case, then code that uses the function does not need to check for null pointers. That's one of the guarantees that the function makes: "I won't ever return a null pointer".

Test for a null pointer value in C++

It's not clear for me how can i do that in C++. In Objective-C I can check a object in this way
if (myValue != [NSNull null]) { … }
myValue is compared with a null object (returned by class method), so this works great , if object has a value, even nil, if statement will return true.
So question is how to test correctly for a null pointer value, i did this way
if (myValue != NULL)
{
qDebug() << "It is not null";
}
but it is not working.
In C++ there's really no concept of null value, only null pointers. You can't compare something that isn't a pointer to NULL.
A pointer in C++ essentially contains an address to some memory location where you object or data is stored. In this case, a "NULL Pointer" is just an empty memory address. This is represented as a zero value. So to check it, you would write something like this:
SomeClass *someClassPointer = // ... call some method to get pointer
// Check for null pointer
if (someClassPointer == 0)
{
// Pointer is null
}
This can be simplified by doing this:
if (someClassPointer)
{
// For checking that the pointer is not null
}
if (!someClassPointer)
{
// For checking that a pointer is null
}
Short answer: it depends.
Longer answer: First of all you can not compare a reference (if the type of myValue is something like T&) nor stack allocated objects (if myValue is just T) for null - these types are always allocated and not null (unless you screw up your stack or do other bad stuff - but you won't check for these cases, because than you will have bigger problems).
The only types you can check for null are pointers (myValue is something of type T*). For those types:
if you use C++98, you can check against 0. NULL is usually just a macro (#define NULL 0).
if you use the new C++11 there is a new nullptr keyword and you should check against this one.
Since 0 evaluates to false and anything else to true, you can also just use the pointer like a normal bool. A nullptr is of type nullptr_t and has operator bool() implemented - so you also can this one like you would use a bool.
In general: in C++98 the lack of nullptr is a source of errors, so if you can use C++11, ALWAYS use nullptr - never use NULL or 0 (int is just the wrong type to assign to a pointer or to compare with a pointer - if you have overladed methods you will run into problems since the compiler would use a method with an int parameter instead of a pointer type if it is suitable).
Let's assume you have two functions:
void foo(int a);
void foo(void *);
If you now call
foo(NULL);
the first function will get called (what probably is not what you want. So in C++11 you would write:
foo(nullptr);
while in C++98 you would have to write:
foo((void *)0);
This is one reason why the lack of null is/was a big issue before C++98. If you want to have something similar than in Objective-C, you could write the following function (for C++98):
template<typename T>
inline bool isNull(const T *obj) {
return obj == ((const T *) 0);
}
// to use it:
if (isNull(myType)) { //myType is a pointer to something
// some code
}
Although I never saw that one used in practice.
I hope this answer helps in understanding the concept in C++.
If i'm right, you want to check for null pointers. This is actually very easy in C++
Foo *pInstanc = new Foo;
if(pInstance)
{
//do something with pInstance
}

In C++, can objects be null?

Here's what I have done:
I've got a simple class:
class Person{
public:
Person();
}
And in my main:
int main() {
Person myPer = NULL;
}
This is impossible since C++ does not allow that, however:
int main() {
Person* perPtr = NULL;
Person myPer = *perPtr; // corrected, it was &perPtr(typo error) before answers
}
This compiles fine and as I see I did able to have a NULL object. So isn't it violating the rule that only pointers can be null in C++? Or is there such a rule in C++?
2nd one is after I wrote this code, I added a if statement checking whether myPer is NULL or not but that gave me error. So does it show that C++ does not really like the NULL object idea no matter what you do to make objects NULL...
Objects cannot be null, only pointers can. Your code is incorrect and does not compile, since its trying to initialize a Person from a pointer to a pointer to Person. If you were to change your code to
Person* perPtr = NULL;
Person myPer = *perPtr;
then it would be trying to initialize a Person out of a dereferenced null pointer to a Person, which is undefined behavior (and most likely a crash).
If you need to use the idioms where an object could be in a NULL state, you could use Boost.Optional:
boost::optional< Person > myPer = boost::none;
if( myPer )
{
myPer->do_something();
}
It's a generalization of what is usually done with pointers, except it does not use dynamic allocation.
This is undefined behaviour. C++ references cannot be legally set to NULL. If you want a "nullable reference", use a pointer.
This is called undefined behavior. Unexpected results may happen when you attempt to dereference NULL or get the address of NULL.
References are basically syntactically nicer way of saying pointers.
You can make a class that has "NULL" state.
E.g. a class that owns something else, such as a file handle or a window handle or anything else, such that it can be empty or not.
You can see this with any string class or with any container class.
if (x.empty()) ...
But the concept of "is null" is limited to pointers and smart pointers (or any class that you override to support such use cases.
You can not have a NULL object in C++. Your first attempt is trying to set an object equal to a pointer, and thus fails.
You can have a NULL pointer, and references are simply pointers with slightly different syntax.
You can de-reference a NULL pointer (as in the compiler will let you), but that's undefined behavior. If you're lucky, dereferencing NULL will crash, so you know what's going on.
I would not say the following is impossible since C++ does not allow it:
int main() {
Person myPer = NULL;
}
It is possible, and C++ does allow it. It all depends on how you've defined the classPerson. For example, if the class Person has a constructor as shown below:
class Person
{
public:
Person(char *) {}
};
then Person myPer = NULL will compile just fine : http://www.ideone.com/586Pf
Now how much useful such class can be is up to you. One may exploit the above fact, and may come up with cool and useful (utility) class.

Difference between references and pointers [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What are the differences between pointer variable and reference variable in C++?
What does Class& mean in c++ and how is it different from Class*?
Class& foo;
Class* foo;
The & version represents a reference while the * version represents a pointer. The difference is far too big for a typical SO post. I suggest you start at the C++ FAQ lite
http://www.parashift.com/c++-faq-lite/references.html
I usually don't like to answer posts with a "you should use google" answer. However this is one topic that I highly advise you google. In particular google "c++ pointers vs. references". There is a wealth of information available on this topic and the discussions on those pages will trump anything we'll write here.
The * is a pointer, the & is a reference. The difference between the two is that a pointer is an area of memory that must be dereferenced, eg. by means of the -> operator in order to be "seen" as a class instance. A reference is instead an "alias", just an alternative name for the same class instance. You don't need to use the -> operator with a reference. You use the dot operator.
Personally, I rarely used the references, mostly when I had a value object that I allocated on the stack. The new operator always returns a pointer, which you then have to dereference. Moreover, one of the most problematic issues of the references is that you cannot set them to NULL. In some cases, it is handy to have a function that accepts either an object pointer or NULL. If your function accepts a reference, you cannot pass a NULL (you could use the Null object pattern, however)
A Class * can point at any class object, or none.
A Class & always points to exactly one class object, and can never point to a different one.
Furthermore, I believe Bjarne is a member of the set of people who have asserted "arrays in C are broken beyond repair," a Class * can point at a whole ding-dang array of class objects, lined up one after the other in memory, and there is absolutely no way in C to tell whether a Class * points at one or many.
Another difference is that reference variables must be initialized. You cannot create a reference variable like what is shown in the sample code. That would produce a compiler error.
As stated you should google it, but to avoid misunderstanding:
References are NOT variables
References are NOT similar to pointers (but you can use them in a similar way)
Think of a Reference as a shortcut for the term that is assigned to it.
One additional tip that I would offer is the following:
Use references when you can, pointers when you have to. If the object is guaranteed to exist, you should probably use a reference. If it is not, then you probably have to use a pointer.
One additional advantage is that references remove ambiguity on ownership. As soon as a maintenance programmer sees a pointer, they'll start to wonder if they should delete it.
Check this example out:
// Wrapper class using a reference because the wrapped object always exists
class Wrapper
{
public:
// If the wrapped is guaranteed to exist at creation, do it this way
Wrapper(Wrapped& wrapped):_wrapped(wrapped) { /* empty */ }
// put extra methods here.
int getWrappedValue() const { return _wrapped.getValue(); }
private:
Wrapped& _wrapped; // This object always exists and is valid
};
// Wrapper class written to support a possibly non-existent wrapped object.
class Wrapper
{
public:
Wrapper(Wrapped* wrapped = 0):_wrapped(wrapped) { /* empty */
void setWrappee(WRappee* wrapped) { _wrapped = wrapped; }
int getWrappedValue() const; // Not making inline -- more complex
private:
Wrapped* _wrapped; // Always check pointer before use
};
int Wrapper::getWrappedValue() const
{
if (_wrapped)
{
return _wrapped->getValue();
}
else
{
return -1; // NOTE, this is a contrived example -- not getting into exceptions
}
}
A reference (&) is just the same as a pointer (*), except that the C++ compiler ensures it not to be NULL. However, it can still be a dangling pointer (a pointer variable that has no reference such that it is garbage and invalid for any use).