From -4785038712222326671 X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: f78e5,ec45d63568ef66b0 X-Google-Attributes: gidf78e5,public X-Google-ArrivalTime: 1991-04-30 07:03:13 PST Path: gmdzi!unido!unidui!math.fu-berlin.de!ira.uka.de!sol.ctr.columbia.edu!caen!sdd.hp.com!wuarchive!uunet!world!wmm From: wmm@world.std.com (William M Miller) Newsgroups: comp.std.c++ Subject: Re: backward virtual function call Message-ID: <1991Apr30.140313.7150@world.std.com> Date: 30 Apr 91 14:03:13 GMT References: <1991Apr30.024010.4331@csi.uottawa.ca> Organization: Glockenspiel, Ltd. Lines: 30 hitz@sim5.csi.uottawa.ca (Martin Hitz) writes: > struct X { > virtual f() { return 1; } > }; > struct Y : X { > f() { return 2; } > }; > > main() > { > X x; > Y * y = (Y *) &x; > cout << y->f(); > } > > The ARM explains the usual case, that a call of f() for an object of > class Y invokes Y::f(), even if it is called via a pointer to X, > but I couldn't find anything about the above case. That's because it's an error. See section 5.4 of E&S: "Such a cast from a base to a derived class assumes that the object of the base class is a sub-object of an object of the derived class; the resulting pointer points to the enclosing object of the derived class. If the object of the base class is not a sub-object of an object of the derived class, the cast may cause an exception." In other words, the behavior is undefined, and an implementation under which the program printed -356, or dumped core, or erased your disk would be perfectly legitimate. -- William M. Miller, Glockenspiel, Ltd. wmm@world.std.com