#include <iostream>
struct X
{
bool isNull() { return this == nullptr; }
bool isNullConst() const { return this == nullptr; }
};
bool isNull(X& x) { return &x == nullptr; }
bool isNullConst(const X& x) { return &x == nullptr; }
// always false or exception.
bool isNullCopy(X x) { return &x == nullptr; }
int main()
{
X* x = nullptr;
std::cout << x->isNull() << '\n';
std::cout << (*x).isNull() << '\n';
std::cout << isNull(*x) << '\n';
// std::cout << isNull2(*x) << '\n'; // exception.
}
Here, I know that X::isNull() is equivalent to isNull(X&) and that X::isNullConst() is equivalent to isNullConst(const X&).
What I did not know is that it's normal to dereference a null pointer. I thought that any dereferencing for a null pointer would result in an exception.
After playing with pointers for a bit, I concluded that dereferencing a null pointer itself is not the problem, the problem is trying to read or write to the address pointed to by the null pointer.
And since the functions are in a well known location in memory, dereferencing a null pointer to a class and calling one of its functions will just result in calling the function with the null object as the first parameter.
That was new to me, but that's probably not the complete picture.
I thought at first that this was an OOP concept at first, thus it should work in java for example, but it didn't work here and caused an exception (which makes me think why it doesn't work in java?...):
class X
{
boolean isNull() { return this == null; }
}
public class Main {
public static void main(String[] args) {
X x = null;
System.out.println(x.isNull());
}
}
So, clearly this is something related to C++ and not OOP in general.
What are all of the situations under which dereferencing a null pointer will be valid and won't cause exceptions?
Is there something else other than pointers of structs and classes that can be dereferenced successfully even if they're null pointers?
Also, why is calling a function of a null pointer without accessing its fields raises an exception in other languages like java?
One case where dereferencing a null pointer makes sense is in Red-Black trees for example. Null pointers are considered to be black.
#define RED true
#define BLACK false;
struct Node
{
bool color;
bool isRed()
{
return this != nullptr && this->color == RED;
}
};
bool isRed(Node* node)
{
return node != nullptr && node->color == RED;
}
Here, I believe it makes more sense to include the function in the Node class itself since it's related to it. It's not very convenient to include all of the logic related to the node inside it except for the one that checks for it being null.