Concept explainers
Exercises11.3 (Composition as an Alternative to Inheritance) Many
Program Plan:
We will implement the BasePlusCommissionEmp class using composition instead of inheritance and invoke different functions in the test program subsequently.
Explanation of Solution
Explanation:
Program Description:
The program demonstrates composition as an alternate way of implementing functionality in Object oriented programming. Some of the pros and cons are self evident in the program, yet we’ll discuss the merits and demerits of using composition over inheritance herewith. As obvious, composition increases duplicacy of code as seen in BasePlusCommissionEmp class where a large part of attributes and functions of the Employee class have to be repeated in the BasePlusCommissionEmp class. Also, the test code or the actual application using these objects becomes more complicated because the use of Data structures like Vectors to store all similar objects together and invoke common functionality in a single loop gets limited. If there are a large number of objects with similar functionality and a little variances, the redundant code soon becomes prone to defect and maintenance nightmares. On the same hand, composition provides more control at the compile time by limiting common access modifier errors and methos overriding errors during development time. has-a relationship is suited mostly where there is limited or no commonality in attributes and functionality of the objects being modelled. Its always better to create an is-a classheirarchywhenthe objects being modelled are having a lot of common attributes and method, resulting in a generic common subset (the base class) and other derived class specializing form it. Inheritance makes the code cleaner to write, read and maintain.
Program:
// BasePlusCommissionEmp class definition . #ifndef BP_COMMISSION_H #define BP_COMMISSION_H #include<string>// C++ standard string class usingnamespace std; classBasePlusCommissionEmp { public: BasePlusCommissionEmp(conststring&, conststring&, conststring&, double = 0.0,double = 0.0, double = 0.0 ); //For generic attributes of Employee voidsetFirstName( conststring& ); // set first name stringgetFirstName() const; // return first name voidsetLastName( conststring& ); // set last name stringgetLastName() const; // return last name voidsetSocialSecurityNumber( conststring& ); // set SSN stringgetSocialSecurityNumber() const; // return SSN // additional functions for attributes of CommisionEmployee voidsetGrossSales( double ); // set gross sales amount doublegetGrossSales() const; // return gross sales amount voidsetCommissionRate( double ); // set commission rate doublegetCommissionRate() const; // return commission rate //additional functions for baseSalary voidsetBaseSalary( double ); // set base salary doublegetBaseSalary() const; // return base salary // Generic functions of Employee doubleearnings() const; voidprint() const; private: //Generic attributes of Employee stringfirstName; // composition: member object stringlastName; // composition: member object stringsocialSecurityNumber; //composition: member object //attributes of CommisionEmployee doublegrossSales; // gross weekly sales doublecommissionRate; // commission percentage //attribute for BaseSalary doublebaseSalary; // base salary }; // end class BasePlusCommissionEmp #endif BasePlusCommisionEmp.cpp /* BasePlusCommissionEmp.cpp using composition Created on: 31-Jul-2018 :rajesh@acroknacks.com */ #include<string>// C++ standard string class #include"BasePlusCommissionEmp.h" #include<iostream> usingnamespace std; BasePlusCommissionEmp::BasePlusCommissionEmp(conststring&fname, conststring&lname, conststring&ssn1, doublebaseSalary, doublegrossSales , doublecomRate ) :firstName (fname), lastName ( lname),socialSecurityNumber (ssn1 ) { setBaseSalary(baseSalary ); // validate and store base salary setGrossSales(grossSales);//validate and store gross sales setCommissionRate(comRate);//validate and store commision rate }// end constructor /&Functions Below are specific to This class */ // set gross sales amount voidBasePlusCommissionEmp::setGrossSales( double sales ) { if ( sales **gt;= 0.0 ) grossSales = sales; else throwinvalid_argument( "Gross sales must be >= 0.0" ); } // end function setGrossSales // return gross sales amount doubleBasePlusCommissionEmp::getGrossSales() const { returngrossSales; } // end function getGrossSales // set commission rate voidBasePlusCommissionEmp::setCommissionRate( double rate ) { if ( rate > 0.0 && rate < 1.0 ) commissionRate = rate; else throwinvalid_argument( "Commission rate must be > 0.0 and < 1.0" ); } // end function setCommissionRate doubleBasePlusCommissionEmp::getCommissionRate() const { returncommissionRate; } // end function getCommissionRate voidBasePlusCommissionEmp::setBaseSalary( double salary ) { if ( salary >= 0.0 ) baseSalary = salary; else throwinvalid_argument( "Salary must be >= 0.0" ); } // end function setBaseSalary // return base salary doubleBasePlusCommissionEmp::getBaseSalary() const { returnbaseSalary; } // end function getBaseSalary //compute earnings doubleBasePlusCommissionEmp::earnings() const { return ( (getCommissionRate() * getGrossSales()) + getBaseSalary()) ; } // end function earnings // print CommissionEmployee object voidBasePlusCommissionEmp::print() const { cout<<"\nBasePlusCommission employee: "; cout<<lastName<<", "<<firstName<<endl; cout<<"SSN : "<<socialSecurityNumber<<endl; cout<<"\n gross sales: $ "<<getGrossSales() <<"\n Base Salary: $ "<<getBaseSalary() <<"\n commission rate: "<<getCommissionRate() ; } // end function print /&Generic Employee functions **/ // set first name voidBasePlusCommissionEmp::setFirstName( conststring**first ) { firstName = first; // should validate } // end function setFirstName // return first name stringBasePlusCommissionEmp::getFirstName() const { returnfirstName; } // end function getFirstName // set last name voidBasePlusCommissionEmp::setLastName( conststring&last ) { lastName = last; // should validate } // end function setLastName // return last name stringBasePlusCommissionEmp::getLastName() const { returnlastName; } // end function getLastName // set social security number voidBasePlusCommissionEmp::setSocialSecurityNumber( conststring&ssn ) { socialSecurityNumber = ssn; // should validate } // end function setSocialSecurityNumber // return social security number stringBasePlusCommissionEmp::getSocialSecurityNumber() const { returnsocialSecurityNumber; } // end function getSocialSecurityNumber Test Program // Testing class BasePlusCommissionEmp. #include<iostream> #include<iomanip> #include"BasePlusCommissionEmp.h"// BasePlusCommissionEmp class definition usingnamespace std; intmain() { // instantiate a BasePlusCommissionEmp object BasePlusCommissionEmpemployee("Sue", "Jones", "222-22-2222",1500,10000,0.16 ); // get commission employee data cout<<"Employee information obtained by get functions: \n" <<"\nFirst name is "<<employee.getFirstName() <<"\nLast name is "<<employee.getLastName() <<"\nSocial security number is " <<employee.getSocialSecurityNumber() <<"\nBase Salary is $"<<employee.getBaseSalary() <<"\nGross sales is $"<<employee.getGrossSales() <<"\nCommission rate is $"<<employee.getCommissionRate() <<endl; cout<<"Earnings based on current Data : $"<<employee.earnings(); //Modify Sales data employee.setGrossSales( 8000 ); // set gross sales employee.setCommissionRate( .1 ); // set commission rate cout<<"\nUpdated employee information output by print function: \n" <<endl; employee.print(); // display the new employee information // display the employee's earnings cout<<"\n\n Updated Employee's earnings: $"<<employee.earnings() <<endl; } // end main
Employee information obtained by get functions:
First name is Sue
Last name is Jones
Social security number is 222-22-2222
Base Salary is $1500
Gross sales is $10000
Commission rate is $0.16
Earnings based on current Data : $3100
Updated employee information output by print function:
BasePlusCommission employee: Jones, Sue
SSN : 222-22-2222
gross sales: $ 8000
Base Salary: $ 1500
commission rate: 0.1
Updated Employee's earnings: $2300
Want to see more full solutions like this?
Chapter 11 Solutions
C++ How to Program (10th Edition)
- 1. Complete the routing table for R2 as per the table shown below when implementing RIP routing Protocol? (14 marks) 195.2.4.0 130.10.0.0 195.2.4.1 m1 130.10.0.2 mo R2 R3 130.10.0.1 195.2.5.1 195.2.5.0 195.2.5.2 195.2.6.1 195.2.6.0 m2 130.11.0.0 130.11.0.2 205.5.5.0 205.5.5.1 R4 130.11.0.1 205.5.6.1 205.5.6.0arrow_forwardAnalyze the charts and introduce each charts by describing each. Identify the patterns in the given data. And determine how are the data points are related. Refer to the raw data (table):arrow_forward3A) Generate a hash table for the following values: 11, 9, 6, 28, 19, 46, 34, 14. Assume the table size is 9 and the primary hash function is h(k) = k % 9. i) Hash table using quadratic probing ii) Hash table with a secondary hash function of h2(k) = 7- (k%7) 3B) Demonstrate with a suitable example, any three possible ways to remove the keys and yet maintaining the properties of a B-Tree. 3C) Differentiate between Greedy and Dynamic Programming.arrow_forward
- What are the charts (with their title name) that could be use to illustrate the data? Please give picture examples.arrow_forwardA design for a synchronous divide-by-six Gray counter isrequired which meets the following specification.The system has 2 inputs, PAUSE and SKIP:• While PAUSE and SKIP are not asserted (logic 0), thecounter continually loops through the Gray coded binarysequence {0002, 0012, 0112, 0102, 1102, 1112}.• If PAUSE is asserted (logic 1) when the counter is onnumber 0102, it stays here until it becomes unasserted (atwhich point it continues counting as before).• While SKIP is asserted (logic 1), the counter misses outodd numbers, i.e. it loops through the sequence {0002,0112, 1102}.The system has 4 outputs, BIT3, BIT2, BIT1, and WAITING:• BIT3, BIT2, and BIT1 are unconditional outputsrepresenting the current number, where BIT3 is the mostsignificant-bit and BIT1 is the least-significant-bit.• An active-high conditional output WAITING should beasserted (logic 1) whenever the counter is paused at 0102.(a) Draw an ASM chart for a synchronous system to providethe functionality described above.(b)…arrow_forwardS A B D FL I C J E G H T K L Figure 1: Search tree 1. Uninformed search algorithms (6 points) Based on the search tree in Figure 1, provide the trace to find a path from the start node S to a goal node T for the following three uninformed search algorithms. When a node has multiple successors, use the left-to-right convention. a. Depth first search (2 points) b. Breadth first search (2 points) c. Iterative deepening search (2 points)arrow_forward
- We want to get an idea of how many tickets we have and what our issues are. Print the ticket ID number, ticket description, ticket priority, ticket status, and, if the information is available, employee first name assigned to it for our records. Include all tickets regardless of whether they have been assigned to an employee or not. Sort it alphabetically by ticket status, and then numerically by ticket ID, with the lower ticket IDs on top.arrow_forwardFigure 1 shows an ASM chart representing the operation of a controller. Stateassignments for each state are indicated in square brackets for [Q1, Q0].Using the ASM design technique:(a) Produce a State Transition Table from the ASM Chart in Figure 1.(b) Extract minimised Boolean expressions from your state transition tablefor Q1, Q0, DISPATCH and REJECT. Show all your working.(c) Implement your design using AND/OR/NOT logic gates and risingedgetriggered D-type Flip Flops. Your answer should include a circuitschematic.arrow_forwardA controller is required for a home security alarm, providing the followingfunctionality. The alarm does nothing while it is disarmed (‘switched off’). It canbe armed (‘switched on’) by entering a PIN on the keypad. Whenever thealarm is armed, it can be disarmed by entering the PIN on the keypad.If motion is detected while the alarm is armed, the siren should sound AND asingle SMS message sent to the police to notify them. Further motion shouldnot result in more messages being sent. If the siren is sounding, it can only bedisarmed by entering the PIN on the keypad. Once the alarm is disarmed, asingle SMS should be sent to the police to notify them.Two (active-high) input signals are provided to the controller:MOTION: Asserted while motion is detected inside the home.PIN: Asserted for a single clock cycle whenever the PIN has beencorrectly entered on the keypad.The controller must provide two (active-high) outputs:SIREN: The siren sounds while this output is asserted.POLICE: One SMS…arrow_forward
- 4G+ Vo) % 1.1. LTE1 : Q B NIS شوز طبي ۱:۱۷ کا A X حاز هذا على إعجاب Mohamed Bashar. MEDICAL SHOE شوز طبي ممول . اقوى عرض بالعراق بلاش سعر القطعة ١٥ الف سعر القطعتين ٢٥ الف سعر 3 قطع ٣٥ الف القياسات : 40-41-42-43-44- افحص وكدر ثم ادفع خدمة التوصيل 5 الف لكافة محافظات العراق ופרסם BNI SH ופרסם DON JU WORLD DON JU MORISO DON JU إرسال رسالة III Messenger التواصل مع شوز طبي تعليق باسم اواب حمیدarrow_forwardA manipulator is identified by the following table of parameters and variables:a. Obtain the transformation matrices between adjacent coordinate frames and calculate the global transformation matrix.arrow_forwardWhich tool takes the 2 provided input datasets and produces the following output dataset? Input 1: Record First Last Output: 1 Enzo Cordova Record 2 Maggie Freelund Input 2: Record Frist Last MI ? First 1 Enzo Last MI Cordova [Null] 2 Maggie Freelund [Null] 3 Jason Wayans T. 4 Ruby Landry [Null] 1 Jason Wayans T. 5 Devonn Unger [Null] 2 Ruby Landry [Null] 6 Bradley Freelund [Null] 3 Devonn Unger [Null] 4 Bradley Freelund [Null] OA. Append Fields O B. Union OC. Join OD. Find Replace Clear selectionarrow_forward
- Microsoft Visual C#Computer ScienceISBN:9781337102100Author:Joyce, Farrell.Publisher:Cengage Learning,C++ Programming: From Problem Analysis to Program...Computer ScienceISBN:9781337102087Author:D. S. MalikPublisher:Cengage LearningEBK JAVA PROGRAMMINGComputer ScienceISBN:9781337671385Author:FARRELLPublisher:CENGAGE LEARNING - CONSIGNMENT
- Programming Logic & Design ComprehensiveComputer ScienceISBN:9781337669405Author:FARRELLPublisher:CengageC++ for Engineers and ScientistsComputer ScienceISBN:9781133187844Author:Bronson, Gary J.Publisher:Course Technology PtrSystems ArchitectureComputer ScienceISBN:9781305080195Author:Stephen D. BurdPublisher:Cengage Learning