Who calls the class destructor when the delete operator is used for multiple inheritance

This question may sound too stupid, but I can’t find a specific answer anywhere.

With a little knowledge of how late binding works and the virtual keyword used in inheritance.

As in the code example, when in the case of inheritance, when the base class pointer is used to free memory, it points to the object of the derived class created during the heap and delete operation, the derivative and base destructor will be called in the order when the base destructor is declared as a virtual function.

Now my question is:

1) When the base destructor is not virtual, why the problem of not invoking dtor derivatives occurs only when, in the case of using the delete operator, why not in the case indicated below:  


derived drvd;
base *bPtr;
bPtr = &drvd; //DTOR called in proper order when goes out of scope.

2) When "delete" operator is used, who is reponsible to call the destructor of the class? The operator delete will have an implementation to call the DTOR ? or complier writes some extra stuff ? If the operator has the implementation then how does it looks like , [I need sample code how this would have been implemented].

3) If virtual keyword is used in this example, how does operator delete now know which DTOR to call?

Fundamentaly i want to know who calls the dtor of the class when delete is used.

<h1> Sample Code </h1>

class base
{
    public:
    base(){
       cout<<"Base CTOR called"<<endl;
    }

    virtual ~base(){  
       cout<<"Base DTOR called"<<endl;
    }
};

class derived:public base
{
    public:
        derived(){
            cout<<"Derived CTOR called"<<endl;
        }

    ~derived(){
            cout<<"Derived DTOR called"<<endl;
     }
};

, , .

int main() {   base * bPtr = new ();

delete bPtr;// only when you explicitly try to delete an object
return 0;

} Code>

+5
source share
4 answers

The compiler generates all the necessary code to call the destructors in the correct order, whether it be a stack object or a member variable that goes out of scope, or a deleted heap object.

+1
source
  • , , drvd derived. drvd ,

  • delete - . , operator delete . , , keyword delete operater delete .

  • , keyword delete , . . , , , , . , , . ,

void fun()
{
    Base *base= new Derived(); 
    delete base;
}

, ,

void deallocate(Base *base)
{
    delete base;
}

, , . .

  • Base (- ). .
  • Base , vtable.
    • . vtable , . , .
    • , vtable ,
+2

+1 BTW.

, , , .

2 , , -, , , . , , - , . .

, ? . , ? . , .

. delete , . , , . , , , , .

. delete . , - ? . . , , - .

, ? , .

+2
  • , , , .
  • , . . , , dtor . , 1 , .
  • , delete dtor .

, .

+1

All Articles