Path: utzoo!utgpu!news-server.csri.toronto.edu!torsqnt!geac!alias!fred!rae From: rae@gpu.utcs.toronto.edu (Reid Ellis) Newsgroups: comp.lang.c++ Subject: Re: Why ask an object its type?? Message-ID: Date: 6 Oct 90 19:25:16 GMT References: <995@halley.UUCP> <57751@microsoft.UUCP> <11810@cadillac.CAD.MCC.COM> Sender: Reid Ellis Reply-To: Reid Ellis Organization: Alias Research, Inc. Toronto ON Canada Lines: 51 In reference to casting of base objects to their derivatives, I'd like to offer a mechanism that does not sacrifice strong typing while at the same time incurring a cost of a method call and a minimum number of methods in the base class [i.e. not requiring all virtual methods for all derivatives to be declared in the base class]. I call it a `safe downcast'. Given a base class, "B", and a derived class, "D", we define a method in the base class, "virtual D* B::asD()". The base class defines this function as failing an assertion [i.e. a panic(), exit(1), what have you] while the derived class defines it as "return this;". This allows functionality to be added to derived classes without having an impact on the base class' interface. However, deriving new classes incurs the cost of adding an "as*()" method to the base class, but only if such functionality is required. Note that this is hierarchical in that if we now derive "F" from "D", we define "F* D::asF()", and can then say "bPtr->asD()->asF()->fMethod()". An alternative to invoking "panic()" in the base class method is to simply return NULL, which allows for error checking on failure. But it makes statements such as "x->asD()->asF->fMethod()" illegal, or at least unwise at best. Is this original, or is it already in use somewhere like the NIH library? Relevant previous dicussion follows. Hit 'n' [or whatever] to skip. What does xrn do with ^L's? ... Marshall Cline I'd like to ask a key question: ``WHY ASK AN OBJECT ITS TYPE?'' [2] you might ask an object its type so you can do a safe down-cast. ... the (strongly typed) virtual mechanism is preferred. Paul Vaughan argues that casting from base to derived objects accomplishes modularity: One part of the program can really only deal with types it understands but the communication between the parts of the program uses a particular base type. There are reasons not to put all the methods onto the base type. ... About the only alternative is to put all possible methods on the base class with null definitions. However, this eventually becomes equivalent to programming with ordinary C structs and functions. -- Reid Ellis 264 Broadway Avenue, Toronto ON, M4P 1V9 Canada rae@gpu.utcs.toronto.edu || rae%alias@csri.toronto.edu || +1 416 487 1383