Home >Backend Development >C++ >Why is a Pure Virtual Function Initialized with \'=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;
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.
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!