CPP 9
CPP 9
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!