Article View: gnu.g++.bug
Article #165Re: does "virtual" mean run-time computed function call ?
From: Gnanasekaran Swaminathan
Date: Tue, 04 Aug 1992 14:51
Date: Tue, 04 Aug 1992 14:51
59 lines
1877 bytes
1877 bytes
grosjean@masi.ibp.fr (Christophe GROSJEAN) wants to know why
his code doesn't exhibit virtual function call
behavior even though he has declared his functions
virtual.
:#include <stdio.h>
:#define DATA int
:
:class function
:{
:public:
: virtual void funcall(DATA i);
:};
:
:virtual void function::funcall(DATA i)
:{
: printf(" first definition = %d ", i);
:}
:
:class function2: public function
:{
:public:
: virtual void funcall(DATA i) { printf(" redefined = %d ", i); }
:};
:
:class Bug
:{
: public:
: void forall(class function f);
:};
:
:void Bug::forall(class function f)
:{
: f.funcall(1);
: f.funcall(2);
:}
You have to declare Bug::forall as follows:
void Bug::forall(function& f);
That is, you have to pass parameter f as a reference to
class function.
If you pass f by value like you have done here, when
you call Bug::funcall with an object whose class is
derived from function, only class function part of the
object is passed to Bug::funcall and hence, function::funcall()
is called rather than function2::funcall().
That is, the derived class funcall will override the
base class funcall for a virtual function funcall iff
the call is through a pointer or reference to base
class (see ARM pp. 208).
:main()
:{
: Bug b;
: function2 f;
: b.forall(f);
:}
Technical Details
Message-ID:
<1992Aug4.145138.3892@murdoch.acc.Virginia.EDU>Path:
arc1-ca.pugleaf.net!sparky!uunet!cis.ohio-state.edu!virginia.edu!gs4tReferences:
<9208031644.AA20662@cao-vlsi.ibp.fr>Show Full Headers
Complete Article Headers
Newsgroups: gnu.g++.bug Path: arc1-ca.pugleaf.net!sparky!uunet!cis.ohio-state.edu!virginia.edu!gs4t From: gs4t@virginia.edu (Gnanasekaran Swaminathan) Subject: Re: does "virtual" mean run-time computed function call ? Message-ID: <1992Aug4.145138.3892@murdoch.acc.Virginia.EDU> Sender: gnulists@ai.mit.edu Reply-To: gs4t@virginia.edu (Gnanasekaran Swaminathan) Organization: University of Virginia References: <9208031644.AA20662@cao-vlsi.ibp.fr> Distribution: gnu Date: Tue, 4 Aug 1992 14:51:38 GMT Approved: bug-g++@prep.ai.mit.edu Lines: 60