首頁 > 後端開發 > C++ > 主體

為什麼我在建構函式和析構函式中出現「純虛函式呼叫」錯誤?

Mary-Kate Olsen
發布: 2024-11-15 07:12:02
原創
295 人瀏覽過

Why Do I Get

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.

以上是為什麼我在建構函式和析構函式中出現「純虛函式呼叫」錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板