home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #3 / NN_1993_3.iso / spool / comp / lang / cplus / 19813 < prev    next >
Encoding:
Text File  |  1993-01-24  |  1.6 KB  |  53 lines

  1. Newsgroups: comp.lang.c++
  2. Path: sparky!uunet!taumet!steve
  3. From: steve@taumet.com (Steve Clamage)
  4. Subject: Re: Friend ..Overload Assignment opertr ..
  5. Message-ID: <1993Jan23.200432.16195@taumet.com>
  6. Organization: TauMetric Corporation
  7. References: <1993Jan22.075317.21062@usl.edu>
  8. Date: Sat, 23 Jan 1993 20:04:32 GMT
  9. Lines: 42
  10.  
  11. rks9954@usl.edu (Srinivasa Rao K) writes:
  12.  
  13.  
  14. >       I am writing a "string"  class which i should be able to use like
  15.  
  16. >       string str1;
  17. >       str1 = "Hello world" ;
  18.  
  19. >       But We canot use a friend to overload the assignment oprator.
  20.  
  21. A String class will usually contain pointers, and so should have
  22. a user-defined assignment operator (which must be a member function,
  23. as you note) and copy constructor.  If not, you will be vary likely to
  24. have bizarre program crashes.  See the book "Effective C++" by Scott
  25. Meyers for a detailed discussion.
  26.  
  27. If you add a String constructor which takes a const char* parameter,
  28. you don't have to do anything else.  It is hard to imagine a String
  29. class without such a constructor.  Example:
  30.  
  31.     class String {
  32.     public:
  33.         String();            // default constructor (optional)
  34.         String(const char*);
  35.         String(const String&);    // copy constructor
  36.         String& operator=(const String &); // assignment operator
  37.         ...
  38.     };
  39.  
  40.     String s;
  41.     s = "Hello";
  42.  
  43. The string "Hello" will automatically be converted to a String by the
  44. constructor, then assigned via the assigment operator.  The code is
  45. evaluated as if you had written
  46.     s.operator=( String("Hello") );
  47.  
  48. The copy constructor is not relevent for this example, but you should
  49. have one anyway.
  50. -- 
  51.  
  52. Steve Clamage, TauMetric Corp, steve@taumet.com
  53.