pcb@usl.usl.edu (Peter C. Bahrs) (05/01/89)
Very recently someone (??) put a question about virtual pointers et.al. on the net. I typed a variation of this in and am not sure why I receive the results below? Any comments? Script started on Sun Apr 30 14:10:33 198 -pcb--> cat b.c #include <stream.h> class What { public: What (void) { cout << form("Construct What\n"); } void virtual print(); }; void What::print() { cout << form ("I am What's print routine\n"); } class Where : public What { public: Where (void) { cout << form("Construct Where\n"); } void print(void) { cout << form ("Where's print routine\n"); } }; main () { typedef void What::WhatMember(); typedef void Where::WhereMember(); What* x = new What; Where* y = new Where; WhatMember* fp1; WhereMember* fp2; fp1 = &Where::print; (x->*fp1)(); fp2 = &Where::print; (y->*fp2)(); } -pcb--> CC b.c -o b CC b.c: cc -o b b..c /usr/local/lib/libC.a -pcb--> b Construct What Construct What Construct Where I am What's print routine Where's print routine -pcb--> ^D script done on Sun Apr 30 14:11:07 198
diamond@diamond.csl.sony.junet (Norman Diamond) (05/02/89)
In article <797@usl.usl.edu> pcb@usl.usl.edu (Peter C. Bahrs) writes: >am not sure why I receive the results below? Any comments? I >#include <stream.h> N > E >class What { W >public: S > What (void) { cout << form("Construct What\n"); } > void virtual print(); I >}; S > >void What::print() A >{ N > cout << form ("I am What's print routine\n"); >} A > S >class Where : public What { S >public: H > Where (void) { cout << form("Construct Where\n"); } O > void print(void) { cout << form ("Where's print routine\n"); } L >}; E > >main () >{ > typedef void What::WhatMember(); > typedef void Where::WhereMember(); > What* x = new What; > Where* y = new Where; > > WhatMember* fp1; > WhereMember* fp2; > fp1 = &Where::print; Interesting. I wonder why this isn't considered a type mismatch. > (x->*fp1)(); > fp2 = &Where::print; > (y->*fp2)(); >} >Construct What For your invocation of new What. >Construct What >Construct Where Both for your invocation of new Where. >I am What's print routine Since print() is virtual, (x->*fp1)() calls the version of print() which is defined for the actual type of (*x), which is What. >Where's print routine Similarly, the actual type of (*y) is Where. If print() were non-virtual, then Where::print() would be called both times. Norman Diamond, Sony Computer Science Lab (diamond%csl.sony.jp@relay.cs.net) The above opinions are my own. | Why are programmers criticized for If they're also your opinions, | re-inventing the wheel, when car you're infringing my copyright. | manufacturers are praised for it?