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.
2. The static variables are not in object scope instead it is of class scope.i.e here only one 'd' will
View Tutorial By: Karthick at 2011-06-29 06:55:17
3. const does not change object. but static shared the values of more than objects. these are two diffe
View Tutorial By: hassan at 2010-06-06 11:29:00
4. u said that const function cant change object.can they change a static member of object?
View Tutorial By: z at 2010-05-09 12:02:17
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