首页  >  文章  >  后端开发  >  为什么我在构造函数和析构函数中出现“纯虚函数调用”错误?

为什么我在构造函数和析构函数中出现“纯虚函数调用”错误?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-11-15 07:12:02296浏览

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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn