0

when a class has private destructor, only dynamic objects of that class can be created. Why?

0726
  • 315
  • 2
  • 13

1 Answers1

2

When a local variable goes out of scope there is an implicit destructor call.

If the destructor is not accessible from that scope, it can't be called.

Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521
  • #include using namespace std; class Test { private: ~Test() {} }; int main() { Test *t = new Test; delete t; } This program fails to compile. If i want to delete an object(local variable) before it's function completes the exec then? – 0726 Apr 15 '16 at 21:46
  • 1
    @0726: You can't. The destructor is like any member function: if it's private, then only a member of that class (or a member of a friend class) can call it. Period. Typically, such a class with a private destructor would have some other method to delete the object, or at least to mark it as no longer in use for some kind of garbage collection mechanism. – Dan Korn Apr 15 '16 at 23:26
  • I'm not sure what part of this is not obvious to you. If the destructor is not accessible then you can't destroy the object. If destruction would happen automatically for a local variable in a context where the destructor is not accessible, you can't use it as a local variable. If destruction would happen because you delete it in a context where the destructor is not accessible, then you can't delete it. – Jonathan Wakely Apr 15 '16 at 23:39