Question

Let me make this disclaimier : I have clear understanding of virtual function call in Constructor or Destructor.

In the below code I am trying to avoid virtual destructor ONLY FOR EXPERIMENTAL purpose.

Now my question is:

In main the call to Destroy fun calls the right virtual function. I am expecting any call to Destroy Function should call the right virtual fun.

But the same Destroy function placed in Base destructor call's the Base virtual function.

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;

}
Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top