home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #31 / NN_1992_31.iso / spool / comp / lang / cplus / 18596 < prev    next >
Encoding:
Text File  |  1992-12-31  |  1.6 KB  |  59 lines

  1. Path: sparky!uunet!news.mentorg.com!sdl!not-for-mail
  2. From: adk@Warren.MENTORG.COM (Ajay Kamdar)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: >>>>>>>>  Is it possible to use 'delete this' ?
  5. Date: 31 Dec 1992 10:47:06 -0500
  6. Organization: Mentor Graphics Corp. -- IC Group
  7. Lines: 47
  8. Message-ID: <1hv4lqINN2fg@ajay.Warren.MENTORG.COM>
  9. References: <ssimmons.725636801@convex.convex.com> <796@ulogic.UUCP>
  10. NNTP-Posting-Host: ajay.warren.mentorg.com
  11.  
  12. In article <796@ulogic.UUCP> hartman@ulogic.UUCP (Richard M. Hartman) writes:
  13. >
  14. >Is it possible, within the definition of a class, to ensure that
  15. >the object may only be successfully created by "new" and not
  16. >by a simple declaration?
  17. >
  18. >e.g.
  19. >
  20. >    Object *p = new Object;        // ok
  21. >    Object O;                    // fails
  22. >
  23. >
  24.  
  25. Yes, this is possible. Make the destructor of the class private. That
  26. will prevent users of the class from creating objects on the stack
  27. (attempts to create such an object on the stack will result in a compile
  28. time error.) A side effect of making the destructor private is that the
  29. object cannot be deleted directly; a member function to perform delete
  30. takes care of that problem.
  31.  
  32. Example:
  33.  
  34. class A {
  35. public:
  36.     A() {}
  37.     void free() {delete this;} // delete the object
  38. private:
  39.     ~A() {} // will prevent A objects from being created on the stack
  40. };
  41.  
  42. int main()
  43. {
  44.     A a1;        // compile time error
  45.     A *a2 = new A;    // ok
  46.     delete a2;    // compile time error
  47.     a2->free();    // ok. deletes object.
  48.     return 0;
  49. }
  50.  
  51.  
  52. - Ajay
  53.  
  54. -- 
  55. I speak for none but myself.
  56.  
  57. Ajay Kamdar                               Email : ajay_kamdar@mentorg.com
  58. Mentor Graphics, IC Group (Warren, NJ)    Phone : (908) 580-0102
  59.