Using 'const' wherever possible is very very important. It can help to avoid mistakes and increase readability very much.
Personally, I even regard ability of using 'const' in code, as one of most important evidence to evaluate programmer's quality.
==== const member function ====
class A { void funcB(void) const; void funcA(int* pa) const; int* funcC(void) const; int a }
const member function(henceforth const member) cannot change class member variable. And, const member can call only const member. But, const member can call any C function.
By the way, there is no constraints about parameter in const member. So, following is possible.
Hack 1 void A::funcB(void) const { funcA(&a); } void A::funcA(int* pa) const { *pa = 9; } Hack 2 void A::funcB(void) const ( int* p = funcC(); *p = 8; } int* A::funcC(void) const {return &a;}
Even if, funcB changes value of member variable, it compiles well. This is one of week points of const member.
==== const & pointer ====
const int* p; // *1 - (*p) is const int const *p; // *2 - (*p) is const int* const p; // *3 - (p) is const
case *1, *2;
"*p = 4" is error, but, "p = &b" is OK.
So, we can hack this like "*((int*)p) = 9;".
case *3
contrary to upper case. So, we should initialize pointer before using it.
==== const & multiple pointer ====
const int** p; // *1 int const **p; // *2 int* const *p; // *3 int** const p: // *4 int* pb; const int* cpb int b;
case *1, *2.
// p = &pb; // error - "cannot convert from 'int **' to 'const int **"
p = &cpb; // OK.
*p = &b;
// **p = 8; // error - "you cannot assign to a variable that is const"
*((int*)*p) = 8 // OK. Hack!
case *3
p = &pb; // OK
*p = &b; // error - "you cannot assign to a variable that is const"
case *4
p = &pb; // error - "you cannot assign to a variable that is const". p should be initialized before used.
'Language > C&C++' 카테고리의 다른 글
[C/C++] new operator... deeper.... (0) | 2009.08.24 |
---|---|
[C/C++] Remind! Limitation of constructor; It doens't give return value!.. (0) | 2009.05.15 |
[C/C++] What is 'variable'?? (0) | 2009.01.24 |
[C/C++] Try to avoid cross-dependency between selective-compile-switches. (0) | 2008.12.14 |
[C/C++] Using static variable in large-size-file. (0) | 2008.09.09 |