home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #27 / NN_1992_27.iso / spool / comp / lang / cplus / 16786 < prev    next >
Encoding:
Internet Message Format  |  1992-11-23  |  2.2 KB

  1. Path: sparky!uunet!mcsun!uknet!news.cs.bham.ac.uk!bham!bhamvx!mccauleyba
  2. From: mccauleyba@vax1.bham.ac.uk (Brian McCauley)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: virtual base class and pointer to member function
  5. Message-ID: <1992Nov23.191017.1@vax1.bham.ac.uk>
  6. Date: 23 Nov 92 19:10:17 GMT
  7. References: <7972@charon.cwi.nl>
  8. Sender: usenet@rs6000.bham.ac.uk (USENET News Service)
  9. Organization: University of Birmingham
  10. Lines: 38
  11.  
  12. In article <7972@charon.cwi.nl>, frans@cwi.nl (Frans Heeman) writes:
  13. > I have a class A that stores a pointer to a member function, that
  14. > function being defined in class A or one of its subclasses. If class B
  15. > is derived from A, and B defines B::f(), I can store a pointer to B::f()
  16. > in A. When I use that member function pointer with an object of type B,
  17.      ^ Oh no you can't (unless you use a non-portable cast)
  18. > B::f() gets invoked for that object (see code below).
  19. > However, when I specify A as a *virtual* base class of B, this no
  20. > longer works. When I now use the member function pointer with an object
  21. > of type B, B::f() gets invoked in the scope of A, even though A does not
  22. > define f(). Only when I explicitly cast the type of the function back
  23. > to (B::*)(), it gives the same result as above.
  24. > Which, if any, of the behaviors above is 'correct'?
  25.  
  26. Explicity casting pointers to functions is not safe and not portable.
  27.  
  28. A few weeks ago there was a long discussion about whether a some
  29. implicit conversions between function pointers should be allowed but
  30. it was concluded that even the most innocent looking conversions could
  31. cause trouble under some implementations.
  32.  
  33. In practice...
  34.  
  35.  void (A::*fptr)() = (void (A::*)()) &B::f();
  36.  B b;
  37.  b.*fptr()
  38.  
  39. ... will only work if A is the first base class of B and is not virtual.
  40. However there is no obligation on the implementor to make this work.
  41. -- 
  42.     \\   ( )    No Bullshit!     |  Email: B.A.McCauley@bham.ac.uk   
  43.  .  _\\__[oo        from         |  Voice: +44 21 471 3789 (home)
  44. .__/  \\ /\@    /~)  /~[   /\/[  |    Fax: +44 21 625 2175 (work)
  45. .  l___\\      /~~) /~~[  /   [  |  Snail: 197 Harborne Lane,
  46.  # ll  l\\    ~~~~ ~   ~ ~    ~  |         Birmingham, B29 6SS, UK
  47. ###LL  LL\\   (Brian McCauley)   |   ICBM: 52.5N 1.9W
  48.