-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconst member functions
50 lines (37 loc) · 1.19 KB
/
const member functions
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
A function becomes const when const keyword is used in function’s declaration. The idea of const functions is not allow them to modify the object on which they are called. It is recommended practice to make as many functions const as possible so that accidental changes to objects are avoided.
Following is a simple example of const function.
#include<iostream>
using namespace std;
class Test {
int value;
public:
Test(int v = 0) {value = v;}
// We get compiler error if we add a line like "value = 100;"
// in this function.
int getValue() const {return value;}
};
int main() {
Test t(20);
cout<<t.getValue();
return 0;
}
Output : 0
When a function is declared as const, it can be called on any type of object. Non-const functions can only be called by non-const objects.
For example the following program has compiler errors.
#include<iostream>
using namespace std;
class Test {
int value;
public:
Test(int v = 0) {value = v;}
int getValue() {return value;}
};
int main() {
const Test t;
cout << t.getValue();
return 0;
}
Run on IDE
Output:
passing 'const Test' as 'this' argument of 'int
Test::getValue()' discards qualifiers