swestrup: (Default)
[personal profile] swestrup
I hadn't realized until just now that dummy parameters were applied based on the static type of their function call. So this code:

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.

Date: 2008-12-03 06:26 pm (UTC)
From: [identity profile] sps.livejournal.com
There's a typo in the second call, right?

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.

Date: 2008-12-04 11:58 pm (UTC)
From: [identity profile] pphaneuf.livejournal.com
Default parameters are treacherous in many situations, especially when changing them around (think also of a compiled shared library user, ouch!). That's a good example. I prefer an inline overload, myself.

January 2017

S M T W T F S
1234567
891011121314
15161718192021
22232425262728
293031    

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Jan. 8th, 2026 01:08 am
Powered by Dreamwidth Studios