C++ function called without object initialization

The code produces undefined behavior, because it attempts to dereference an uninitialized pointer. Undefined behavior is unpredictable and follows no logic whatsoever. For this reason, any questions about why your code does something or doesn’t do something make no sense.

You are asking why it runs? It doesn’t run. It produces undefined behavior.

You are asking how it is assigning 5 to a non-existing member? It doesn’t assign anything to anything. It produces undefined behavior.

You are saying the output is 5? Wrong. The output is not 5. There’s no meaningful output. The code produces undefined behavior. Just because it somehow happened to print 5 in your experiment means absolutely nothing and has no meaningful explanation.

Leave a Comment