Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are default arguments trailing ones?

Tags:

c++

Why are default arguments in C++ trailing ones?

like image 560
Ashish Avatar asked Aug 17 '10 11:08

Ashish


2 Answers

if you had void func(int a = 0, int b);, how would you specify to use the default parameter in calling this function?

like image 184
tenfour Avatar answered Oct 09 '22 07:10

tenfour


Because that is how the language has been designed.

A more interesting question would be: what are the alternatives?

Suppose you have void f(A a = MyA, B b);

  • Placeholder / blank argument: f(_, abee) or f(, abee)
  • Named arguments (like in Python): f(b = abee)

But those are niceties and certainly not necessary, because unlike Python C++ supports function overloading:

  • void f(A a, B b);
  • void f(B b) { f(MyA, b); }

and thus the default arguments are unnecessary... especially considering that there are issues when used with polymorphic code because default arguments are statically resolved (compile-time).

struct Base
{
  virtual void func(int g = 3);
};

struct Derived
{
  virtual void func(int g = 4);
};

int main(int argc, char* argv[])
{
  Derived d;
  d.func(); // Derived::func invoked with g == 4

  Base& b = d;
  b.func(); // Derived::func invoked with g == 3 (AH !!)
}

Regarding named parameters:

The feature can be emulated using function objects.

class Func
{
public:
  Func(B b): mA(MyA), mB(b) {}

  A& a(A a) { mA = a; }
  B& b(B b) { mB = b; }

  void operator()() { func(mA, mB); }
private:
  A mA;
  B mB;
};

int main(int argc, char* argv[])
{
  A a;
  B b;
  Func(b)();
  Func(b).a(a)();
}

In case you don't want to copy the arguments, you have the possibility to use references/pointers though it can get complicated.

It's a handy idiom when you have a whole lot of defaults with no real order of priority.

like image 25
Matthieu M. Avatar answered Oct 09 '22 08:10

Matthieu M.