Warning: foreach() argument must be of type array|object, bool given in /var/www/html/web/app/themes/studypress-core-theme/template-parts/header/mobile-offcanvas.php on line 20

( Package Inheritance Hierarchy) Package-delivery services, such as \(\mathrm{FedEx}^{\mathbb{Q}}\), \(\mathrm{DHL}^{@}\) and \(\mathrm{UPS}^{@}\), offer a number of different shipping options, each with specific costs associated. Create an inheritance hierarchy to represent various types of packages. Use Package as the base class of the hierarchy, then include classes TwoDayPackage and overnight Package that derive from Package. Base class Package should include data members representing the name, address, city, state and ZIP code for both the sender and the recipient of the package, in addition to data members that store the weight (in ounces) and cost per ounce to ship the package. Package's constructor should initialize these data members. Ensure that the weight and cost per ounce contain positive values. Package should provide a public member function calculatecost that returns a double indicating the cost associated with shipping the package. Package's calculatecost function should determine the cost by multiplying the weight by the cost per ounce. Derived class Two DayPackage should inherit the functionality of base class Package, but also include a data member that represents a flat fee that the shipping company charges for two-day-delivery service. TwoDayPackage's constructor should receive a value to initialize this data member. Two ouppackage should redefine member function calculatecost so that it computes the shipping cost by adding the flat fee to the weight-based cost calculated by base class Package's calculatecost function. Class overnightPackage should inherit directly from class Package and contain an additional data member representing an additional fee per ounce charged for overnight-delivery service. overnightPackage should redefine member function calculatecost so that it adds the additional fee per ounce to the standard cost per ounce before calculating the shipping cost. Write a test program that creates objects of each type of Package and tests member function calculatecost.

Short Answer

Expert verified
Define classes for Package, TwoDayPackage, and OvernightPackage with specific cost calculations per delivery type.

Step by step solution

01

Define the Base Class Package

Create a class named `Package` that represents the base class for our hierarchy. Define data members for the name, address, city, state, and ZIP code of both sender and recipient. Also, include the weight of the package in ounces and the cost per ounce. Implement a constructor to initialize these data members and ensure that weight and cost per ounce are positive by adding checks in the constructor.
02

Implement CalculateCost Method

Within the `Package` class, implement the `calculateCost` method. This method should return the cost of shipping by multiplying the weight of the package by the cost per ounce.
03

Create the TwoDayPackage Derived Class

Define a class `TwoDayPackage` derived from the `Package` class. Add a new data member to store the flat fee for two-day delivery. In the constructor, initialize this flat fee along with the inherited attributes from `Package`. Override the `calculateCost` method to add this flat fee to the shipping cost calculated using the base class method.
04

Create the OvernightPackage Derived Class

Define another derived class `OvernightPackage` from the `Package` base class. Include an additional data member to store the extra fee per ounce for overnight delivery. Override the `calculateCost` method to compute the total cost by first adding the extra fee per ounce to the cost per ounce, and then calculating the shipping cost using the updated value.
05

Test the Package Hierarchy

Create a test function or program that instantiates objects of `Package`, `TwoDayPackage`, and `OvernightPackage`. For each object, call the `calculateCost` method to ensure that it computes and returns the correct shipping cost based on the specific delivery option. Validate the computations with sample data to confirm the classes work as intended.

Unlock Step-by-Step Solutions & Ace Your Exams!

  • Full Textbook Solutions

    Get detailed explanations and key concepts

  • Unlimited Al creation

    Al flashcards, explanations, exams and more...

  • Ads-free access

    To over 500 millions flashcards

  • Money-back guarantee

    We refund you if you fail your exam.

Over 30 million students worldwide already upgrade their learning with Vaia!

Key Concepts

These are the key concepts you need to understand to accurately answer the question.

Class Inheritance
In the context of object-oriented programming (OOP) in C++, class inheritance is a fundamental concept that allows one class to inherit the properties and functionalities of another class. This relationship between classes helps promote code reusability and logical hierarchy. In our exercise, the `Package` class serves as the base class. It contains common attributes and methods shared among package types. Derived classes like `TwoDayPackage` and `OvernightPackage` inherit from `Package`, gaining all of its attributes and methods. By doing so, derived classes can extend or modify these inherited characteristics to cater to specific needs.
This concept is beneficial in creating various shipping packages, as demonstrated in the hierarchy. The common attributes such as sender and recipient details, along with calculateCost() method, are declared in `Package`, and then tailored by `TwoDayPackage` and `OvernightPackage` for specific delivery types. The reusability of base class features in derived classes simplifies the process of handling different package types, without rewriting shared code from scratch, thus illustrating the power of inheritance.
Polymorphism
Polymorphism is another powerful feature of OOP, allowing objects of different classes to be treated as objects of a common superclass. It is particularly useful when different types of objects can be processed in a uniform manner. In C++, polymorphism is commonly achieved through virtual functions and method overriding.
In our exercise, polymorphism is illustrated when `calculateCost()` method is redefined in derived classes `TwoDayPackage` and `OvernightPackage`. These derived classes provide their own implementation of `calculateCost()`, adapting the base class's method to compute costs according to specific requirements. This allows the same method name to perform various actions depending on which class object is invoking it, empowering flexibility in code execution.
For instance, an array of `Package` pointers can store references to `Package`, `TwoDayPackage`, and `OvernightPackage` objects. When `calculateCost()` is called on these objects, each will execute their unique version of the method, showcasing polymorphic behavior. This seamless interchangeability underlines polymorphism's ability to handle diverse functionalities through a unified interface.
Encapsulation
Encapsulation in OOP is the concept of bundling the data (variables) and methods that operate on the data into a single unit or class. Moreover, it involves restricting access to some of the class's components. This is usually accomplished by defining access specifiers like private, protected, and public.
In our package hierarchy, encapsulation is achieved by keeping data members such as the sender and recipient information, weight, and cost per ounce within each class. These members are typically private or protected, limiting direct access from outside the class. Instead, public methods like constructors and setters/getters are provided to interact with these private data members safely and effectively.
This manner of data hiding protects the integrity of the object's data, preventing unauthorized or accidental changes. For example, ensuring weight and cost per ounce are positive upon initialization is accomplished through encapsulation. This structured approach promotes internal class integrity and simplifies object management within the program.
Data Members and Methods
In object-oriented programming, data members and methods (also called member functions) form the core components of a class. Data members are variables that represent the properties or attributes of a class. Methods are functions associated with the class, defining behaviors that objects of the class can perform.
In the provided exercise, the `Package` class contains data members like sender details, recipient details, weight, and cost per ounce, which are critical to defining the package's properties. Each of these represents a characteristic that any package must have to be properly described in the system.
Methods include the constructor which initializes these data members, and `calculateCost()` function which computes the shipping cost based on weight and cost per ounce. These methods define the operations that can be performed on an instance of the class.
By encapsulating data members and methods within a class, we create a blueprint from which objects can be instantiated, each with its unique set of data, yet consistent with class-defined operations. This principle ensures a modular, organized, and scalable codebase.

One App. One Place for Learning.

All the tools & learning materials you need for study success - in one app.

Get started for free

Most popular questions from this chapter

Draw an inheritance hierarchy for classes ouadrilateral, TRapezoid, Parallelogram, Rectangle and Square. Use quadrilateral as the base class of the hierarchy. Make the hierarchy as deep as possible.

Fill in the blanks in each of the following statements: a. _______ is a form of software reuse in which new classes absorb the data and behaviors of existing classes and embellish these classes with new capabilities. b. A base class's _______ members can be accessed only in the base- class definition or in derived-class definitions. c. \(\ln a(n)\) _______ relationship, an object of a derived class also can be treated as an object of its base class. d. \(\ln a(n)\) _______relationship, a class object has one or more objects of other classes as members. e. In single inheritance, a class exists in a(n) _______ relationship with its derived classes. f. A base class's _______ members are accessible within that base class and anywhere that the program has a handle to an object of that base class or to an object of one of its derived classes. g. \(A\) base class's protected access members have a level of protection between those of public and _______ access. h. \(C++\) provides for _______ which allows a derived class to inherit from many base classes, even if these base classes are unrelated. i. When an object of a derived class is instantiated, the base class's _______ is called implicitly or explicitly to do any necessary initialization of the base-class data members in the derived-class object. J. When deriving a class from a base class with public inheritance, public members of the base class become _______ members of the derived class, and protected members of the base class become _______ members of the derived class. k. When deriving a class from a base class with protected inheritance, public members of the base class become _______ members of the derived class, and protected members of the base class become _______ members of the derived class.

Discuss the ways in which inheritance promotes software reuse, saves time during program development and helps prevent errors.

(Account Inheritance Hierarchy) Create an inheritance hierarchy that a bank might use to represent customers' bank accounts. All customers at this bank can deposit (i.e., credit) money into their accounts and withdraw (i.e., debit) money from their accounts. More specific types of accounts also exist. Savings accounts, for instance, earn interest on the money they hold. Checking accounts, on the other hand, charge a fee per transaction (i.e.. credit or debit). Create an inheritance hierarchy containing base class account and derived classes savingsAccount and checkingAccount that inherit from class Account. Base class Account should include one data member of type double to represent the account balance. The class should provide a constructor that receives an initial balance and uses it to initialize the data member. The constructor should validate the initial balance to ensure that it is greater than or equal to \(\theta . \theta .\) If not, the balance should be set to \(\theta . \theta\) and the constructor should display an error message, indicating that the initial balance was invalid. The class should provide three member functions. Member function credit should add an amount to the current balance. Member function debit should withdraw money from the account and ensure that the debit amount does not exceed the account's balance. If it does, the balance should be left unchanged and the function should print the message "Debit amount exceeded account balance." Member function getBalance should return the current balance. Derived class savingsAccount should inherit the functionality of an Account, but also include a data member of type double indicating the interest rate (percentage) assigned to the Account. SavingsAccount's constructor should receive the initial balance, as well as an initial value for the SavingsAccount's interest rate. SavingsAccount should provide a public member function calculateInterest that returns a double indicating the amount of interest earned by an account. Member function calculateInterest should determine this amount by multiplying the interest rate by the account balance. [Note: SavingsAccount should inherit member functions credit and debit as is without redefining them.] Derived class checkingAccount should inherit from base class Account and include an additional data member of type double that represents the fee charged per transaction. CheckingAccount's constructor should receive the initial balance, as well as a parameter indicating a fee amount. Class CheckingAccount should redefine member functions credit and debit so that they subtract the fee from the account balance whenever either transaction is performed successfully. CheckingAccount's versions of these functions should invoke the base-class account version to perform the updates to an account balance. CheckingAccount's debit function should charge a fee only if money is actually withdrawn (i.e., the debit amount does not exceed the account balance). [Hint: Define Account's debit function so that it returns a bool indicating whether money was withdrawn. Then use the return value to determine whether a fee should be charged.] After defining the classes in this hierarchy, write a program that creates objects of each class and tests their member functions. Add interest to the SavingsAccount object by first invoking its calculateInterest function, then passing the returned interest amount to the object's credit function.

Some programmers prefer not to use protected access because they believe it breaks the encapsulation of the base class. Discuss the relative merits of using protected access vs. using private access in base classes.

See all solutions

Recommended explanations on Computer Science Textbooks

View all explanations

What do you think about this solution?

We value your feedback to improve our textbook solutions.

Study anywhere. Anytime. Across all devices.

Sign-up for free