Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!usc!apple!hercules!sparkyfs!mckenney From: mckenney@sparkyfs.istc.sri.com (Paul Mckenney) Newsgroups: comp.lang.c++ Subject: Re: reference parameters for overloaded operators Message-ID: <32584@sparkyfs.istc.sri.com> Date: 21 Aug 90 16:25:18 GMT References: <1990Aug13.144540.7804@ctk1.UUCP> <26CBE285.4EC2@tct.uucp> <56749@microsoft.UUCP> <117703@linus.mitre.org> Reply-To: mckenney@perth.itstd.sri.com.UUCP (Paul E. McKenney) Organization: SRI International, Menlo Park, CA 94025 Lines: 57 In article <117703@linus.mitre.org> fkuhl@ralph.mitre.org (F. S. Kuhl) writes: >In article <56749@microsoft.UUCP> jimad@microsoft.UUCP (Jim ADCOCK) writes: >>Also, whenever doing polymorphic programming [as in vtables and virtual >>functions, not polymophic via parameter overloading] one should call >>by reference to avoid the slicing problem. >OK, I give. What's the slicing problem? C++ already looks to my >uninitiated mind like a Swiss Army knife. Suppose you have a function expecting a base-class object for its parameter: class B { int a; public: virtual void q() { cout << "B::q\n"; } }; class D : public B { int b; public: void q() { cout << "D::q\n"; } }; void f(B x); Then a call to ``f'' passing in a derived object: D y; f(y); will coerce from class D to class B in the process of initializing formal parameter object ``x'' from object ``y''. Conceptually, this involves ``slicing'' off the definitions that class D adds to class B, in this case the member variable ``b''. In addition, if ``f'' invokes member function ``q'': y.q(); class B's definition of ``q'' will be used (in other worded, ``B::q'' will be printed). Formal parameter ``x'' is in all ways an object of class ``B''. Suppose that another function uses a reference rather than value parameter: void g(B &z); Then a call to ``g'' passing in a derived object: g(y); would pass in a pointer to the instance ``y''. No ``slicing'' would occur, member variable ``z.b'' would be intact, and if ``g'' invoked virtual member function ``z.q()'', ``D::q'' would be printed. None of the ``D''-ness of instance ``y'' has been lost. Hope this helps, Paul