Horizon
Horizon

Reputation: 53

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?

Upvotes: 4

Views: 5704

Answers (1)

NPE
NPE

Reputation: 500437

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.

Upvotes: 7

Related Questions