C++ How to Program (10th Edition)
C++ How to Program (10th Edition)
10th Edition
ISBN: 9780134448237
Author: Paul J. Deitel, Harvey Deitel
Publisher: PEARSON
bartleby

Concept explainers

bartleby

Videos

Textbook Question
Book Icon
Chapter 11, Problem 11.3E

Exercises11.3 (Composition as an Alternative to Inheritance) Many programs written with inheritance can be written with composition instead, and vice versa. Rewrite class asePlusCommissionEmp1oyee of the CommissionEmployee-BasePlusCommissionEmployee hierarchy to use composition rather than inheritance. After you do this, assess the relative merits of the two approaches for designing classes CommissionEmployee and BasePlusCommissionEmployee, as well as for object-oriented pro- grams in general. Which approach is more natural? Why?

Expert Solution & Answer
Check Mark
Program Plan Intro

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
Sample Output

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?

Subscribe now to access step-by-step solutions to millions of textbook problems written by subject matter experts!
Students have asked these similar questions
Goal 1: Update the Fractions Class Here we will overload two functions that will used by the Recipe class later: multipliedBy, dividedBy Previously, these functions took a Fraction object as a parameter. Now ADD an implementation that takes an integer as a parameter. The functionality remains the same: Instead of multiplying/dividing the current object with another Fraction, it multiplies/divides with an integer (affecting numerator/denominator of the returned object). For example; a fraction 2/3 when multiplied by 4 becomes 8/3. Similarly, a fraction 2/3 when divided by 4 becomes 1/6. Goal 2: Update the Recipe Class Now add a private member variable of type int to denote the serving size and initialize it to 1. This means all recipes are initially constructed for a single serving. Update the overloaded extraction operator (<<) to include the serving size (sample output below for an example of formatting) . New Member functions to the Recipe Class: 1. Add four member functions…
Description: Create a class named ComparableDog that extends Animal and implements Comparable interface. Implement the compareTo method to compare the Dogs on the basis of age. Write a test class to find the bigger age of two instances of ComparableDog Objects, and complement the ComparableDog class with the missing part. 1)      The test program, the ComparableDog class, and its super class Animal are given as follows.     // Main method   public static void main(String[] args) {     // Create two comparable Dogs     ComparableDog dog1 = new ComparableDog(3);     ComparableDog dog2 = new ComparableDog(4);          System.out.println("Dog1:" + dog1);     System.out.println("Dog2:" + dog2);               if(dog1.compareTo(dog2) == 1)               System.out.println("Dog1 is older than Dog2");        else if(dog1.compareTo(dog2) == -1)               System.out.println("Dog1 is younger than Dog2");        else               System.out.println("Dog1 and Dog2 have the same age");      }…
Create a deck of cards class. Internally, the deck of cards should use another class, a card class. Your requirements are: The Deck class should have a deal method to deal a single card from the deck After a card is dealt, it is removed from the deck. There should be a shuffle method which makes sure the deck of cards has all 52 cards and then rearranges them randomly. The Card class should have a suit (Hearts, Diamonds, Clubs, Spades) and a value (A,2,3,4,5,6,7,8,9,10,J,Q,K)
Knowledge Booster
Background pattern image
Computer Science
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.
Similar questions
SEE MORE QUESTIONS
Recommended textbooks for you
Text book image
Database System Concepts
Computer Science
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:McGraw-Hill Education
Text book image
Starting Out with Python (4th Edition)
Computer Science
ISBN:9780134444321
Author:Tony Gaddis
Publisher:PEARSON
Text book image
Digital Fundamentals (11th Edition)
Computer Science
ISBN:9780132737968
Author:Thomas L. Floyd
Publisher:PEARSON
Text book image
C How to Program (8th Edition)
Computer Science
ISBN:9780133976892
Author:Paul J. Deitel, Harvey Deitel
Publisher:PEARSON
Text book image
Database Systems: Design, Implementation, & Manag...
Computer Science
ISBN:9781337627900
Author:Carlos Coronel, Steven Morris
Publisher:Cengage Learning
Text book image
Programmable Logic Controllers
Computer Science
ISBN:9780073373843
Author:Frank D. Petruzella
Publisher:McGraw-Hill Education
Introduction to Classes and Objects - Part 1 (Data Structures & Algorithms #3); Author: CS Dojo;https://www.youtube.com/watch?v=8yjkWGRlUmY;License: Standard YouTube License, CC-BY