-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdefault_values.cpp
60 lines (51 loc) · 1.14 KB
/
default_values.cpp
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <vector>
// example class to demonstrate
// lvalue and rvalues
class X
{
public:
// constructor; 0 parameter constructor
X() : val(0) { std::cout << "X obj created" << std::endl; };
X &operator+=(int o)
{
val += o;
return *this;
}
friend std::ostream &operator<<(std::ostream &o, const X &x)
{
o << x.val;
return o;
}
private:
int val;
};
// the X() statement gets evaluated every time,
void defaultExample(int val, X obj = X())
{
obj += val;
std::cout << "obj is now" << obj << std::endl;
}
// const lvalues can be bound to newly created objects
void defaultExample2(const X &obj = X())
{
// can't increment it bc it is const
// obj += val
std::cout << "obj is" << obj << std::endl;
}
// this would'nt work; anyone know why?
// void incorrectDefaultExample(int val, X &obj = X())
// {
// obj += val;
// std::cout << "obj is" << obj << std::endl;
// }
int main()
{
// default parameter lifetime
defaultExample(1);
defaultExample(3);
// const lvalue binding
defaultExample2();
defaultExample2();
return 0;
}