Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: C++
Expertise: Beginner
Sep 11, 2000



Application Security Testing: An Integral Part of DevOps

Const Member Functions

What does the 'const' in the following funciton prototype mean?

class A
 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.

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date