Article View: comp.std.c++
Article #1060Re: backward virtual function call
From: William M Miller
Date: Tue, 30 Apr 1991 14:03
Date: Tue, 30 Apr 1991 14:03
30 lines
1465 bytes
1465 bytes
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
Technical Details
Message-ID:
<1991Apr30.140313.7150@world.std.com>Path:
arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!bonnie.concordia.ca!uunet!world!wmmReferences:
<1991Apr30.024010.4331@csi.uottawa.ca>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!bonnie.concordia.ca!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