Search code examples
c++nullptr

How to define our own nullptr in c++98?


Actually I am writing my own version of all library classes, and I don't want to include the STL files into my class file. So, for example, I want to check whether the node is equal to null. If I write something like

#define nullptr 0

Then it is not working with some other node pointer (i.e. Node *root = nullptr)


Solution

  • How to do that is mentioned in the book: Effective C++, 2nd edition by Scott Meyers (newer edition is available) in chapter: "Item 25: Avoid overloading on a pointer and a numerical type.".

    It is needed if your compiler doesn't know the nullptr keyword introduced by C++11.

    const                         /* this is a const object...     */
    class nullptr_t
    {
    public:
       template<class T>          /* convertible to any type       */
       operator T*() const        /* of null non-member            */
          { return 0; }           /* pointer...                    */
    
       template<class C, class T> /* or any type of null           */
          operator T C::*() const /* member pointer...             */
          { return 0; }   
    
    private:
       void operator&() const;    /* Can't take address of nullptr */
    
    } nullptr = {};               /* and whose name is nullptr     */
    

    That book is definitely worth reading.


    The advantage of nullptr over NULL is, that nullptr acts like a real pointer type thus it adds type safety whereas NULL acts like an integer just set to 0 in pre C++11.