0

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)

ajithcpas
  • 51
  • 1
  • 6
  • 1
    is this c or c++? if it is c++ then nullptr is a keyword – codeconscious Jun 13 '17 at 09:33
  • 8
    Don't spam tags! C is not C++. And `nullptr` is a standard keyword, introduced to exactly avoid the ambivalent `0` conversion. – too honest for this site Jun 13 '17 at 09:34
  • 6
    Unless you can add your motivation for why you need to do this, you will get downvoted: nullptr was introduced in the language to avoid the accidental confusion with zero (by ADL resolution and implicit type conversions). What you are proposing (the define) is dangerous and a source of bugs that will be difficult to find. (effectively, you are reintroducing in your code base the bugs that NULL caused, and that nullptr is there to solve). – utnapistim Jun 13 '17 at 09:40

2 Answers2

10

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.

Andre Kampling
  • 5,476
  • 2
  • 20
  • 47
6

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • 5
    This is true, but `nullptr` was added only in C++11. That said, I don't think that is what this question is about. – Ellis Jun 13 '17 at 09:36