Search code examples
c++comparisonimplicit-conversionnull-pointer

Determining null pointer


I have function that returns pointer to child object.

Function prototype:

ObjClass* ObjClass::getChildFromParent(ObjClass* parent = nullptr);

This function has default parameter as null pointer and I want to check this parameter anyway, because if pointer is null I will return nullptr but if it's not I will return pointer to child object, so:

ObjClass* ObjClass::getChildFromParent(ObjClass* parent)
{
    return parent == 0 ? nullptr : parent->getChild();
}

But I think checking null pointer using zero is not correct. So, should I use keyword to determine null pointer?


Solution

  • According to the C++ 14 Standard (5.10 Equality operators)

    2 If at least one of the operands is a pointer, pointer conversions (4.10) and qualification conversions (4.4) are performed on both operands to bring them to their composite pointer type (Clause 5). Comparing pointers is defined as follows: Two pointers compare equal if they are both null, both point to the same function, or both represent the same address (3.9.2), otherwise they compare unequal.

    And (4.10 Pointer conversions)

    1 A null pointer constant is an integer literal (2.13.2) with value zero or a prvalue of type std::nullptr_t. A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type and is distinguishable from every other value of object pointer or function pointer type. Such a conversion is called a null pointer conversion...

    Thus the expression in the return statement

     return parent == 0 ? nullptr : parent->getChild();
    

    is entirely correct because the null pointer constant 0 is converted to a null pointer value of the type of the pointer parent. But it will be more expressive to write

     return parent == nullptr ? nullptr : parent->getChild();