Friday, 15 June 2012

c++ - Default Argument in Virtual Function -



c++ - Default Argument in Virtual Function -

this question has reply here:

virtual function default arguments behaviour 6 answers

please help me find reasons behind it:

#include <iostream> using std::cout; class { public: virtual void fun(int = 5) { cout<<a; } }; class b::public { public: void fun(int = 10) { cout<<"inside a::b::fun().\n"; cout<<"\n"<<a; } }; int _tmain(int argc, _tchar* argv[]) { *obj = new b(); obj->fun(); reutrn 0; }

althought calling b::fun(), still printing 5, why , how work.?

a *obj = new b(); obj->fun();

in code, fun() invoked polymorphically - caller uses (only) knowledge of a::fun(), phone call dispatched pointer redirects implementation b::fun(). function argument - a / 5 - provided caller before redirected phone call though (way before - during compilation) - a's default seen, not b's.

if want seem expect, might find works have a::fun(int = -1) or other sentinel value, implementations of fun checking sentinel value replacing 5 or 10 desired. way, implementation-specific values incorporated during call, not before.

c++ virtual-functions default-arguments

No comments:

Post a Comment