default arguments

Can C++ default the values of a methods areguments?

Ie. foo( int start, int end );

I'd like to be able to call this as:

foo( 123, 456 ); // Do foo on elements 123 thru 456

or

foo( , 456 ); // Do foo on elements 0 thru 456

or

foo( 123, ); // Do foo on elements 123 thru foo::max
// (whatever that is for this foo)
Yeah. You'd need to tailor it somewhat to meet those requirements. Basically, when giving a default value to a function in C++ you eliminate the need for that argument to be passed in.

1
2
3
4
5
6
7
void SomeFunction( int x=100 )
{
   std::cout << x << std::endl;
}

someFunction(); // Prints 100
someFunction(50); // Prints 50 


Last edited on
Hm. Seems there is no way to omit a parameter than is not the last?

This compiles/runs okey:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int count( int lo = 0, int hi = 16384 ) {
    return hi - lo;
}

int main() {
    cout << count() << endl;
    cout << count( 1000 ) << endl;
//    cout << count( , 1000 ) << endl;
    cout << count( 1000, 10000 ) << endl;
}


But uncomment the commented line and I get
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
test.cpp
test.cpp(11) : error C2143: syntax error : missing ')' before ','
test.cpp(11) : error C2059: syntax error : ')'
test.cpp(11) : error C2563: mismatch in formal parameter list
test.cpp(11) : error C2568: '<<' : 
    unable to resolve function overload
C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\Include\ostream(974):
could be 'std::basic_ostream<_Elem,_Traits> 
&std::endl(std::basic_ostream<_Elem,_Traits> &)'
        with
        [
            _Elem=wchar_t,
            _Traits=std::char_traits<wchar_t>
        ]

C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\Include\ostream(966):
or       'std::basic_ostream<_Elem,_Traits>
&std::endl(std::basic_ostream<_Elem,_Traits> &)'
        with
        [
            _Elem=char,
            _Traits=std::char_traits<char>
        ]
C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\Include\ostream(940):
or       'std::basic_ostream<_Elem,_Traits>
&std::endl(std::basic_ostream<_Elem,_Traits> &)'


Is there no way around that?
As your parameters have the same type int I do not see any way to achieve what you want except to declare one more function with a different name that will accept the second parameter of the original function as its first parameter maybe with same default argument.
Topic archived. No new replies allowed.