0
class base
{
public:
    virtual ~base() = 0;
};

base::~base()
{
    cout <<"Destructing base"<<endl;
}

class derived : public base
{
    ~derived()
    {
        cout <<"Destructing derived"<<endl;
    }
};

int main()
{
    base* b = new derived();
    delete b;
    b = 0;

}

Here - I have declared the derived destructor as private and allocated memory on heap. But when I run this, I do see the derived destructor also getting called. Instead if I run this in the main function as below by allocating memory on the code segment as below -

int main()
{
  derived d;
}

This throws an error saying the destructor is private.

I am confused - Doesn't delete internally also call the destructor before calling free()?

  • 1
    Very similar to http://stackoverflow.com/questions/5685514/virtual-function-breaking-private-access – chris Mar 12 '15 at 06:03
  • `b` is a pointer to `base`. Its destructor is public. Try `derived * d = new derived(); delete d;` – juanchopanza Mar 12 '15 at 06:08
  • Think of C++ encapsulation not like "a prison", but a label "Please, do not disturb". And virtual function is a key. – Matt Mar 12 '15 at 06:12
  • 1
    Access control in C++, generally speaking, applies to *names*. – T.C. Mar 12 '15 at 06:17

0 Answers0