Advanced Inheritance 545
16
Accessing Members of the Aggregated Class ................................................
A class that aggregates other objects does not have special access to those object’s mem-
ber data and functions. Rather, it has whatever access is normally exposed. For example,
Employeeobjects do not have special access to the member variables of String. If the
Employeeobject Edietries to access the private member variable itsLenof its own
itsFirstNamemember variable, it receives a compile-time error. This is not much of a
burden, however. The accessor functions provide an interface for the Stringclass, and
the Employeeclass need not worry about the implementation details, any more than it
worries about how the integer variable,itsSalary, stores its information.
Aggregated members don’t have any special access to the members of the
class within which they are aggregated. The only ability they have to access
the instance that aggregates them is to have a copy of the owner class
“this” pointer passed to them at creation or at some point thereafter. If
this is done, they have the same normal access to that object as they would
to any other.
NOTE
Controlling Access to Aggregated Members..................................................
Note that the Stringclass provides an overloaded plus operator:operator+. The
designer of the Employeeclass has blocked access to the operator+being called on
Employeeobjects by declaring that all the string accessors, such as GetFirstName(),
return a constant reference. Because operator+is not (and can’t be) a constfunction (it
changes the object it is called on), attempting to write the following causes 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 constand that the member function itself is no
longer const. Changing just the return value is not sufficient to overload the function
name; you must change the “constness” of the function itself.