-2

I am looking for a way to protect a class from receiving a NULL pointer at compiler time.

class B
{
   // gives some API

}


class A
{


    private:
        B* ptrB_;
    
    public:
        A(B* ptrB) 
        {
            // How can I prevent the class to be created with a null pointer?
            ptrB_ = ptrB;
        }

        // multiple member function using: ptrB_ 
        void A::Func1(void)
        {
            if(!ptrB_ )
                rerturn; // I don't want to add it in every function.

            ...

            return;
        }

}


int main()
{
   B tempB = NULL;
   A tempA(&tempB);
}

How can I force user to always pass a pointer (not NULL) to A constructor?

Was looking at constexpr , but this forces to use static , and that's something I am trying to avoid.

1 Answers1

1

To avoid the risk of NULL pointers, don't pass a pointer at all, instead use references (there are no 'null' references).

e.g.

A(B* ptrB) { ptrB_ =  ptrB; } //instead of passing the address of an object
A(B& ptrB) { ptrB_ = &ptrB; } //take and store the address of the reference
Erdal Küçük
  • 4,810
  • 1
  • 6
  • 11