>  기사  >  백엔드 개발  >  생성자와 소멸자에서 "순수 가상 함수 호출" 오류가 발생하는 이유는 무엇입니까?

생성자와 소멸자에서 "순수 가상 함수 호출" 오류가 발생하는 이유는 무엇입니까?

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으로 문의하세요.