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=-0.9 required=3.0 tests=BAYES_00,FROM_ADDR_WS autolearn=no autolearn_force=no version=3.4.5-pre1 Date: 21 Sep 92 14:35:53 GMT From: eru.mt.luth.se!lunic!sunic!lth.se!newsuser@bloom-beacon.mit.edu (Dag Bru ck) Subject: Re: Dangerous truncation of object Message-ID: <1992Sep21.143553.18736@lth.se> List-Id: In firth@sei.cmu.edu (Robert Firth) writes: >In article <1992Sep21.063607.10441@lth.se> dag@control.lth.se (Dag Bruck) writ es: > >> Employee* e1 = new Employee; >> Employee* e2 = new Supervisor; >> >>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. It is not an "employee" that is either of two things; a pointer or a reference can either point to an "employee" or to any class derived from "employee". That is quite well defined, and polymorphism is maintained. The dangerous case is when we ask the compiler to truncate the object itself. Maybe I should point out that the behaviour is clear from the definition of C++, but it is a pitfall because a small change in the source code changes a program from pass-by-reference to pass-by-value. It would be much safer if the designer of "supervisor" could specify that truncation is illegal. -- Dag