Rumah > Artikel > pembangunan bahagian belakang > Mengapa Saya Mendapat Ralat "Panggilan Fungsi Maya Tulen" dalam Pembina dan Pemusnah?
Fatal "Pure Virtual Function Call" Errors: Unraveling Their Roots
It can be puzzling to encounter program crashes with the "pure virtual function call" error, especially when the affected class is abstract and thus should prohibit object creation. This article aims to shed light on the underlying causes behind such errors and provide a comprehensive explanation.
Virtual Function Calls in Abstract Classes
Virtual functions allow derived classes to override base class implementations, enabling polymorphism. However, in abstract classes, certain functions designated as "pure virtual functions" do not have any implementation in the base class. Instead, they serve as placeholders, requiring all derived classes to provide their own implementations. An abstract class without at least one pure virtual function can be instantiated, but calls to pure virtual functions will cause a runtime error.
"Pure Virtual Function Call" Crashes
However, an unexpected scenario can occur when a virtual function call is attempted from within a constructor or destructor. Due to the constraints of object construction and destruction, virtual function calls are not permitted at these stages. Consequently, the base class version of the virtual function is invoked instead, which in the case of a pure virtual function, is nonexistent, triggering a runtime crash.
Example Illustration
Consider the following code snippet:
class Base { public: Base() { reallyDoIt(); } void reallyDoIt() { doIt(); } // DON'T DO THIS virtual void doIt() = 0; }; class Derived : public Base { void doIt() {} }; int main(void) { Derived d; // This will cause "pure virtual function call" error }
In this example, an attempt to invoke a virtual function (doIt()) from the constructor of the abstract base class (Base) results in a "pure virtual function call" error when the derived class object (d) is created. Since there is no implementation for doIt() in Base, the call falls through to the pure virtual function placeholder, which is invalid.
Conclusion
"Pure virtual function call" errors occur when virtual function calls are mistakenly made from constructors or destructors. Understanding this limitation is crucial to avoid these crashes and ensure the correct functioning of abstract classes. For further insights, refer to Raymond Chen's enlightening articles on the subject.
Atas ialah kandungan terperinci Mengapa Saya Mendapat Ralat "Panggilan Fungsi Maya Tulen" dalam Pembina dan Pemusnah?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!