Path: utzoo!attcan!uunet!mcsun!hp4nl!sci.kun.nl!atcmpe!leo From: leo@atcmp.nl (Leo Willems) Newsgroups: comp.lang.c++ Subject: polymorfism on objects, not pointers Keywords: polymorfism dynamic binding Message-ID: <631@atcmpe.atcmp.nl> Date: 4 Jul 90 20:17:02 GMT Organization: AT Computing, Nijmegen, The Netherlands Lines: 107 In the example below ::g() accepts a class B variable (not a pointer/reference) If g() is called with a D (derived from B) the virtual mechanism works! B bb; D dd; g(dd); //see end of posting for complete code In C++ 1.2 this didn't work (compile time error: can not make a B from a D) but in 2.0 it is possible to make a B from a D but as I understand it that should not alter the B behaviour, and so no runtime binding is expected. What strikes me is the difference in behaviour: when assigning a D to a B: bb = dd; bb->f(); //B::f(); as exptected there is no dynamic binding, when calling a function with a D which is expecting a B however there is: g(dd); // g(B x) { x.f(); } ===> D::f() !!!!!! In both cases I thought that the B part of a D was taken and no dynamic binding is expected. To make it even more complicated, when giving class B a copy constructor B::B(B&) {} the dynamic behaviour in the call g(dd) has disapeared! Can someone enlighten me? To be specific: *) Is the virtual mechanism supposed to work on class variables or only on pointer or references to classes? ( I have never ever read about the posibility that it should work on class variables. So if it is supposed to work please mail a reference on the subject.) ( if it should not work with class variables (as I think) then our compiler may be the problem: it is Glsp 2.0 for sparc stations Is this a known problem?) ( if it should not work with class variables (as I think) then the example in G Booch's OODWA is wrong: (p 102) void sendTelemetryData(TelemetryData D){ D.send(); } sendTelemetryData(telemtery); sendTelemetryData(electrical); (sorry for all the white space between the characters:-) Booch claims that here polymorfism is at work. If it is (and I am wrong) flame on me :-( ) Thanks, Leo ======== Complete example for C++ 2.0 ====== #include class b { public: virtual void f() { cout << "fb()\n"; } }; class d: public b { public: virtual void f() { cout << "fd()\n"; } }; void g(b x) { x.f(); } main() { b bb; d dd; g(bb); // fb() g(dd); // fd()!!!! bb = dd; g(bb); // fb() } ============ Leo Willems Internet: leo@atcmp.nl AT Computing UUCP: mcsun!hp4nl!kunivv1!atcmpe!leo P. O. Box 1428 6501 BK Nijmegen Phone: +31-80-566880 The Netherlands Fax: +31-80-555887