`
Use Cases
- We basically have 3 use cases of
const
keyword:
- Restrict the change in value of a Variable
- Restrict the change of Pointer
- Restrict the class method to change the variables of that class
Restrict the change in value of a Variable
1 2
| const int x = 7; x = 10;
|
1 2
| const int& p = 9; p = 10;
|
1 2 3 4 5 6
| const int* a = NULL;
int val = 2; a = &val;
*a = 10;
|
Another way of writing:
const int x = 7
is identical to int const x = 7
const int& p = 9
is identical to int const & p = 9
const int* a = NULL
is identical to int const * a = NULL
- Generalization:
const
can be written on either side of datatype name (e.g. int, float, class_name etc.) in order to restrict the change in value.
Restrict the change of a Pointer
1 2 3 4 5 6
| int* const a = NULL;
int val = 2; a = &val;
*a = 10;
|
Restrict the class method to change the variables of that class
1 2 3 4 5 6 7 8 9
| class Person { int age=7;
int modify_age() const { age = 10; } };
|
Combining all three
1 2 3 4 5 6 7 8 9 10
| class Dummy { int* ptr = NULL;
const int* const get_ptr() const { return ptr; }
};
|
get_ptr
is a constant method which cannot change the variables of that class and returns a pointer which cannot be changed nor can be its content.
const int* const get_ptr() const
is identical to int const * const get_ptr() const
- Second one seems more uniform as
const
always appear on the right side of what it is applied on. That is:
int const
makes value const
* cont
makes pointer const
get_ptr() const
makes method const
TODO
void function_name(const int x)
const objects can call const methods only
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
| class Person { private: int age = 7;
public: int get_age() const { return age; }
void set_age(int val) { age = val; } };
int main() { const Person p; p.get_age(); p.set_age(10);
return 0; }
|