home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #16 / NN_1992_16.iso / spool / comp / lang / cplus / 11289 < prev    next >
Encoding:
Text File  |  1992-07-21  |  1.2 KB  |  45 lines

  1. Path: sparky!uunet!dtix!darwin.sura.net!mips!zaphod.mps.ohio-state.edu!uakari.primate.wisc.edu!ames!agate!forney.berkeley.edu!jbuck
  2. From: jbuck@forney.berkeley.edu (Joe Buck)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: HELP: mixing const and non const function
  5. Message-ID: <14i99nINN2s7@agate.berkeley.edu>
  6. Date: 22 Jul 92 00:14:47 GMT
  7. References: <1992Jul21.182115.1@cuavax.dnet.cua.edu>
  8. Organization: U. C. Berkeley
  9. Lines: 33
  10. NNTP-Posting-Host: forney.berkeley.edu
  11.  
  12. In article <1992Jul21.182115.1@cuavax.dnet.cua.edu> 48ganelin@cuavax.dnet.cua.edu writes:
  13. > I want to declare a function to be constant though it
  14. > uses a nonconstant function.
  15. > (Of course it is an error for usual situation, but see example)
  16.  
  17. The example code is
  18. class foo {
  19.     int vector [10] ;
  20. public:
  21.     int& operator () (int at)  { return vector[at] ; }
  22. };
  23.  
  24. class foo2
  25. {
  26.    foo f ;
  27.    int median (void) const { return f(5); }  // const violation
  28. };
  29.  
  30. You can get the effect you want by changing foo to
  31.  
  32. class foo {
  33.     int vector [10] ;
  34. public:
  35.     int& operator () (int at)  { return vector[at] ; }
  36.     const int& operator () (int at) const { return vector[at] ;}
  37. };
  38.  
  39. foo2 will now use the const version in its median function.
  40.  
  41.  
  42.  
  43. --
  44. Joe Buck    jbuck@ohm.berkeley.edu
  45.