Reputation: 308
i created a book class which i having being working on as part of my assignment but its seems have being having one problem which i am failing to 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;
}
In the above code is a constructor and destructor, my question is what happens when I pass a NULL
as an argument in the stactic void DelBook
function? like this below
static void DelBook(NULL)
{
delete NULL;
}
How can I make it compile if its possible to pass a NULL value? Thanks in advance.
Upvotes: 5
Views: 23473
Reputation: 6372
NULL
is a valid pointer: it points to memory location zero. Therefore you can pass NULL into a function that takes a Book*
pointer, because it IS a Book*
pointer.
Additionally, NULL is special and doesn't need to be cast to Book*
- you do not need to say DelBook((Book*)NULL)
. Therefore, the program should compile already.
Deleting a null pointer does nothing, so you don't need a sanity check. However if you need to do something with a member of the Book
class, you must check it is not NULL first:
static void DelBook(Book * X)
{
if (X){
x->tidyUpBeforeDeletion();
delete X;
}
}
Failure to check this will result in a segfault - this is dereferencing a null pointer and is very bad news.
Upvotes: 0
Reputation: 6368
Passing NULL itself usually isn't a problem. It's basically 0. Deleting NULL probably has no effect
Upvotes: -2
Reputation: 143061
As long as DelBook
only invokes delete
— nothing happens, it's a no-op. (and it is possible to invoke your DelBook
with NULL
as a parameter value, no extra action needed).
Upvotes: 5