Article View: comp.std.c++
Article #1089Re: backward virtual function call
From: Jim ADCOCK
Date: Mon, 06 May 1991 19:12
Date: Mon, 06 May 1991 19:12
61 lines
1873 bytes
1873 bytes
In article <1991Apr30.024010.4331@csi.uottawa.ca> hitz@sim5.csi.uottawa.ca (Martin Hitz) writes:
|I wonder if the following is guaranteed to print 1:
|
|#include <stream.h>
|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. Zortech and g++
|both yield 1 for this example. Is this considered to be the standard
|behaviour?
What would a C++ compiler then do with the following?
[All that I'm aware of act in an ill-defined manner, which is expected
since the ARM prohibits such erroneous down-casts. Your example just
happens to work on most C++ compilers]
extern "C" int printf(const char*, ...);
class A
{
private: virtual void illegalToAccess()
{ printf("erroneous access of A private method\n"); }
public: virtual void print() { printf("A\n"); }
};
class B
{
public: virtual void print() { printf("B\n"); }
private: virtual void illegalToAccess()
{ printf("erroneous access of B private method\n"); }
};
class AB: public A, public B
{
public: virtual void print() { printf("AB\n"); }
};
main()
{
A aA;
B aB;
A* a = &aA;
((AB*)a)->print();
B* b = &aB;
((AB*)b)->print();
return 0;
}
Technical Details
Message-ID:
<72185@microsoft.UUCP>Path:
arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!bonnie.concordia.ca!uunet!microsoft!jimadReferences:
<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!microsoft!jimad From: jimad@microsoft.UUCP (Jim ADCOCK) Newsgroups: comp.std.c++ Subject: Re: backward virtual function call Message-ID: <72185@microsoft.UUCP> Date: 6 May 91 19:12:04 GMT References: <1991Apr30.024010.4331@csi.uottawa.ca> Reply-To: jimad@microsoft.UUCP (Jim ADCOCK) Organization: Microsoft Corp., Redmond WA Lines: 61