You are on page 1of 2

Using Const

• If your function does not modify


parameters, you should declare them as
Intro to C++ part 9 “const”.
• “const” parameters cannot be modified
1. Richard Watson, notes on C++
2. Winston, P.H., “On to C++”
ISBN: 0-201-58043-8

Calling Member Functions This Should Work…


• Sometimes, you need to call member • But is doesn’t compile
functions of your const parameters. • By declaring “first” and “second” as const,
• Example: max function for Queues: you promised not to modify them
Queue Max(const Queue &first, const Queue &second) { • The compiler will complain about calling
if (first.Size () > second.Size()) {
return first; “Size”
} else { • The compiler doesn’t know that “Size”
return second;
} doesn’t modify the Queue
}

Making Class Members Const • Old “Size” prototype:


/* Returns the number of elements in me */
• Class member functions can be declared int Size();

as “const”
• New “Size” prototype:
• Members declared as const cannot modify
fields of the class. /* Returns the number of elements in me */
int Size() const;
• Let’s fix our Size function!
• Definition header changes too:
int Queue::Size() const {
// Algorithm comment:
// n is the size of the queue, return it.
return n;
}

1
Can’t Go Const Crazy Dequeue Can’t Be Const
• Why not declare all functions as “const”? • Which line(s) keep this from compiling?
It would make our lives easier.
• Compiler won’t let you declare a function char Queue::Dequeue() const {
char head = contents[0];
as “const” if it modifies any field of the // shift all elements down 1 slot towards the head.
for(int i = 0; i < n-1; i++) {
class. contents[i] = contents[i+1];
}
• Example… n--; // update size <-- THIS ONE!
return head;
}

The Lesson…
• You *can* change values that are pointed- • A member function can be “const” if it
to by fields of the class. does not modify fields of the class
• An obvious way around const is to make • Should declare all such members as const
all your fields pointers • Although the compiler won’t stop you, you
• But you should not be looking for ways shouldn’t modify contents of memory that
around const. fields point to in “const” functions.
• Const is your friend!

You might also like