Indirect virtual function call from Destructor

Let me give up on this: I have a clear understanding of calling a virtual function in a constructor or destructor.

In the code below, I try to avoid the virtual destructor ONLY FOR EXPERIMENTAL purposes.

Now my question is:

Basically, calling Destroy fun calls the correct virtual function. I expect that any call to the Destroy function should trigger the correct virtual entertainment.

But the same Destroy function placed in the Base destructor calls the virtual function Base.

Is this related to static binding or compiler optimization?

class Base { public: Base() { } void Destroy() { callVirtual(); } virtual void callVirtual() { cout<<"In Base callVirtual "<<endl; } ~ Base() { cout<<"In Base Destructor"<<endl; Destroy(); } }; 

.

 class Derived : public Base { public: Derived() { } void callVirtual() { cout"<<In Derived callVirtual"<<endl; } }; 

.

 int main() { Base *pointer = new Derived(); pointer->Destroy(); // Calls the right callVirtual return 0; } 
+4
source share
1 answer

In the destructor, the dynamic type this is the type of the current class, and not the original dynamic type of the object. See http://www.artima.com/cppsource/nevercall.html .

+5
source

Source: https://habr.com/ru/post/1337651/


All Articles