Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!wuarchive!usc!apple!netcom!teda!ditka!mcdchg!tellab5!balr!clrcom!rmartin From: rmartin@clear.com (Bob Martin) Newsgroups: comp.lang.c++ Subject: Re: How smart is operator resolution? Message-ID: <1990Nov30.042621.18213@clear.com> Date: 30 Nov 90 04:26:21 GMT References: <1747@umriscc.isc.umr.edu> Organization: Clear Communications, Inc. Lines: 64 In article <1747@umriscc.isc.umr.edu> 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? > >----------------------- BEGIN CODE ------------------------------------- > >#include > >const float pi = 3.14159; > >class figure { // abstract base class definition >protected: > float r, h; >public: > virtual float volume(void) = 0; >}; > >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; } > friend ostream &operator<<(ostream&, sphere&); >}; > >ostream &operator<<(ostream &strm, sphere &sph) { > strm << "VOLUME OF SPHERE:\n"; > strm << "radius = " << sph.r << "\n"; > strm << "volume = " << sph.volume() << "\n"; > return strm; >} ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This function defines the << operator for a sphere but not for a figure. > >main() { > figure *fig = new sphere(2.0); > cout << *fig << "\n"; ^^^^^^^^^^^^^^^^^^^^^^^^^^ The compiler cannot resolve this statement because there is not << operator defined for a figure. > return 0; >} > >------------------------- END CODE ------------------------------------- > >-- >James J. Hartley Internet: jamesh@cs.umr.edu >Department of Computer Science Bitnet: jamesh@cs.umr.edu@umrvmb.bitnet >University of Missouri - Rolla UUCP: ...!uunet!cs.umr.edu!jamesh What you need to do is declare a virtual function (say printOn) for sphere. Then in operator<<(ostream&, figure&) call the virtual function. -- +-Robert C. Martin-----+:RRR:::CCC:M:::::M:| Nobody is responsible for | | rmartin@clear.com |:R::R:C::::M:M:M:M:| my words but me. I want | | uunet!clrcom!rmartin |:RRR::C::::M::M::M:| all the credit, and all | +----------------------+:R::R::CCC:M:::::M:| the blame. So there. | Brought to you by Super Global Mega Corp .com