Home > Backend Development > C++ > Why Does Calling a Non-Virtual Member Function on a Null Pointer in C Sometimes Work?

Why Does Calling a Non-Virtual Member Function on a Null Pointer in C Sometimes Work?

DDD
Release: 2024-12-13 16:58:10
Original
666 people have browsed it

Why Does Calling a Non-Virtual Member Function on a Null Pointer in C   Sometimes Work?

Gotcha in C : Accessing Non-Virtual Class Members on a Null Pointer

In C , calling non-virtual member functions on a null pointer may unexpectedly work, posing a curious puzzle. Let's delve into this behavior through an intriguing code snippet:

Puzzle Explained

The confusion arises from the different mechanisms used to call virtual and non-virtual methods.

  • Virtual methods: Require vtable lookup to determine the function to call, which fails for null pointers as they have no valid objects associated with them.
  • Non-virtual methods: Are compiled directly as a function call with the this pointer (object reference) passed as a hidden parameter.

In the given code, the non-virtual method say_hi() never explicitly dereferences the this pointer, bypassing the null pointer dereference error. It's essentially the equivalent of a function call with a parameter passed by value:

Undefined Behavior

Technically, calling any function (even non-virtual) on a null pointer is undefined behavior in C . However, some compiler implementations may provide well-defined behavior for specific scenarios, such as the above non-virtual function call.

Caution

While the unexpected behavior may seem convenient, relying on it is risky and not a best practice. Always avoid accessing class members on null pointers, as it can lead to unexpected and unpredictable results.

The above is the detailed content of Why Does Calling a Non-Virtual Member Function on a Null Pointer in C Sometimes Work?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template