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
Personfrom a pointer to a pointer toPerson. If you were to change your code tothen it would be trying to initialize a
Personout of a dereferenced null pointer to aPerson, which is undefined behavior (and most likely a crash).If you need to use the idioms where an object could be in a
NULLstate, you could useBoost.Optional:It’s a generalization of what is usually done with pointers, except it does not use dynamic allocation.