Can a destructor be declared private?

K

Ken Wilson

Is it possible to declare a class destructor as private?

Try it and see.

I would venture not though because the program would no longer be able
to call it. :)

Ken Wilson
"Coding, coding, over the bounding main()"
 
A

Alfonso Morra

Ken said:
Try it and see.
I already did and found the answer (that's why I deleted the OP).
I would venture not though because the program would no longer be able
to call it. :)
Not necessarily true. This is a nested class that must not be accesible
outside its parent contaner. The container object is declared a friend
and therefore has access to the nested classes private parts.
 
T

titancipher

True, but if the class/function were made a friend, it would have
access to the class's destructor.
 
K

Ken Wilson

True, but if the class/function were made a friend, it would have
access to the class's destructor.

Fair enough. I was thinking about making the nested class private to
the container and then the destructor could be made public.

Ken Wilson
"Coding, coding, over the bounding main()"
 
M

Mercator

Ken said:
Try it and see.

There exists a well-known compiler (from a very big company) that
ignores the private-ness of destructors.
I would venture not though because the program would no longer be able
to call it. :)

Hint: friendship
 
J

John Carson

Mercator said:
There exists a well-known compiler (from a very big company) that
ignores the private-ness of destructors.

If it is the company that I am thinking of, then I am unable to reproduce
this. In particular, the following code won't compile on versions 6.0, 7.1
and 8.0 Beta 2 (I haven't tested 7.0):

class Test
{
~Test(){}
};


int main()
{
Test t;
}
 
M

Mercator

John said:
If it is the company that I am thinking of, then I am unable to reproduce
this. In particular, the following code won't compile on versions 6.0, 7.1
and 8.0 Beta 2 (I haven't tested 7.0):

You are right. I confused it with a problem I had some time ago using a
private operator delete.
 
?

=?iso-8859-1?q?Stephan_Br=F6nnimann?=

See Scott Meyers, More effective C++, item 27.
If you want to force the creation of an object on the heap,
then you use a private destructor and provide a public
member function destroy.

class Demo {
~Demo() {} // private
public:
void destroy() const
{
delete this;
}
};

Now the following won't work:

void foo()
{
Demo d;
}

regards, Stephan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,430
Messages
2,571,676
Members
48,796
Latest member
Greg L.

Latest Threads

Top