TITLE: Virtualness, cloning, and type-safety PROBLEM: David Cok (cok@islsun.Kodak.COM), 11 Nov 91 [ The C++ type restrictions are too strict in some cases. An example is shown below. -adc ] if we have (a) virtual Shape* Shape :: clone () to produce a copy of a shape, we cannot also have (b) Circle* Circle :: clone () if Circle is derived from Shape. Instead we have to use (c) Shape* Circle :: clone () and "lose" the compile time type when we are cloning an explicitly Circle object. Granted it can be readily gotten back with a cast: Circle circle(radius,centerxy); Circle* new_circle; new_circle = (Circle*)(circle->clone()); But it would be a whole lot more elegant and type-safe simply to allow (b) -- that is, to allow virtual functions in derived classes to return a pointer or reference to a class derived from the return type of the virtual function in the base class. [ This problem statement brings up the concept of covariance of method return types. This covariance is absolutley type safe. In fact, recent postings to the "net" indicate that the ANSI X3J16 has adopted this as part of the C++ standard. You will see this in a future release of C++! - adc ] RESPONSE: Jeremy Grodberg (jgro@lia.com) The problem is that C++ requires static type information exclusively, since it only does type checking at compile time. You can achieve everything you can achieve without implementing run-time type checking by simply having a virtual function "Shape* Clone()" and non-virtual functions like "Circle* Circle::CircleClone() { return (Circle *) Clone(); }" You need run-time type checking to do validate something like: Circle* bar = new Circle; Shape* foo = bar->Clone(); Circle* baz = foo->Clone(); Yes, a super-smart compiler might be able to validate all that at compile time, but the above is also an over-simplified example. Not that I'm in favor of this proposal, mind you. I'm merely pointing out the Mr. Cox's request has a very high cost, and IMHO is not nearly useful enough to warrant it. [ Note that no run-time type checking is needed for covariance of the return type. -adc ]