Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!usc!samsung!munnari.oz.au!metro!extro!dpg From: dpg@extro.ucc.su.OZ.AU (D P Gilbert) Newsgroups: comp.lang.c++ Subject: polymorphism on base objects? Summary: polymorphism on base objects or compiler bug Keywords: C++, polymorphism, references, base objects, bug Message-ID: Date: 14 May 91 13:10:30 GMT Sender: news@metro.ucc.su.OZ.AU Distribution: comp Organization: Sydney University Computing Service, Sydney, NSW, Australia Lines: 54 Nntp-Posting-Host: extro.ucc.su.oz.au I was experimenting with polymorphism to see if it works through a function that takes a reference to a base class and got the following surprises. 2 compilers (SUN C++ and Comeau on ix/386) based on cfront 2.0 gave the same results. The following sections in the ARM throw some light on this (but I'm still confused): 4.7 (reference conversion), 5.17 (assignment operator), and 10.2 (Virtual functions). #include class Base { public: virtual void className() const { cout << "Class name: Base\n"; } }; class D1 : public Base { public: void className() const { cout << "Class name: D1\n"; } }; class D2 : public Base { public: void className() const { cout << "Class name: D2\n"; } }; void test_a(const Base &bas) { bas.className(); } // expect polymorphism void test_b(const Base bas) { bas.className(); } // don't expect ... main() { Base b; D1 d1; D2 d2; Base bb(d2); // Hoped for: cout << "test_a(b) : "; test_a(b); // Class name: Base cout << "test_a(d1) : "; test_a(d1); // Class name: D1 cout << "test_a(bb) : "; test_a(bb); // Class name: Base cout << "test_b(b) : "; test_b(b); // Class name: Base cout << "test_b(d1) : "; test_b(d1); // Class name: Base cout << "test_b(bb) : "; test_b(bb); // Class name: Base } Got the following output: test_a(b) : Class name: Base test_a(d1) : Class name: D1 test_a(bb) : Class name: D2 ??? test_b(b) : Class name: Base test_b(d1) : Class name: D1 ??? test_b(bb) : Class name: D2 ??? These last 2 results seem to indicate I can get polymorphism via base objects? Apologies is this is a stupid question. Thanks Doug Gilbert