0
#include <iostream>

class TestClass {
public:
    TestClass() {
        std::cout << "TestClass instantiated\n";
    }

    ~TestClass() {
        std::cout << "TestClass destructed\n";
    }

    void PrintSomething() {
        std::cout << "TestClass is printing something\n";
    }
};

int main() {
    
    TestClass* tClass = new TestClass();
    delete tClass;
    tClass = nullptr;
    tClass->PrintSomething();

    std::cout << "Exiting...\n";
    return 0;
}

Result:

TestClass instantiated
TestClass destructed
TestClass is printing something
Exiting...

I thought that trying to print something after the tClass pointer had been set to nullptr would cause a nullpointer exception error, but it prints just fine.

olawrdhalpme
  • 180
  • 8
  • 2
    Undefined Behaviour is undefined, anything can happen. A possible explanation is in the linked duplicate. – Yksisarvinen May 02 '22 at 12:17
  • 2
    There are no "null pointer exceptions" in the C++ standard. Perhaps you're basing your expectations on some other language? – molbdnilo May 02 '22 at 12:29
  • When a program crashes, sometimes the operation system reports the problem as an "exception". That's not the same thing as a C++ exception. In C++ you get an exception when you `throw` it. Interestingly, Java doesn't have pointers, but it does have a `NullPointerException`. – Pete Becker May 02 '22 at 12:39
  • 2
    The language does not detect nullptr misuse for you. C++ is not a nanny language. You need to check if a potentially nullptr pointer is a nullptr before dereferencing it. Just before `tClass->PrintSomething();` add this line `if (tClass == nullptr) throw std::logic_error("nullptr");` – Eljay May 02 '22 at 13:08

1 Answers1

2

Why doesn't accessing this nullpointer cause an exception?

Because it's not specified to cause an exception. Accessing through a null poitner results in undefined behaviour. Don't do it.

eerorika
  • 232,697
  • 12
  • 197
  • 326