home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #1 / NN_1993_1.iso / spool / comp / lang / cplus / 19011 < prev    next >
Encoding:
Text File  |  1993-01-12  |  2.1 KB  |  62 lines

  1. Path: sparky!uunet!dtix!darwin.sura.net!haven.umd.edu!wam.umd.edu!krc
  2. From: krc@wam.umd.edu (Kevin R. Coombes)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: semi-private public methods?
  5. Message-ID: <1993Jan12.162217.23432@wam.umd.edu>
  6. Date: 12 Jan 93 16:22:17 GMT
  7. References: <RALPH.93Jan11143011@yo_dud.bell.ca>
  8. Sender: usenet@wam.umd.edu (USENET News system)
  9. Distribution: na
  10. Organization: University of Maryland, College Park
  11. Lines: 48
  12. Nntp-Posting-Host: rac1.wam.umd.edu
  13.  
  14. In article <RALPH.93Jan11143011@yo_dud.bell.ca> ralph@dci.pinetree.org writes:
  15. >I would like to have a class that has some public methods that can
  16. >only be used by a certain group of classes.
  17. >Lets call this class A, and I want B,C,D &E to be able to use the
  18. >public methods on A. (no problem so far)
  19. >However, I don't want classes X, Y, &Z to be able to use the methods,
  20. >nor any other similar classes added in the future.
  21. >I don't want B,C,D &E to access the private data of A, so I can't make
  22. >them friend classes.  A,B,C,D, &E aren't in the same heirarchy, so I
  23. >can't use inheritance to have a solution to the problem.
  24. >What I would like to be able to do is say that the public methods of A
  25. >are only public to a certain group of classes, and private to all
  26. >others.
  27. >Any ideas?
  28. >
  29.  
  30. As my newsreader asks, are you absolutely sure that you want to do this?
  31.  
  32. It sounds like you should look very carefully at the design of the classes
  33. before trying to do this; the wrong class is hoarding some data, or your
  34. design is missing a class.
  35.  
  36. Can you explain why the "public" methods of A aren't really public? Do they
  37. allow clients to disturb the integrity of the data? Do they produce objects
  38. with incoherent data?
  39.  
  40. Anyway, supposing you really DO want to do this, can you do the following:
  41.  
  42. class A {
  43.   public:
  44.     void really_public_method();
  45.   protected:
  46.     void semi_public_method();
  47.   private:
  48.     int dont_touch_me;
  49. };
  50.  
  51. class SemiPublic : public A {
  52.   friend class B;
  53.   friend class C;
  54.   // etc.
  55. };
  56.  
  57. Now B and C can access the protected methods of A, since they are part of
  58. the interface of SemiPublic. They can't touch the private members of A,
  59. because SemiPublic can't touch them.
  60.  
  61. Kevin Coombes <krc@math.umd.edu>
  62.