-
Notifications
You must be signed in to change notification settings - Fork 0
/
const-func.cpp
104 lines (90 loc) · 1.58 KB
/
const-func.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <new>
#include <memory>
#include <atomic>
#include <thread>
#include <mutex>
#include <future>
#include <utility>
#include <tuple>
#include <string>
#include <array>
#include <vector>
#include <deque>
#include <list>
#include <forward_list>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <stack>
#include <queue>
#include <algorithm>
#include <iterator>
#include <functional>
#include <regex>
#include <bitset>
#include <iostream>
using namespace std;
/**
* const used with functions
*/
class Dog
{
int age;
string name;
public:
Dog()
{
age = 3;
name = "dummy";
}
// const parameters
void setAge1(const int a)
{
age = a;
}
// <- fails: 'void Dog::setAge1(int)' cannot be overloaded
// void setAge1(int a) {
// age = a;
// }
void setAge2(int &a)
{
age = a;
a++; // modifies variable outside
}
void setAgeConstRef3(const int &a)
{
age = a;
// a++; // <- fails
}
// const return value: caller cannot change the value
const string &getName()
{
return name;
}
// const is useless here
// const string getName() {
// return name;
// }
// const function - does not change member variables
void printDogName() const
{
cout << name << " const " << endl;
}
// overload - separate function
void printDogName()
{
cout << name << " non-const " << endl;
}
};
int main()
{
int i = 9;
Dog d;
d.setAge2(i);
d.setAgeConstRef3(i);
d.printDogName(); // calls second function
const Dog d2;
d2.printDogName(); // call first function
return 0;
}