0

In C++, when we assign an object as null, can we still use that object to call it's member functions? My understanding was when we assign object as null, then no memory gets created so we shouldn't be able to assign it's data member values or call functions until we assign memory using new operator. I was expecting it to throw me a compiler error, but below program is working fine. Why is that? Can someone please explain.

class A{
  public:
  void print(){
      std::cout<<"hi\n";
  }
};

int main()
{
    A *a = NULL; 
    //or A *a = nullptr;
    //or A *a;
    a->print();
}
  • 2
    You are invoking *undefined behavior* by calling a member function on a null-pointer. The compiler is not required to diagnose this – UnholySheep Sep 25 '20 at 10:00
  • 1
    It seems you might be coming from another language. Yes, `a` is an object, but it doesn't have member functions. `a` is a pointer (type `A*`) and can be `NULL`. The type `A` is not a pointer, cannot be `NULL`, but `A` is a class type and does have members. You don't have any object of type `A`. – MSalters Sep 25 '20 at 10:49
  • The answer to your first question is: **no**, you can not use a pointer that is nullptr to call member functions. The answer to your second question is: C++ is not a nanny language; you are expected to not do these kinds of things; C++ gives you enough rope to shoot yourself in the foot. (The program crashes on my machine.) – Eljay Sep 25 '20 at 12:03

0 Answers0