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