Aggregation Example

The incomplete classes below show a more complex example of the use of aggregation.

A "community" is comprised of homes, a set of streets and has a name.
A "home" is comprised of rooms, an address and a yard.
A "room" is comprised of dimensions and a type.
An "address" is comprised of street number, street name, city, state and zipcode.

As you look at these definitions, consider what some of the code would look like as we remember the relationships among the classes.

  1. The Community can only use the public interface provided by the House class (and the strings).
    The Community cannot directly call any method of the Address class, even though the House class uses an Address. (similarly for the Rooms).
    How would a member function of the Community gain access to the street name of the first House?

  2. The House can only use the public methods of Room and Address.
    How would a member function of the House access the 2nd Room's type?
//------------------ // a room in a house //------------------ class Room { public: enum RoomType = {Kitchen, LivingRoom, DiningRoom, Garage, BedRoom, PowderRoom}; Room (int length, int width, int height, RoomType type); int Area( ) const; RoomType GetRoomType( ) const; // accessors, mutators private: int m_length; int m_width; int m_height; RoomType m_type; }; //--------------------------- // The address of a house //--------------------------- class Address { public: Address ( ); // accessors, mutators const string& GetStreet( ) const; const string& GetCity ( ) const; private: string m_street; string m_city; string m_state; int m_zipcode; int m_streetNr; }; //------------------------- // a house with an address // and rooms //------------------------- class House { public: House ( ); const Address& GetAddress( ) const; void AddRoom( const Room& room ); void AddDoor( ); int NrRooms ( ) const; void ListRooms( ) const; // accessors, mutators // other public methods const Room& GetRoom( int index ) const; private: Address m_address; vector< Room > m_rooms; int m_nrDoors; double m_yardSize; // acres }; //------------------------ // A community of homes //------------------------ class Community { public: Community( ); int NrHouses ( ) const; void ListStreets( ) const; void BuildHome (const Home& home ); const string& GetName( ) const; const House& GetHouse( int index ) const; // other public methods private: vector< House > m_homes; vector< string > m_streets; string m_name; // other potential uses of aggregation School m_school; PlayGround m_playground; Name m_president; };

Last Modified: Monday, 28-Aug-2006 10:15:53 EDT