Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!sdd.hp.com!zaphod.mps.ohio-state.edu!sol.ctr.columbia.edu!ira.uka.de!fuchs From: fuchs@it.uka.de (Harald Fuchs) Newsgroups: comp.lang.c++ Subject: Re: How smart is operator resolution? Message-ID: Date: 29 Nov 90 18:11:22 GMT References: <1747@umriscc.isc.umr.edu> Sender: news@ira.uka.de (USENET News System) Organization: University of Karlsruhe, FRG Lines: 49 jamesh@cs.umr.edu (James Hartley) writes: >I recently tried taking advantage of virtual functions by creating a generic >routine which would take a base class pointer and output the appropriate >derived class where the insertor was properly overloaded. The following >program attempts to illustrate the idea. Turbo C++ balks at the output >statement in main() because the insertor is not defined with respect to >the base class. Is this operator resolution beyond the restraints of the >language, or is this a bug in the compiler? You get the inserter you want by making it virtual. You can't do this directly because the standard insertion operator<< expects your "figure" to be the 2nd argument. Do it like that: class figure { // abstract base class definition protected: float r, h; public: virtual float volume(void) = 0; virtual void printOn (ostream&) const = 0; }; inline ostream& operator<< (ostream& s, const figure& x) { x.printOn (s); return s; } class sphere : public figure { // derived class definition public: sphere(float radius) { r = radius; } virtual float volume(void) { return 4.0 / 3.0 * pi * r * r * r; } void printOn (ostream&) const; }; void sphere::printOn (ostream& strm) const { strm << "VOLUME OF SPHERE:\n"; strm << "radius = " << sph.r << "\n"; strm << "volume = " << sph.volume() << "\n"; } main() { figure *fig = new sphere (2.0); cout << *fig << "\n"; return 0; } -- Harald Fuchs ... *gulp*