More C++ Geekery.
Dec. 3rd, 2008 08:39 amI hadn't realized until just now that dummy parameters were applied based on the static type of their function call. So this code:
Has the surprising output of:
The last output is because the dummy parameter is supplied at the beginning of the call to bp->f() which has a static signature of void Base::f(int=10), even though virtual function resolution ends up with Derived::f() getting called.
I don't know that I will ever have reason to use this fact, but its yet one more gotcha in C++ that I hadn't known about.
struct Base
{
virtual void f(int x=10)
{ cout << "Base: " << x << endl; }
};
struct Derived : public Base
{
virtual void f(int x=20)
{ cout << "Derived: " << x << endl; }
};
int main()
{
Base b;
Derived d;
Base *bp = &d;
b.f();
d.f();
bp->f();
return 0;
}
Has the surprising output of:
Base: 10
Derived: 20
Derived: 10
The last output is because the dummy parameter is supplied at the beginning of the call to bp->f() which has a static signature of void Base::f(int=10), even though virtual function resolution ends up with Derived::f() getting called.
I don't know that I will ever have reason to use this fact, but its yet one more gotcha in C++ that I hadn't known about.
no subject
Date: 2008-12-03 06:26 pm (UTC)This is "the expected behaviour" because of a very early decision in C++ that functions do not have multiple entry points: the default parameter does not generate an overload. Without it doing that, it's not clear how else this could behave.
Not that it doesn't suck. The overload semantics would have been much more elegant.
no subject
Date: 2008-12-03 07:09 pm (UTC)Oops, yeah. Now fixed.
And somehow, I'd always assumed that default parameters generated overloads. It would have been the more useful choice.
no subject
Date: 2008-12-04 11:58 pm (UTC)