9/26/2015
Like in Java, you can add modifiers to methods, such as
specifying what they can throw or declaring them
as const
. These are very powerful and fit
right into the type system.
Let's look at how to apply const
properly to
methods. Last time we showed two methods that retrieve
elements from the Array
:
// unchecked const access T& operator[](int index) { return array_start[index]; } // checked access - throws exception if out of bounds T& at(int index) { if(index < 0 || index >= length) throw std::out_of_range("Index out of range"); return array_start[index]; }
None of the methods on the Array
class have
a const
flag so a const Array
is
useless! Looking at these methods, it makes sense to make
a const operator[]
method that will return
a const
reference rather than a normal
reference. Let's implement that:
// unchecked const access const T& operator[](int index) const { return array_start[index]; } // checked const access const T& at(int index) const { if(index < 0 || index >= length) throw std::out_of_range("Index out of range"); return array_start[index]; }
Now we can read elements from our const Array
without changing it! Each element returned will be
a const
reference so cannot be modified,
ensuring the const
ness of the
Array
.
I'll showing template meta programming next time and how to make your classes work with the standard library functions.