Const Member Functions

What does the ‘const’ in the following funciton prototype mean?

class A{public: void fn (int a ) const;}

The const after a member function’s parameter list indicates that the function doesn’t change the state of its object. Such a function is also called an “observer function.” The use of const stems from the “design by contract” idiom, whereby a design premise (i.e., the function doesn’t change its object’s state) is enforced by the language. Thus, if you try to change the state of the object through this function, e.g., assign a new value to one of the members, the compiler will issue an error message.

The use of const is important for two reasons: it enables users to call such a function safely (even if they didn’t examine its definition), knowing that it doesn’t change its object’s state behind their back. Secondly, in a well-designed application, the lack of const after the parameter list indicates that the member function may change the state of its object.

A classic example of this dichotomy is the getter and setter functions: a setter is never const because it assigns a value to an object’s member. On the other hand, a getter merely returns an existing value without changing its object. Therefore, it’s declared const.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: