Click to See Complete Forum and Search --> : Private destructor


Jin Song
March 17th, 2003, 02:03 PM
Here is a simplified code piece of mine:


class A
{
A()
{
cout << "ccc\n";
}
~A()
{
}
public:
static A *GetA(void)
{
static A a;
return &a;
}
};

int main()
{
A *b = A::GetA();
return 0;
}

It doesn't compile compaining
error C2248: 'A::~A' : cannot access private member declared in class 'A'

My mind doesn't work any more. Could someone kindly point out my problem? Thanks.

Paul McKenzie
March 17th, 2003, 02:16 PM
What compiler are you using? This is a confirmed bug in VC++ 6.0 that has been fixed in VC 7.0.

Regards,

Paul McKenzie

I know, I know
March 17th, 2003, 02:19 PM
By default all functions are declared private. You do not have the public decleration until below your constructor and destructor. I am not sure why you would ever want your constructor private, I can understand protected but not private. If you are going to use class A as just a parent class declare the constructor protected, but I think the destructor has to always be public.

galathaea
March 17th, 2003, 02:30 PM
I know, I know, private ctors / dtors are used to implement singleton classes (classes that can have only one instance throughout a program). This is why there is an instance access method (GetA) available.

The program is probably in error due to a compiler bug, as Paul McKenzie has pointed out. A workaround is to just not have the dtor private on MS6.0 and grep around by hand for its usage to make sure there are no deletes on the instance in any client code before compilation, or if that is not possible, use a different compiler or just live with the possibility of bad client code. It's not nice, but it gets you by.

Paul McKenzie
March 17th, 2003, 02:33 PM
Originally posted by I know, I know
By default all functions are declared private. You do not have the public decleration until below your constructor and destructor. I am not sure why you would ever want your constructor private, I can understand protected but not private. If you are going to use class A as just a parent class declare the constructor protected, but I think the destructor has to always be public. It is a bug in VC 6.0 that has been fixed in V 7.0.

Also, destructors can be private -- implementations of singleton patterns make use of private destructors.

Regards,

Paul McKenzie

Jin Song
March 17th, 2003, 03:02 PM
Thanks a lot. Unfortunately I'm using VC6.0.:(
I'll leave the destructor as public for now. Thanks again.