Horizon Horizon - 2 months ago 10
C++ Question

Is it allowed to compare a pointer to an object to nullptr?

I have declared and implemented two classes,

Library
and
Book
.
Library
has a private member
Book** books
. This pointer to a pointer is used to store pointers to
Book
objects. I have also overload the
+=
operator in the
Library
class as follows:

Library& Library::operator+=(Book* addThisBook){
bool added = false;
int index = 0;

if(isFull()){
cout << "Library is full!" << endl;
}else{
//add book in first available space
while(!added && index<librarySize){
if(books[index] == nullptr){
books[index] = addThisBook;
added = true;
}
index++;
}
numBooks++;
}
return *this;
}


My question is in regards to the conditional in the if statement; is it allowed to compare a pointer to a custom class to
nullptr
?

NPE NPE
Answer

is it allowed to compare a pointer to a custom class to nullptr?

Yes, a pointer of any type can be compared to nullptr for (in)equality.

Comments