Home > Backend Development > C++ > Why is a Pure Virtual Function Initialized with \'=0\'?

Why is a Pure Virtual Function Initialized with \'=0\'?

Susan Sarandon
Release: 2024-12-04 18:31:14
Original
912 people have browsed it

Why is a Pure Virtual Function Initialized with

Why is a Pure Virtual Function's Default Initialization "=0"?

In object-oriented programming, pure virtual functions are a crucial concept. As their name suggests, they are virtual functions that must be implemented in derived classes before the program can be complete. To declare a function as pure virtual, you use the syntax:

virtual void fun() = 0;
Copy after login

One notable aspect of pure virtual functions is their default initialization to 0. This leads to the question: why is this particular value chosen?

Contrary to common assumptions, the "=0" initialization is not intended to set the vtable entry for the pure virtual function to NULL. This was confirmed by Bjarne Stroustrup, the creator of C , in his book "The Design & Evolution of C ":

The curious "=0" syntax was chosen ... because at the time I saw no chance of getting a new keyword accepted.
Copy after login

In other words, the choice of "=0" was purely syntactic, driven by the lack of a better way to represent a pure virtual function at the time.

It's important to note that Stroustrup also acknowledges that setting the vtable entry to NULL is not the ideal way of implementing pure virtual functions. Modern C compilers handle this aspect more efficiently, ensuring that pure virtual functions are handled appropriately without relying on =0 initialization.

The above is the detailed content of Why is a Pure Virtual Function 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