next up previous contents
Next: What does const mean Up: Software Development and Coding Previous: What does a pointer   Contents

Using const

Appropriate usage of the const modifier enforces data encapsulation and protection. It is conventionally ranked in importance about as high as a mall cop, but it has far more power than a mall cop when used appropriately. Use the const modifier liberally and whenever possible. In some cases liberal use of const will bring to light some serious bugs.


Table: Using const.
Use Do not use
void foo(const CMyStruct &ms); void foo(CMyStruct ms);
int getProp() const; int getProp();
const char* getName() const; CString getName();
const CMyStruct* getStruct() const; CMyStruct* getStruct();


If you want to allow direct access to a member variable via a function call, make two versions of the function:

  1. MyStruct& GetStruct();
  2. const MyStruct& GetStruct() const;

This will allow both types of access at the appropriate time such as on the left or right side of an assignment operator.



Subsections
next up previous contents
Next: What does const mean Up: Software Development and Coding Previous: What does a pointer   Contents
Falko Kuester 2001-08-24