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

  1. Newsgroups: comp.lang.c++
  2. Path: sparky!uunet!taumet!steve
  3. From: steve@taumet.com (Steve Clamage)
  4. Subject: Re: virtual madness - problem with virtual base class
  5. Message-ID: <1992Jul25.155730.19131@taumet.com>
  6. Organization: TauMetric Corporation
  7. References: <1992Jul24.190709.10315@walter.bellcore.com>
  8. Date: Sat, 25 Jul 1992 15:57:30 GMT
  9. Lines: 36
  10.  
  11. ik@snoopy.ctt.bellcore.com (Ik Su Yoo) writes:
  12.  
  13. >I'm using cfront 2.1 with ObjectCenter 1.1 and having problem with the
  14. >following code:  [ condensed ]
  15.  
  16. >    class A {
  17. >    public:
  18. >      virtual void f();
  19. >    };
  20.  
  21. >    class B: public virtual A { };
  22.  
  23. >      B bb;
  24. >      void* bbp = &bb;
  25. >      ((B*)bbp)->f();
  26. >      ((A*)bbp)->f();
  27.  
  28. Pointer casts in C++ do not in general mean "copy the bits".  When a
  29. class hierarchy is involved, the compile-time type is taken into
  30. account to adjust the pointer value.  When you cast &bb to type void*,
  31. you lose all the compile-time type information.
  32.  
  33. For example, when a B* is cast to an A*, there is a value change.
  34. The A base class does not start at the same address as the B derived
  35. class -- a virtual base must be located somewhere else.  The compiler
  36. generates code to adjust the address to the start of the A object.
  37.  
  38. In your example, you take the address of a B, cast it to void*.  Then
  39. you take the void* and cast it to type A*.  The information that the
  40. address is really of a B was lost to the compiler, so it can't make the
  41. adjustment.  You take the address of the B and try to use it as though
  42. it were the address of an A, which it is not.
  43. -- 
  44.  
  45. Steve Clamage, TauMetric Corp, steve@taumet.com
  46. Vice Chair, ANSI C++ Committee, X3J16
  47.