home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #18 / NN_1992_18.iso / spool / comp / lang / cplus / 12370 < prev    next >
Encoding:
Text File  |  1992-08-14  |  1.9 KB  |  75 lines

  1. Newsgroups: comp.lang.c++
  2. Path: sparky!uunet!wupost!darwin.sura.net!jvnc.net!nuscc!iti.gov.sg!nicholas
  3. From: nicholas@iti.gov.sg (Nicholas Tan)
  4. Subject: pointer to constant object violation
  5. Message-ID: <1992Aug15.133926@iti.gov.sg>
  6. Originator: nicholas@helios.iti.gov.sg
  7. Sender: news@iti.gov.sg (News Admin)
  8. Organization: Information Technology Institute, National Computer Board, S'pore
  9. Date: Sat, 15 Aug 1992 05:39:26 GMT
  10. Lines: 63
  11.  
  12.  
  13. I have come across something that puzzles me.  My test program below has a class
  14. String which has a member function that returns a pointer to a constant string.
  15. However, if I use a typedef rather than a #define for STR, different behaviour is
  16. observed.  Using a typedef, I can compile, link, and run using Borland C++ 3.0,
  17. g++ 2.2.2, and Sun CC 2.?.  The result is that the 4th character is modified to
  18. a 'Z'.  If I use a #define, g++ 2.2.2 gives a warning, "assignment of read-only
  19. location", and produces an executable that behaves as previously.  However, both
  20. Sun CC 2.? and Borland C++ 3.0 produces an error during compilation.
  21.  
  22. I thought a typedef was just a synonym for another type, it does not introduce
  23. a new type.  Also, does a compiler need to see a '*' character in order to flag
  24. pointer to constant object violation?  Can someone tell me whether what
  25. happens is or is not correct C++?
  26.  
  27. Thanks.
  28.  
  29.  
  30. --------------------------------------------------------------------------
  31.  
  32.  
  33. #include <iostream.h>
  34. #include <string.h>
  35.  
  36.  
  37. typedef char*        STR;
  38. //#define STR        char*
  39.  
  40.  
  41. class String
  42. {
  43.     private:
  44.         STR str;
  45.  
  46.     public:
  47.         String(STR = "");
  48.         const STR value() const;
  49. };
  50.  
  51.  
  52. String::String(STR str)
  53. {
  54.     unsigned int len = strlen(str);
  55.     this->str = new char[len+1];
  56.     strcpy(this->str, str);
  57. }
  58.  
  59.  
  60. const STR String::value() const
  61. {
  62.     return this->str;
  63. }
  64.  
  65.  
  66. int main(int, char* [])
  67. {
  68.     String s1("Hello World");
  69.     cout << s1.value() << "\n";
  70.     (s1.value())[3] = 'Z';
  71.     cout << s1.value() << "\n";
  72.  
  73.     return 0;
  74. }
  75.