default parameter

I make a function

1
2
3
4
5
6
7
8
9
10
11
void fun1(int x=10, int y=20, int z=30){
// code
}

int main(){

fun1(,y,)// I want to pass 2nd parameter value
         //other values are default

}
is this possible in cpp.
it is possible in php;
Last edited on
You can only omit arguments starting from the right side. So you would have to say:

fun1(10,y);

There are a variety of ways around this, but they require either arguments of distinct types or a lot more code than a simple function header.

The simplest way I like to use is by using a temporary object's destructor or conversion operator:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>

struct fun1
{
  int mx, my, mz;
  fun1( int x=10, int y=20, int z=30 ): mx(x), my(y), mz(z) { }
  fun1& x( int x ) { mx = x; return *this; }
  fun1& y( int y ) { my = y; return *this; }
  fun1& z( int z ) { mz = z; return *this; }

  // Use this one for functions of the type:
  // void fun1( x, y, z )
 ~fun1()
  {
    std::cout << "(" << mx << ", " << my << ", " << mz << ")\n";
  }

  // Use this one for functions of the type:
  // int fun1( x, y, z )
  operator int () const
  {
    return mx * my + mz;
  }
};

int main()
{
  // print "(10, 12, 30)"
  fun1().y(12);

  // x = 10*74+30 = 770
  // and print "(10, 74, 30)"
  int x = fun1().y(74);
  std::cout << x << "\n";
}

Hope this helps.
thnx actually more than thax really good one. very smart tics.

Topic archived. No new replies allowed.