Protected vs Private Destructor
Is there any difference between a protected and a private destructor in C++? If a base classes destructor is private, I imagine that it is still called when deleting the derived 开发者_开发知识库class object.
If the base class destructor is private
or protected
then you cannot call delete
through the base-class pointer.
Use a protected destructor to prevent the destruction of a derived object via a base-class pointer. It limits access to the destuctor to derived classes. And it prevents automatic (stack) objects of class base.
In effect it is used to allow any other polymorphic use of derived classes via pointers to base, but not allow the users to delete using such a pointer. Example:- Abstract Base Classes / Interfaces.
But a protected
, non-virtual
destructor on a non-final
class seems to be a bug waiting to happen. Assuming you do not provide a destroy()
function, you have to eventually make the dtor public. As soon as you do that, you have no further control over the class, and run the risk of polymorphic deletion with a non-virtual dtor, if someone derives further from your class.
Taken from here:
If the constructor/destructor is declared as private, then the class cannot be instantiated.
This is true, however it can be instantiated from another method in the class. Similarly, if the destructor is private
, then the object can only be deleted from inside the class as well. Also, it prevents the class from being inherited (or at least, prevent the inherited class from being instantiated/destroyed at all).
The following piece of code will result in the compiler error (VC2010): C2248: 'base::~base' : cannot access private member declared in class 'base'
class base
{
~base(){}
};
class derived : public base
{
};
int main ()
{
derived* d = new derived;
delete d;
}
However, if you change the base destructor to be protected, everything works fine.
The answer is that your assumption is wrong. The base class destructor cannot be called when it is private.
精彩评论