By: Emiley J
If you declare a class method const, you are promising that the method won't change the value of any of the members of the class. To declare a class method constant, put the keyword const after the parentheses but before the semicolon. The declaration of the constant member function SomeFunction() takes no arguments and returns void. It looks like this:
void SomeFunction() const;
Accessor functions are often declared as constant functions by using the const modifier. The Cat class has two accessor functions:
void SetAge(int anAge); int GetAge();
SetAge() cannot be const because it changes the member variable itsAge. GetAge(), on the other hand, can and should be const because it doesn't change the class at all. GetAge() simply returns the current value of the member variable itsAge. Therefore, the declaration of these functions should be written like this:
void SetAge(int anAge); int GetAge() const;
If you declare a function to be const, and the implementation of that function changes the object by changing the value of any of its members, the compiler flags it as an error. For example, if you wrote GetAge() in such a way that it kept count of the number of times that the Cat was asked its age, it would generate a compiler error. This is because you would be changing the Cat object by calling this method.
NOTE: Use const whenever possible. Declare member functions to be const whenever they should not change the object. This lets the compiler help you find errors; it's faster and less expensive than doing it yourself.
It is good programming practice to declare as many methods to be const as possible. Each time you do, you enable the compiler to catch your errors, instead of letting your errors become bugs that will show up when your program is running.
Most Viewed Articles (in C++ )
Latest Articles (in C++)
Comment on this tutorial
- Data Science
- Cloud Computing
- Java Beans
- Mac OS X
- Office 365
- Tech Reviews
Subscribe to Tutorials
2. const does not change object. but static shared th
View Tutorial By: hassan at 2010-06-06 11:29:00
3. The static variables are not in object scope inste
View Tutorial By: Karthick at 2011-06-29 06:55:17