Passing NULL as an argument to a function

i created a book class that I am working on as part of my assignment, but it seems to have one problem that I don’t understand in my code below, this is my code

private: Book (string N = " ", int p = 100, string A = "", string P = "", string T = "", int Y = 2000) { cout << "Book constructor start " << N << endl; Title=N; pages=p; Author=A; Publisher=P; Type=T; Yearpublished=Y; } ~Book(void) { cout << "Book destructor start " << Title << endl; system("pause"); } public: static Book * MakeBook(string N = "", int p = 100, string A = "", string P = "",string T = "",int Y = 2000) { return new Book(N,p,A,P,T,Y); } static void DelBook(Book * X) { delete X; } 

There is a constructor and destructor in the above code, my question is what happens when I pass NULL as an argument to the stactic void DelBook ? as below

 static void DelBook(NULL) { delete NULL; } 

How can I compile it if it is possible to pass a NULL value? Thanks in advance.

+4
source share
3 answers

While DelBook only calls delete , nothing happens, it's non-op. (and you can call << 20> with NULL as the parameter value, no additional steps are required).

+4
source

NULL is a valid pointer: it points to a zero memory location. Therefore, you can pass NULL to a function that takes a Book* pointer, because it is a Book* pointer.

In addition, NULL is special and does not need to be discarded on Book* - you do not need to say DelBook((Book*)NULL) . Therefore, the program should compile already.

Removing a null pointer does nothing, so you don't need a health check. However, if you need to do something with a member of the Book class, you must verify that it is not NULL at first:

 static void DelBook(Book * X) { if (X){ x->tidyUpBeforeDeletion(); delete X; } } 

Failure to verify this will result in segfault - this is dereferencing a null pointer and very bad news.

0
source

Passing NULL itself is usually not a problem. This is basically 0. Removing NULL probably has no effect

-1
source

Source: https://habr.com/ru/post/1447303/


All Articles