#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 ?
Private Destructor in C++ This code has private destructor, but it will not generate any error because no object is created.
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.
There's nothing inherently wrong with making the destructor protected or private, but it restricts who can delete the pointer.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With