Skip to content

W6 ‐ References and Overloading

Riccardo Polvara edited this page Nov 4, 2024 · 3 revisions

CMP9133 - Workshop 6

University of Lincoln

School of Computer Science

CMP9133 – Programming Principles

Landing page

Join the sixth workshop at the dedicated LINK 💻

Task 1: Swap function with references

You are tasked with writing a C++ program that demonstrates the use of references to swap two values. Your program should show how references can be used to modify values in functions and how they affect the original variables.

Instructions:

  1. Implement a function named swapValues that takes two integer references as parameters and swaps their values.

swap

Task 2: Inventory

Here’s a more advanced task using references in a way that emphasizes their utility in modifying complex data structures. This example involves a simple inventory system with an Item class and an Inventory class to manage a collection of items. The task will highlight the use of references to access and modify objects directly within a container (e.g., a vector of Item objects).

Instructions:

  1. Define an Item class with attributes like name, quantity, and price.
  2. Define an Inventory class that holds a collection of Item objects. NB: use the 'vector' class
  3. Create functions to:
    • Add a new item to the inventory.
    • Update an existing item’s quantity and price by using references. Return trueor false depending if the item has been found and modified or not.
    • Display the inventory items. NB: inspect the inventory_test.cppfile to understand the expected format returned from this method.

By using references, the program should modify items directly in the inventory without copying them, which is crucial for large collections.

inventory

Task 3: Function Overloading

You are tasked with creating a C++ program that demonstrates function overloading. Your program should define multiple overloaded functions with the same name but different parameter types. Each overloaded function should perform a specific mathematical operation based on the input types.

Instructions:

  1. Define a function named calculate with the following overloaded versions:
    • int calculate(int a, int b): This version should return the sum of two integers.
    • double calculate(double a, double b): This version should return the product of two double-precision floating-point numbers.
    • int calculate(int a, int b, int c): This version should return the result of subtracting c from the product of a and b.

overloading