ajithcpas
ajithcpas

Reputation: 51

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)

Upvotes: 0

Views: 4938

Answers (2)

Andre Kampling
Andre Kampling

Reputation: 5630

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.

Upvotes: 10

eerorika
eerorika

Reputation: 238461

You should not define macros with identifiers that are keywords.

Even if you don't use STL, there is no need to define your own nullptr, because it is not part of STL (nor the standard library), but is part of the (C++) language itself.

Upvotes: 6

Related Questions