Path: utzoo!utgpu!watmath!att!dptg!ulysses!andante!alice!ark From: ark@alice.UUCP (Andrew Koenig) Newsgroups: comp.lang.c++ Subject: Re: Implementing virtual functions that return reference to self Keywords: virtual functions, derived classes, extended typechecking Message-ID: <9694@alice.UUCP> Date: 28 Jul 89 18:34:46 GMT References: <8975@thorin.cs.unc.edu> <7131@microsoft.UUCP> <7137@microsoft.UUCP> Organization: AT&T Bell Laboratories, Liberty Corner NJ Lines: 60 At first glance it may seem obvious that it should be possible in C++ for a virtual function to return a reference to *this without converting it to its base class. However, a closer look brings second thoughts. For example: class X { public: virtual X& self() { return *this; } }; class Y: public X { public: virtual Y& self() { return *this; } // illegal }; X* xp; The reason the line marked `illegal' is illegal is because if it were legal, then it would be impossible to know the type of xp->self() at compilation time. This type uncertainty would have ramifications throughout the language. For example: void f(X); void f(Y); // overloading f(xp->self()); Evidently it would be necessary to do a run-time dispatch to decide which f() to call. If f has multiple arguments, the problem becomes that much harder. This implicit run-time dispatch can even creep into non-virtual member functions. For instance: X* xp = new Y; X* xq = new Y; xp->self() = xq->self(); Since xp and xq both point at Y objects, one would presumably want this assignment to copy a Y rather than just copying the X part. To do that, though, effectively requires making all assignments into virtual functions. Worse yet, there are four possible combinations of X and Y that xp and xq might point to; what is the right thing to do in each case? The problems become still more complicated in the presence of multiple inheritance. In short, the reason that a virtual function must have the same return type in a derived class as in its base class(es) is that otherwise the type of an expression becomes impossible to determine during compilation. -- --Andrew Koenig ark@europa.att.com