|
|
|
|
|
|
|
Accessing Members of the Contained Class |
|
|
|
|
|
|
|
|
Employee objects do not have special access to the member variables of String. If the employee object Edie tried to access the member variable itsLen of its own itsFirstName member variable, it would get a compile-time error. This is not much of a burden, however. The accessor functions provide an interface for the String class, and the Employee class need not worry about the implementation details any more than it worries about how the integer variable, itsSalary, stores its information. |
|
|
|
|
|
|
|
|
Filtering Access to Contained Members. |
|
|
|
|
|
|
|
|
Note that the String class provides the operator+. The designer of the Employee class has blocked access to the operator+ being called on Employee objects by declaring that all the string accessors, such as GetFirstName(), return a constant reference. Because operator+ is not (and can't be) a const function (because it changes the object it is called on), attempting to write the following will cause a compile-time error: |
|
|
|
|
|
|
|
|
String buffer = Edie.GetFirstName() + Edie.GetLastName(); |
|
|
|
|
|
|
|
|
GetFirstName() returns a constant String, and you can't call operator+ on a constant object. |
|
|
|
|
|
|
|
|
To fix this, overload GetFirstName() to be non-const: |
|
|
|
|
|
|
|
|
const String & GetFirstName() const { return itsFirstName; }
String & GetFirstName() { return itsFirstName; } |
|
|
|
|
|
|
|
|
Note that the return value is no longer const and that the member function itself is no longer const. Changing the return value is not sufficient to overload the function name; you must change the constancy of the function itself. |
|
|
|
|
|
|
|
|
It is important to note that the user of an Employee class pays the price of each of those string objects every time one is constructed or a copy of the Employee is made. |
|
|
|
|
|
|
|
|
Uncommenting the cout statements in Listing 20.3 (lines 38, 52, 64, 76, 84, and 101) reveals how often these are called. |
|
|
|
|
|
|
|
|
Copying by Value Versus by Reference |
|
|
|
|
|
|
|
|
When you pass Employee objects by value, all their contained strings are copied as well, and therefore copy constructors are called. This is very expensive; it takes up memory and it takes time. |
|
|
|
|
|