Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!wuarchive!cs.utexas.edu!tut.cis.ohio-state.edu!att!dptg!ulysses!andante!alice!ark From: ark@alice.UUCP (Andrew Koenig) Newsgroups: comp.lang.c++ Subject: Re: When polymorphic, when not? Message-ID: <10225@alice.UUCP> Date: 8 Dec 89 03:39:03 GMT References: <22395@brunix.UUCP> Organization: AT&T Bell Laboratories, Liberty Corner NJ Lines: 68 In article <22395@brunix.UUCP>, sdm@cs.brown.edu (Scott Meyers) writes: 1 #include 2 3 struct B { virtual void foo() { cout << "B::foo\n"; }}; 4 struct D: public B { void foo() { cout << "D::foo\n"; }}; 5 6 void val(B p) { p.foo(); } 7 void ref(B &p) { p.foo(); } 8 9 main() { 10 { 11 D d; 12 B b; 13 14 b = d; // b is still a B 15 D &dr = d; 16 B &br = d; 17 18 val(b); // calls B::foo 19 val(br); // calls D::foo [g++ calls B::foo] // g++ is correct here. This is a bug in cfront 2.0, // which will be fixed in 2.1 20 ref(b); // calls B::foo [g++ calls D::foo] // cfront is correct here. b is a B. 21 ref(br); // calls D::foo // correct. br refers to a D. 22 23 val(d); // calls D::foo [g++ calls B::foo] 24 val(dr); // calls D::foo [g++ calls B::foo] // these two lines exhibit the same cfront bug as above. 25 ref(d); // calls D::foo 26 ref(dr); // calls D::foo // correct. 27 } 28 29 // I don't know what results g++ gives for the following section 30 { 31 D d; 32 B b = d; // g++ won't compile this line ("unexpected argument 33 // to constructor `B'") // apparently a bug in g++. B always has a copy // constructor B::const(B&) and you can bind the // argument of that constructor to a D. 34 35 D &dr = d; 36 B &br = d; 37 38 val(b); // calls D::foo 39 val(br); // calls D::foo 40 ref(b); // calls D::foo 41 ref(br); // calls D::foo 42 43 val(d); // calls D::foo 44 val(dr); // calls D::foo 45 ref(d); // calls D::foo 46 ref(dr); // calls D::foo 47 } 48 } -- --Andrew Koenig ark@europa.att.com