forked from wadehuber/codeexamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstmethod.cpp
More file actions
67 lines (53 loc) · 1.67 KB
/
Copy pathconstmethod.cpp
File metadata and controls
67 lines (53 loc) · 1.67 KB
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
#include<iostream>
class ConstClass {
private:
int num;
public:
ConstClass(int x) { num = x; }
// print() should not change the object, so we declare it const
void print() const { std::cout << "num=" << num << std::endl;}
// const is part of the method signature, so func() is overloaded
void func() { std::cout << "func (non-const) " << num << std::endl; }
void func() const { std::cout << "func (const) " << num << std::endl; }
};
// obj is passed by constant reference
void stuff(const ConstClass& obj) {
std::cout << "stuff function:" << std::endl;
obj.print();
obj.func();
std::cout << std::endl;
}
int main() {
ConstClass nonConstObj(20);
const ConstClass constObj(10);
ConstClass * ptr = &nonConstObj;
const ConstClass * constPtr = &constObj;
std::cout << "nonConstObj:" << std::endl;
nonConstObj.print();
nonConstObj.func();
std::cout << std::endl;
std::cout << "constObj:" << std::endl;
constObj.print();
constObj.func();
std::cout << std::endl;
std::cout << "non-const pointer to nonConstObj:" << std::endl;
ptr->print();
ptr->func();
std::cout << std::endl;
std::cout << "const pointer to constObj:" << std::endl;
constPtr->print();
constPtr->func();
std::cout << std::endl;
constPtr = &nonConstObj;
std::cout << "const pointer to nonConstObj:" << std::endl;
constPtr->print();
constPtr->func();
std::cout << std::endl;
std::cout << "stuff(nonConstObj):" << std::endl;
stuff(nonConstObj);
std::cout << std::endl;
std::cout << "stuff(constObj):" << std::endl;
stuff(constObj);
std::cout << std::endl;
return 0;
}