Content deleted Content added
mNo edit summary |
|||
Line 63:
constC.Set(10); // Error! Set() is a non-const method and constC is a const-qualified object
}
Often the programmer will supply both a <code>const</code> and a non-<code>const</code> method with the same name (but possibly quite different uses) in a class to accommodate both types of callers. Consider:
Line 70 ⟶ 69:
{
int data[100];
int & Get(int i) { return data[i]; }
int const & Get(int i) const { return data[i]; }
};
void Foo( MyArray & array, MyArray const & constArray )
{
// Get a reference to an array element
// and modify its referenced value.
array.Get( 5 ) = 42;
constArray.Get( 5 ) = 42; // Error!
}
The <code>const</code>-ness of the calling object determines which version of <code>MyArray::Get()</code> will be invoked and thus whether or not the caller is given a reference with which he can manipulate or only observe the private data in the object. (Returning a <code>const</code> reference to an <code>int</code>, instead of merely returning the <code>int</code> by value, may be overkill in the second method, but the same technique can be used for arbitrary types, as in the [[Standard Template Library]].)
|