-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconst.cpp
More file actions
45 lines (36 loc) · 959 Bytes
/
const.cpp
File metadata and controls
45 lines (36 loc) · 959 Bytes
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
#include<iostream>
#include<string>
using namespace std;
class Example {
// const variable
const int count = 10;
public:
Example() {};
Example(int c) : count(c) {}; // initialize const in initializer list.
void getCount() {
cout << count;
}
void setCount(int c) {
// this->count = c;
// returns error because count is not modifiable value.
}
};
class Student {
int age; // non-const
const int id; // const
public:
Student(int a, int i): age(a), id(i) {}
void updateAge(int newAge) {
age = newAge; // ✅ allowed
// id = 10; // ❌ error: const can't be changed anywhere
}
void show() const {
// age = 20; // ❌ error: can't modify in const function
// id = 5; // ❌ error: const can't be modified
cout << age << " " << id << endl;
}
};
int main() {
Example e1(5);
e1.getCount();
}