Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the derived class destructor get invoked being private in the following program?

#include<iostream>

class base
{
   public:
       virtual ~base(){std::cout << "base\n";}
};
class derived : public base
{
   private:
        ~derived(){std::cout << "derived\n";} /* destructor is private */
};
int main()
{
      base *pt= new derived;
      delete pt;
}

The above program compiles and runs fine. How does the derived class destructor get invoked being private ?

like image 241
Kaustav Ray Avatar asked Nov 18 '13 04:11

Kaustav Ray


People also ask

What happens when a destructor is private?

Private Destructor in C++ This code has private destructor, but it will not generate any error because no object is created.

Can we make a destructor as private?

Destructors with the access modifier as private are known as Private Destructors. Whenever we want to prevent the destruction of an object, we can make the destructor private.

Does destructor have to be public?

There's nothing inherently wrong with making the destructor protected or private, but it restricts who can delete the pointer.


1 Answers

This will happen not only with destructors.

You can override any virtual public function with a private one.

#include<iostream>

class base
{
   public:
       virtual void x(){std::cout << "base\n";}
};
class derived : public base
{
   private:
        void x(){std::cout << "derived\n"; base::x();}
};
int main()
{
      base *pt= new derived;
      pt->x(); //OK
      //((derived *)pt)->x();  //error: ‘virtual void derived::x()’ is private
      derived *pt2= new derived;
      //pt2->x();  //error: ‘virtual void derived::x()’ is private
      ((base *)pt2)->x(); //OK
}

Upside/downside of this is you will have to use pointer to base to access this method. This feature is one of ways to separate public API from customized implementation.

So, in other words, your destructor is getting called because it was declared as public in base and you are calling it trough pointer to base.

like image 146
fsw Avatar answered Sep 30 '22 00:09

fsw