On Wed, 5 Nov 2003 18:52:58 -0500, Josh Lessard
<jrlessar@plg2.math.uwaterloo.ca> wrote:
[color=blue]
> Hi all. I'm maintaining a C++ program and I've come across a nasty piece
> of code that works, but I just don't understand why. I'm not actually
> this part of the program, but I really want to know how and why it works.
>
> I'll post a simplified version of it below and ask my questions
> afterwards:
>
> class Base {
> void *function_ptr;
>
> public:
> Base();
> void Initialize();
> virtual void Function();
> };
>
> Base::Base() {
> function_ptr = (void *)&Base::Function;
> }
>
> void Base::Initialize() { // should be called from derived constructor
> if ( function_ptr != (void *)&Base::Function ) {
> /* do something */
> }
> }
>
> void Base::Function() {
> /* some code */
> }
>
>
> class Derived : public virtual Base {
> public:
> Derived();
> virtual void Function();
> };
>
> Derived::Derived() {
> Initialize();
> }
>
> void Derived::Function() {
> /* some code */
> }
>
>
> So the derived class overrides the virtual function "Function". Now,
> when
> the derived class calls Initialize (which is non-virtual and defined in
> the base), the statements between the curly braces in the if clause
> actually get executed. Why does this work? It seems like the base is
> setting function_ptr to &Base::Function, but then when it checks it again
> in Initialize(), they're no longer equal.[/color]
Expression &Base::Function maybe evaluated through virtual table , in this
case , when Initialized is called from Derived &Base::Function will return
pointer related to overriden Function.
This all is not regulated in the standard. Proper way to store pointers to
member function is void (Base::*ptr)() type not a void * type.
You may try to replace void * by the above and try again.
[color=blue]
>
> Does this have anything at all to do with the fact that Base is a virtual
> base class (ie would this still work if it wasn't a virtual base)? As
> far
> as I knew, virtual bases are used only to prevent multiple copies of the
> base class in a multiple inheritance tree, but recent discussion in this
> newsgroup has caused me to wonder if there isn't (quite a bit) more to it
> than that.
>
> Thanks in advance for any help.
>
> ************************************************** ***
> Josh Lessard
> Master's Student
> School of Computer Science
> Faculty of Mathematics
> University of Waterloo
> (519)888-4567 x3400
>
http://www.cs.uwaterloo.ca
> ************************************************** ***
>
>[/color]
--
grzegorz