Home > Backend Development > C++ > Why are Pure Virtual Functions Initialized with `0`?

Why are Pure Virtual Functions Initialized with `0`?

Patricia Arquette
Release: 2024-11-26 14:32:09
Original
168 people have browsed it

Why are Pure Virtual Functions Initialized with `0`?

Understanding the Initialization of Pure Virtual Functions with '0'

When declaring pure virtual functions, you may notice that they are always assigned to the value 0:

virtual void fun() = 0;
Copy after login

This practice raises the question of why pure virtual functions are initialized with 0.

The Incorrect Assumption

Initially, you might have believed that the value 0 is assigned to pure virtual functions to set the corresponding vtable entry to NULL. However, this assumption is incorrect. The value assigned to a pure virtual function does not necessarily set the vtable entry to NULL.

The Real Reason for '0'

The use of the =0 syntax for pure virtual functions dates back to Bjarne Stroustrup's early work on C . Rather than introducing a new keyword like "pure," he chose the =0 syntax because he believed it had a better chance of being accepted by the C community at that time.

As Stroustrup himself states in his book, "The Design & Evolution of C ," the =0 syntax was not intended to set the vtable entry to NULL. Moreover, setting the vtable entry to NULL is not an ideal implementation strategy for pure virtual functions.

Conclusion

The initialization of pure virtual functions with 0 is not related to setting the vtable entry to NULL. Instead, the =0 syntax was chosen purely for readability and compatibility reasons in the early stages of C development.

The above is the detailed content of Why are Pure Virtual Functions Initialized with `0`?. 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