Reference and optional parameters C+

why can't reference parameters be optional parameters in C+? I had an instructor ask this today and I'm having trouble even with research to locate an answer.
A reference parameter may be declared with a default argument.
For instance: void foo( std::ostream& stm = std::cout ) ;

When calling the function, passing the argument is optional. For instance: foo() ; // calls foo( std::cout )

C++17: In std::optional<T>, the type T can't be a reference type;
the standard requires that T must be an object type.
Last edited on
They can.
1
2
3
void f(const std::string &s = "hello"){
    std::cout << s;
}
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
36
37
38
39
40
41
42
43
44
45
void Func1(int a, int b, int c)
{

}


void Func2(int a, int b, int c=3)
{

}


void Func3(int a=1, int b, int c)       // illegal, there is no way to call Func3 in a way to make parameter 1 optional
{

}


void Func4(int & a, int b, int & c)
{

}


void Func5(int & a, int b, int & c=3)     // illegal, no way to utilize 3rd parameters default as we will need to pass an actual reference through for c
{

}


int main()
{
   Func1(1, 2, 3);      // ok
   
   Func2(1, 2);         // ok - 3rd parameter is optional since we have a default value.
   
   Func3(2, 3);         // illegal - the compiler can't guess that you are intending for parameter 1's default to be used.
   
   int a = 1, c = 3;
   Func4(a, 2, c);      // must pass variables for parameter 1 and parameter 3 as they are passed by reference
                        // which means that Func4 will be able to update the actual values that these references refer to  
                        
   Func5(a, 2)          // illegal - Func5 requires reference for parameter 3 which has to be of type int.
} 
Topic archived. No new replies allowed.