const Member Functions

If you declare a class member function to be 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 as 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;

Get accessor functions (some programmers call them “getter 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. It 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 then the implementation of that function changes the object (by changing the value of any of its members), the compiler will flag it as an error. For example, if you wrote GetAge() so that it kept count of the number of times that Cat was asked its age, it would generate a compiler error. You would be changing the Cat object by calling this method.

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.218.226