I'm fairly new to C++ and trying to understand some code I'm looking at:
bool ClassName::ClassMethod(const STRUCT_THING* const parameterName) {}
What is the purpose of the second "const" in the argument? How does it differ from just const STRUCT_THING* parameterName?
Thanks!
That means it is a const pointer to a const variable.
See the following examples:
int x = 5; // non-const int
int* y = &x; // non-const pointer to non-const int
int const a = 3; // const int
int* const b = &a; // const pointer to non-const int
int const* const c = &a; // const pointer to const int
So you can see that two things have the potential to be mutable, the variable and the pointer. Either of these two can be const.
A const variable works just as you'd imagine:
int foo = 10;
foo += 5; // Okay!
int const bar = 5;
bar += 3; // Not okay! Should result in a compiler warning (at least)
A const pointer works the same way:
int foo = 10;
int bar = 5;
int* a = &foo;
a = &bar; // Okay!
int* const b = &foo;
b = &bar; // Not okay! Should also result in a compiler warning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With