Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!husc6!mit-eddie!ll-xn!ames!ptsfa!hoptoad!dasys1!wfp From: wfp@dasys1.UUCP (William Phillips) Newsgroups: comp.lang.c++ Subject: Interesting "Feature" of C++ Message-ID: <1718@dasys1.UUCP> Date: Tue, 20-Oct-87 01:46:07 EDT Article-I.D.: dasys1.1718 Posted: Tue Oct 20 01:46:07 1987 Date-Received: Fri, 23-Oct-87 01:56:59 EDT Organization: The Big Electric Cat Lines: 72 Keywords: virtual functions, assigning to this I have discovered an interesting "feature" of C++ (undocumented, as far as I know) which takes effect when using virtual functions and assignments to this . Briefly, given a base class and derived class(es) containing virtual function(s), if your program makes an assignment to this , you may be in trouble. Example: struct base { . . base *something(); // defined elsewhere base *something_else(); virtual void whatever(); . . . } struct derived : base { . . . void whatever(); . . . } . . . this = something(); if (this == NULL) { this = something_else(); } . . . A fragment similar to the above, if the result of the assignment this = something(); is in fact null, will (on a Silicon Graphics Iris workstation) cause a segmentation violation at runtime. If you explicitly assign this = NULL; (or this = 0;) the problem will not occur. The reason is that the C code generated by cfront in the first case does more than assigning the result of a function call; it also sets a pointer to an array of pointers to the virtual functions. It does not generate code to check the value of this before attempting to set the pointer, however. Thus, if this is NULL, the program attempts to set the function pointer to some bizarre value, and crashes. An explicit assignment of 0 to this does not generate code for changing the function pointer, and so causes no problem. The workaround is simple, but annoying (untidy!): base *that = something(); if (that == NULL) { that = something_else(); } this = that; . . . or something like that. Any comments? -- William Phillips {allegra,philabs,cmcl2}!phri\ Big Electric Cat Public Unix {bellcore,cmcl2}!cucard!dasys1!wfp New York, NY, USA (-: Just say "NO" to OS/2! :-)