Home > Backend Development > C++ > Why Does Calling a Non-Virtual Method on a NULL Pointer Not Result in Undefined Behavior?

Why Does Calling a Non-Virtual Method on a NULL Pointer Not Result in Undefined Behavior?

Susan Sarandon
Release: 2024-12-31 18:44:13
Original
243 people have browsed it

Why Does Calling a Non-Virtual Method on a NULL Pointer Not Result in Undefined Behavior?

Accessing Class Members on a NULL Pointer

Despite being declared as a pointer to an instance of type Foo, the foo variable is initialized to 0, making it a null pointer. This may seem counterintuitive, as accessing members of a null pointer is typically undefined behavior. However, certain circumstances allow this behavior.

Non-Virtual Method Invocation

The non-virtual method say_hi() is successfully invoked despite the null pointer because it is not a virtual method. Virtual methods require a valid object to determine which function to call based on the object's type. Non-virtual methods, on the other hand, have a predetermined function address that the compiler uses to generate a direct function call instruction.

Specifically, the compiler generates code equivalent to the following:

void Foo_say_hi(Foo* this);
Foo_say_hi(foo);
Copy after login

Since the say_hi() function does not reference the this pointer, it bypasses the need to dereference a potentially null pointer.

Object Allocation

The foo variable is a local variable within the main function, so it is allocated on the function's stack. As a pointer variable, the actual object it points to is not allocated here. The null value indicates that the pointer does not reference a valid object.

The above is the detailed content of Why Does Calling a Non-Virtual Method on a NULL Pointer Not Result in Undefined Behavior?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template