Composition Objects together Members of Classes

An AlarmClock object requirements to understand when that is supposed to sound its alarm, so why not include a Time object as a member of the AlarmClock class? together a capability is referred to as composition and also is periodically referred to as a has-a relationship. A course can have actually objects of other classes together members.

You are watching: When composition (one object having another object as a member) is used:

Software engineering Observation 10.5

A common type of software reusability is composition, in i m sorry a class has objects of various other classes together members.

When an object is created, that is constructor is dubbed automatically. Previously, us saw how to pass disagreements to the constructor of things we developed in main. This ar shows how an object's constructor deserve to pass disagreements to member-object constructors, i beg your pardon is completed via member initializers. Member objects are created in the order in which they are asserted in the class definition (not in the order castle are noted in the constructor's member initializer list) and before their enclosing course objects (sometimes referred to as host objects) room constructed.

The regime of Figs. 10.1010.14 uses class Date (Figs. 10.1010.11) and also class Employee (Figs. 10.1210.13) to show objects as members of other objects. The definition of course Employee (Fig. 10.12) includes private data members firstName, lastName, birthDate and hireDate. Members birthDate and hireDate are const objects of course Date, which has private data members month, day and year. The Employee constructor's header (Fig. 10.13, lines 1821) mentions that the constructor receives 4 parameters (first, last, dateOfBirth and also dateOfHire). The first two parameters are supplied in the constructor's human body to initialize the personality arrays firstName and also lastName. The last 2 parameters space passed via member initializers come the constructor for class Date. The colon (:) in the header the end the member initializers native the parameter list. The member initializers clues the Employee constructor parameters being passed come the constructors that the member day objects. Parameter dateOfBirth is happen to thing birthDate's constructor (Fig. 10.13, heat 20), and also parameter dateOfHire is pass to object hireDate's constructor (Fig. 10.13, line 21). Again, member initializers space separated by commas. As you study course Date (Fig. 10.10), notification that the course does not administer a constructor the receives a parameter of type Date. So, exactly how is the member initializer list in course Employee's constructor able come initialize the birthDate and also hireDate objects through passing date object's to their day constructors? as we discussed in chapter 9, the compiler gives each course with a default copy constructor that copies each member of the constructor's debate object right into the matching member that the object being initialized. Thing 11 discusses how programmers can define customized copy constructors.

Figure 10.10. Date class definition.

1 // Fig. 10.10: Date.h 2 // Date class definition; Member functions defined in Date.cpp 3 #ifndef DATE_H 4 #define DATE_H 5 6 course Date 7 8 public: 9 Date( int = 1, int = 1, int = 1900 ); // default constructor10 void print() const; // print date in month/day/year format11 ~Date(); // provided to confirm damage order12 private:13 int month; // 1-12 (January-December)14 int day; // 1-31 based upon month15 int year; // any type of year1617 // utility duty to check if job is proper for month and year18 int checkDay( int ) const;19 ; // end course Date2021 #endif

Figure 10.11. Date class member-function definitions.

(This items is presented on pages 536 - 537 in the print version)

1 // Fig. 10.11: Date.cpp 2 // Member-function interpretations for course Date. 3 #include 4 using std::cout; 5 utilizing std::endl; 6 7 #include "Date.h" // include date class meaning 8 9 // constructor confirms suitable value for month; calls10 // utility duty checkDay come confirm ideal value because that day11 Date::Date( int mn, int dy, int yr )12 {13 if ( mn > 0 && mn 0 && testDay

Figure 10.12. Employee class definition showing composition.

(This item is shown on web page 537 in the publish version)

1 // Fig. 10.12: Employee.h 2 // Employee course definition. 3 // Member functions characterized in Employee.cpp. 4 #ifndef EMPLOYEE_H 5 #define EMPLOYEE_H 6 7 #include "Date.h" // include date class meaning 8 9 class Employee10 11 public:12 Employee( const char * const, const char * const,13 const date &, const date & );14 void print() const;15 ~Employee(); // provided to confirm damage order16 private:17 char firstName< 25 >;18 char lastName< 25 >;19 const day birthDate; // composition: member object20 const date hireDate; // composition: member object21 ; // end class Employee2223 #endif

Figure 10.13. Employee class member-function definitions, consisting of constructor v a member initializer list.

(This items is displayed on pages 538 - 539 in the publish version)

1 // Fig. 10.13: Employee.cpp 2 // Member-function definitions for course Employee. 3 #include 4 utilizing std::cout; 5 making use of std::endl; 6 7 #include // strlen and also strncpy prototypes 8 making use of std::strlen; 9 using std::strncpy;1011 #include "Employee.h" // Employee class definition12 #include "Date.h" // Date course definition1314 // constructor provides member initializer perform to happen initializer15 // worths to constructors of member objects birthDate and also hireDate16 // 18 Employee::Employee( const char * const first, const char * const last,19 const day &dateOfBirth, const day &dateOfHire )20 : birthDate( dateOfBirth ), // initialize birthDate21 hireDate( dateOfHire ) // initialize hireDate22 {23 // copy an initial into firstName and be certain that the fits24 int size = strlen( first );25 size = ( size

Figure 10.14 create two day objects (lines 1112) and also passes them as arguments to the constructor that the Employee object produced in line 13. Line 16 outputs the Employee object's data. When each date object is developed in lines 1112, the date constructor characterized at currently 1128 the Fig. 10.11 display screens a line of calculation to present that the constructor was called (see the an initial two lines of the sample output).

Figure 10.14. Member-object initializers.

A member object does not should be initialized clearly through a member initializer. If a member initializer is no provided, the member object's default constructor will certainly be dubbed implicitly. Values, if any, established by the default constructor deserve to be overridden by collection functions. However, for complicated initialization, this method may require significant additional work and time.

Common Programming Error 10.6

*

A compilation error occurs if a member thing is not initialized with a member initializer and also the member object's class does not administer a default constructor (i.e., the member object's course defines one or an ext constructors, but none is a default constructor).

Performance tip 10.2

*

Initialize member objects explicitly through member initializers. This eliminates the overhead that "doubly initializing" member objectsonce once the member object's default constructor is called and also again when collection functions are dubbed in the constructor human body (or later) to initialize the member object.

Software engineering Observation 10.6

If a class member is an object of one more class, making the member object public does not violate the encapsulation and hiding of the member object's personal members. However, it does violate the encapsulation and also hiding of the include class's implementation, therefore member objects the class types should still be private, like all other data members.

In heat 26 the Fig. 10.11, notice the call to date member duty print. Many member attributes of class in C++ require no arguments. This is due to the fact that each member duty contains one implicit handle (in the type of a pointer) come the object on which the operates. We discuss the implicitly pointer, i m sorry is stood for by keyword this, in ar 10.5.

Class Employee supplies two 25-character arrays (Fig. 10.12, currently 1718) to represent the an initial name and last surname of the Employee. This arrays might waste an are for names shorter than 24 characters. (Remember, one character in each range is for the end null character, '', the the string.) Also, names longer than 24 personalities must it is in truncated come fit in this fixed-size character arrays. Section 10.7 presents another version of class Employee the dynamically create the exact amount of space required to organize the first and the last name.

See more: Stream Since You Ve Been Gone Pitch Perfect "), Since U Been Gone (From Pitch Perfect)

Note the the simplest method to represent an Employee's very first and last name making use of the specific amount of space required is to use two string objects (C++ traditional Library course string was introduced in thing 3). If we did this, the Employee constructor would appear as follows

Employee::Employee( const wire &first, const wire &last, const day &dateOfBirth, const day &dateOfHire ) : firstName( first), // initialize firstName lastName( last ), // initialize lastName birthDate( dateOfBirth ), // initialize birthDate hireDate( dateOfHire ) // initialize hireDate { // calculation Employee object to display when constructor is dubbed cout notification that data members firstName and also lastName (now string objects) room initialized with member initializers. The Employee classes gift in Chapters 1213 use string objects in this fashion. In this chapter, we use pointer-based strings to provide the leader with additional exposure to pointer manipulation.