From mboxrd@z Thu Jan 1 00:00:00 1970 X-Spam-Checker-Version: SpamAssassin 3.4.5-pre1 (2020-06-20) on ip-172-31-74-118.ec2.internal X-Spam-Level: X-Spam-Status: No, score=-1.9 required=3.0 tests=BAYES_00 autolearn=ham autolearn_force=no version=3.4.5-pre1 Date: 21 Sep 92 12:59:36 GMT From: dog.ee.lbl.gov!hellgate.utah.edu!caen!zaphod.mps.ohio-state.edu!cis.ohio- state.edu!news.sei.cmu.edu!firth@ucbvax.Berkeley.EDU (Robert Firth) Subject: Re: Dangerous truncation of object Message-ID: <1992Sep21.125936.25779@sei.cmu.edu> List-Id: In article <1992Sep21.063607.10441@lth.se> dag@control.lth.se (Dag Bruck) write s: > Employee* e1 = new Employee; > Employee* e2 = new Supervisor; > >A pointer or a reference to an Employee may in fact point to a >Supervisor object, but because MonthlyPay() is declared as "virtual" >the correct function will be invoked. So far so good. > >The problem arises (most commonly) when we pass objects by value to >functions. > > void MakeCheck(Employee* e); // ok > void MakeCheck(Employee e); // dangerous > >If we pass a pointer or a reference as a function argument, the >polymorphic behaviour is preserved. If we pass the object by value, >the object is truncated to its Employee part. Maybe I'm about to display a ludicrous ignorance of object-oriented programming, but I don't see the problem here. If an "employee" can be either of two objects, then all operations, in principle, are polymorphic. So, if the compiler has to select the correct "monthlypay" operation, it also has to select the correct "passbyvalue" operation; by the same reasoning and, presumably, with a similar implementation.