Path: utzoo!attcan!uunet!munnari.oz.au!brolga!uqcspe!batserver.cs.uq.oz.au!iain From: iain@batserver.cs.uq.oz.au (Iain Fogg) Newsgroups: comp.lang.c++ Subject: Re: Multiple inheritance and type casting Message-ID: <5130@uqcspe.cs.uq.oz.au> Date: 8 Oct 90 02:23:07 GMT References: <5087@uqcspe.cs.uq.oz.au> <2709eabf.5abd@petunia.CalPoly.EDU> Sender: news@uqcspe.cs.uq.oz.au Reply-To: iain@batserver.cs.uq.oz.au Lines: 57 rae@gpu.utcs.toronto.edu (Reid Ellis) writes: >iain@batserver.cs.uq.oz.au writes: > >If D1::f() cast the formal parameter to type D1 (ie. (D1 > >&) b), for example to interrogate private data members, no > >problems. However, if X::f() casts to an X& my compiler > >complains (TC++ V1.0) saying "Cannot cast from B& to X&". >How do you know that the object passed in is really an "X &"? If you are >writing some sort of "clone()" method for instance, there is no way to tell if >the object being passed in is really of the type you expect. This is a design >flaw. There are other ways to do it. What is it you're trying to do? >I have found that casts lead to errors, plain and simple. If you are casting >base types to derived types, something is wrong with your design. I don't agree. Take for example the overloading of operator==. If we defined it as follows inline operator == (Base &b1, Base &b2) { return b1.IsEqual (b2); } where IsEqual is a virtual function declared in class Base. It's prototype is virtual int IsEqual (Base &); Now, any class derived from Base will probably want it's own version of IsEqual, but because the formal parameter is a Base &, a cast to the derived class will be required to compare attributes of the derived class (for example). For example, class Derived: public Base { public: virtual int IsEqual (Base &b) { return x == ((Derived &) b).x; } private: int x; } We can then say things like Derived d1, d2; if ( d1 == d2 ) ... If I've missed something, and there is a more elegant solution to the above scenario, please contribute. (Assume that we cannot declare operator== as a virtual function in Base). >If you are casting from derived types to base types, you're being >silly ;-). Bloody stupid, more likely. Iain Fogg. PS. For those familiar with TC++ classlib, this scenario arises when testing the equality of objects of classes derived from Object.