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

  1. Path: sparky!uunet!ogicse!decwrl!pacbell.com!pjcondi
  2. From: pjcondi@ns.pacbell.com (Paul Condie)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: operator = with inheritance
  5. Message-ID: <1993Jan26.175530.1382@PacBell.COM>
  6. Date: 26 Jan 93 17:55:30 GMT
  7. Article-I.D.: PacBell.1993Jan26.175530.1382
  8. References: <1993Jan14.185649.21213@murdoch.acc.Virginia.EDU>
  9. Sender: news@PacBell.COM (Pacific Bell Netnews)
  10. Organization: Pacific * Bell
  11. Lines: 61
  12. X-Newsreader: TIN [version 1.1 PL8]
  13.  
  14.  
  15.  
  16. What would be wrong with this implementation:
  17.  
  18.  
  19. #include    <iostream.h>
  20.  
  21. class A
  22. {
  23.    public:
  24.     A (int arg = 0){
  25.          a = arg; 
  26.     }
  27.  
  28.     virtual A & operator = (const A & rhs) {
  29.         a = rhs.a;
  30.         return *this;
  31.     }
  32.  
  33.    private:
  34.     int a;
  35. };
  36.  
  37.  
  38. class B : public A
  39. {
  40.    public:
  41.     B (int arg = 0) : A(arg) {
  42.          b = arg; 
  43.     }
  44.  
  45.     A & operator = (const A & rhs) {
  46.         A::operator = (rhs);
  47.  
  48.         // The following cast should be ok because we know
  49.         // we have a B object because the virtual mechanism
  50.         // has told us. right?
  51.  
  52.         b = ((B &)rhs).b;
  53.  
  54.         return *this;
  55.     }
  56.  
  57.    private:
  58.     int b;
  59. };
  60.  
  61.  
  62.  
  63. main ()
  64. {
  65.     A * obj3 = new B (1);
  66.     A * obj4 = new B;
  67.  
  68.     *obj4 = *obj3;            // works for pointer types
  69.  
  70.     B obj1 (2);
  71.     B obj2;
  72.  
  73.     obj2 = obj1;            // works for object types
  74. }
  75.