home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!wupost!darwin.sura.net!jvnc.net!nuscc!iti.gov.sg!nicholas
- From: nicholas@iti.gov.sg (Nicholas Tan)
- Subject: pointer to constant object violation
- Message-ID: <1992Aug15.133926@iti.gov.sg>
- Originator: nicholas@helios.iti.gov.sg
- Sender: news@iti.gov.sg (News Admin)
- Organization: Information Technology Institute, National Computer Board, S'pore
- Date: Sat, 15 Aug 1992 05:39:26 GMT
- Lines: 63
-
-
- I have come across something that puzzles me. My test program below has a class
- String which has a member function that returns a pointer to a constant string.
- However, if I use a typedef rather than a #define for STR, different behaviour is
- observed. Using a typedef, I can compile, link, and run using Borland C++ 3.0,
- g++ 2.2.2, and Sun CC 2.?. The result is that the 4th character is modified to
- a 'Z'. If I use a #define, g++ 2.2.2 gives a warning, "assignment of read-only
- location", and produces an executable that behaves as previously. However, both
- Sun CC 2.? and Borland C++ 3.0 produces an error during compilation.
-
- I thought a typedef was just a synonym for another type, it does not introduce
- a new type. Also, does a compiler need to see a '*' character in order to flag
- pointer to constant object violation? Can someone tell me whether what
- happens is or is not correct C++?
-
- Thanks.
-
-
- --------------------------------------------------------------------------
-
-
- #include <iostream.h>
- #include <string.h>
-
-
- typedef char* STR;
- //#define STR char*
-
-
- class String
- {
- private:
- STR str;
-
- public:
- String(STR = "");
- const STR value() const;
- };
-
-
- String::String(STR str)
- {
- unsigned int len = strlen(str);
- this->str = new char[len+1];
- strcpy(this->str, str);
- }
-
-
- const STR String::value() const
- {
- return this->str;
- }
-
-
- int main(int, char* [])
- {
- String s1("Hello World");
- cout << s1.value() << "\n";
- (s1.value())[3] = 'Z';
- cout << s1.value() << "\n";
-
- return 0;
- }
-