2

I don't understand something in C++ - I create some pointer on class and set it to null.

Now I call some function with this null pointer and the function succeeds. Why doesn't it crash ?

class Entity
{
public:
    void Print() const
    {
        std::cout << "Print" << std::endl;
    }
};

int main()
{
    Entity* ptr = nullptr;
    Entity& _ref = *ptr;    // No crash here - I expected a null pointer exception

    _ref->Print();  
}
Yanshof
  • 9,659
  • 21
  • 95
  • 195
  • 5
    While we're at it: there's no null pointer exception in C++. Never. Any use where you would expect one just triggers UB. – Quentin Apr 17 '18 at 08:08
  • @Quentin, so does this call `operator=` but `Entity&` is just `nullptr` resulting to UB? quite confusing that a `reference` can be a `nullptr` – Joseph D. Apr 17 '18 at 08:11
  • 1
    @codekaizer I don't get where you're taking that `operator =` from, there's only an `Entity *` here. And you cannot have a null reference: dereferencing the null pointer to obtain it is UB already. – Quentin Apr 17 '18 at 08:22
  • @hnefatl If you're both talking about the only `=` in the snippet, that's not an assignment but an initialization. It just initializes the pointer to be null. – Quentin Apr 17 '18 at 08:25
  • @Quentin, thanks for clarifying. for a moment I was obfuscated by references being null. true, this is just an initialization. – Joseph D. Apr 17 '18 at 08:27

2 Answers2

6

This an example of UB. It may or may not crash. But it is wrong code. UB means anything is possible. Although as other posts suggest, this simple snippet does not crash on many platforms.

Red.Wave
  • 2,790
  • 11
  • 17
1

This is a common thing in C++, the function is not part of the instance, but part of the class definition.

If you tried to access this in the function then you would have a crash.

As @YSC mentioned below, this is considered undefined behavior, and you should not assume this will work. but it will mostly work and i heard this is even asked in C++ interviews questions.

Arkady Godlin
  • 588
  • 2
  • 9
  • 3
    I **must** downvote any answer which does not mention _undefined behaviour_. – YSC Apr 17 '18 at 08:15
  • 3
    If an interviewer starts assuming the behaviour of code with no defined behaviour, just get up and walk away. You do *not* want to debug code with UB. – Quentin Apr 17 '18 at 08:41
  • @Quentin i agree, just wrote that i only know about this thing is from someone who worked with me and said this is a interview question he was asked in some place. – Arkady Godlin Apr 17 '18 at 08:50
  • 1
    Edit seen. I maintain my downvote. UB do not _"mostly work"_. I've heard, for years, people telling me `-O3` is buggy, and funny enough those same persons _do_ tend to ignore UB as you do. – YSC Apr 17 '18 at 09:44