the output of code 15 , don't know why. think uses x=5 in foo function don't know why. can me ?
#include <iostream> #include <string> using namespace std; struct { virtual int foo(int x = 5) { return x*2; } }; struct b : public { int foo(int x = 10) { return x*3; } }; int main(int argc, char** argv) { a* = new b; cout << a->foo(); return 0; }
i think uses
x=5infoofunction don't know why.
yes, default argument base class a's declaration (i.e. 5) used here, because you're calling foo() on object static type a*. default arguments decided based on static type, other dynamic type.
the standard has clear explanation this, $8.3.6/10 default arguments [dcl.fct.default]:
(emphasis mine)
a virtual function call ([class.virtual]) uses default arguments in declaration of virtual function determined static type of pointer or reference denoting object. overriding function in derived class not acquire default arguments function overrides. [ example:
struct { virtual void f(int = 7); }; struct b : public { void f(int a); }; void m() { b* pb = new b; a* pa = pb; pa->f(); // ok, calls pa->b::f(7) pb->f(); // error: wrong number of arguments b::f() }— end example ]
Comments
Post a Comment