Search⌘ K
AI Features

Solution: Invoice Generator

Explore function overloading and default arguments in C++ to handle different parameter types and optional values. Understand how to write functions that modify variables by reference and manage default tax rates in calculations. This lesson builds skills for designing flexible program structures using core C++ functionalities.

We'll cover the following...
C++ 23
#include <iostream>
// Overload 1: Calculates price for discrete items (quantity is int)
double calculatePrice(double pricePerUnit, int quantity) {
return pricePerUnit * quantity;
}
// Overload 2: Calculates price for weighted items (weight is double)
double calculatePrice(double pricePerKg, double weight) {
return pricePerKg * weight;
}
// Updates total by reference. Uses a default taxRate of 5% if not provided.
void addToTotal(double& total, double itemCost, double taxRate = 0.05) {
double taxAmount = itemCost * taxRate;
double finalAmount = itemCost + taxAmount;
total += finalAmount;
std::cout << "Added item: $" << itemCost
<< " + Tax: $" << taxAmount
<< " = $" << finalAmount << "\n";
}
int main() {
double invoiceTotal = 0.0;
// 1. Buy 3 Books at $10.00 each
// Compiler selects Overload 1 because 3 is an integer
double booksCost = calculatePrice(10.00, 3);
// Updates invoiceTotal using the default 5% tax
addToTotal(invoiceTotal, booksCost);
// 2. Buy 2.5 kg of Fruit at $4.00 per kg
// Compiler selects Overload 2 because 2.5 is a double
double fruitCost = calculatePrice(4.00, 2.5);
// Updates invoiceTotal with 0% tax (overriding the default)
addToTotal(invoiceTotal, fruitCost, 0.0);
std::cout << "Final Invoice Total: $" << invoiceTotal << "\n";
return 0;
}
...