Home

Functions and their Parameters

 

Parameters and Arguments

 

Default Arguments

Whenever a function takes an argument, that argument is required. If the calling function does not provide the (required) argument, the compiler would throw an error.

Imagine you write a function that will be used to calculate the final price of an item after discount. The function would need the discount rate in order to perform the calculation. Such a function could look like this:

double __fastcall CalculateNetPrice(double DiscountRate)
{
    double OrigPrice;

    cout << "Please enter the original price: ";
    cin >> OrigPrice;

    return OrigPrice - (OrigPrice * DiscountRate / 100);
}

Since this function expects an argument, if you do not supply it, the following program would not compile:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
double  __fastcall CalculateNetPrice(double DiscountRate)
{
    double OrigPrice;

    cout << "Please enter the original price: ";
    cin >> OrigPrice;

    return OrigPrice - (OrigPrice * DiscountRate / 100);
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    double FinalPrice;
    double Discount = 15; // That is 25% = 25

    FinalPrice = CalculateNetPrice(Discount);

    cout << "\nAfter applying the discount";
    cout << "\nFinal Price = " << FinalPrice << "\n";

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

Here is an example of running the program:

Please enter the original price: 255.95

After applying the discount
Final Price = 217.558

Press any key to continue...

Most of the time, a function such as this CalculateNetPrice() would use the same discount rate over and over again. Therefore, instead of supplying an argument all the time, C++ allows you to define an argument whose value would be used whenever the function is not provided with a value for the argument.

To give a default value to an argument, when declaring the function, type the name of the argument followed by the assignment operator, =, followed by the default value. The CalculateNetPrice() function, with a default value, could be defined as:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
double  __fastcall CalculateNetPrice(double DiscountRate = 25)
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    double FinalPrice;

    FinalPrice = CalculateNetPrice();

    cout << "\nAfter applying the discount";
    cout << "\nFinal Price = " << FinalPrice << "\n";

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------
double  __fastcall CalculateNetPrice(double DiscountRate)
{
    double OrigPrice;

    cout << "Please enter the original price: ";
    cin >> OrigPrice;

    return OrigPrice - (OrigPrice * DiscountRate / 100);
}

Here is an example of running the program:

Please enter the original price: 120.15

After applying the discount
Final Price = 90.1125

Press any key to continue...

If a function takes more than one argument, you can provide a default argument for each and select which ones would have default values. If you want all arguments to have default values, when defining the function, type each name followed by = and followed by the desired value. Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
double  __fastcall CalculateNetPrice(double Tax = 5.75, double Discount = 25,
                         double OrigPrice = 245.55)
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    double FinalPrice;

    FinalPrice = CalculateNetPrice();

    cout << "\nAfter applying the discount";
    cout << "\nFinal Price = " << FinalPrice << "\n";

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------
double  __fastcall CalculateNetPrice(double Tax, double Discount, double OrigPrice)
{
    double DiscountValue = OrigPrice * Discount / 100;
    double TaxValue = Tax / 100;
    double NetPrice = OrigPrice - DiscountValue + TaxValue;

    cout << "Original Price: $" << OrigPrice << endl;
    cout << "Discount Rate: " << Discount << "%" << endl;
    cout << "Tax Amount: $" << Tax << endl;

    return NetPrice;
}
//---------------------------------------------------------------------------

Here is the result produced:

Original Price: $245.55
Discount Rate: 25%
Tax Amount: $5.75

After applying the discount
Final Price = 184.22

Press any key to continue...

If a function takes more than one argument and you would like to provide default values for those parameters, the order of appearance of the arguments is very important.

  1. If a function takes two arguments, you can declare it with default values. We already know how to do that. If you want to provide a default value for only one of the arguments, the argument that would have a default value must be the second in the list. Here is an example:
    double CalculatePrice(double Tax, double Discount = 25);

    When calling such a function, if you supply only one argument, the compiler would assign its value to the first parameter in the list and ignore assigning a value to the second:

    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    using namespace std;
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    double __fastcall CalculateNetPrice(double Tax, double Discount = 25);
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {
        double FinalPrice;
        double TaxRate = 5.50; // = 5.50%
    
        FinalPrice = CalculateNetPrice(TaxRate);
    
        cout << "\nAfter applying a 25% discount and a 5.50% tax rate";
        cout << "\nFinal Price = " << FinalPrice << "\n";
    
        cout << "\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
    double  __fastcall CalculateNetPrice(double Tax, double Discount)
    {
        double OrigPrice, DiscountValue, TaxValue, NetPrice;
    
        cout << "Enter the original price of the item: ";
        cin >> OrigPrice;
    
        DiscountValue = OrigPrice * Discount / 100;
        TaxValue = Tax / 100;
        NetPrice = OrigPrice - DiscountValue + TaxValue;
    
        return NetPrice;
    }
    //---------------------------------------------------------------------------

    Here is an example of running the program:

    Enter the original price of the item: 250.50
    
    After applying a 25% discount and a 5.50% tax rate
    Final Price = 187.93
    
    Press any key to continue...

    If you define the function and assign a default value to the first argument, if you provide only one argument when calling the function, you would receive an error.

  2. If the function receives more than two arguments and you would like only some of those arguments to have default values, the arguments that would have default values must be at the end of the list. Regardless of how many arguments would or would not have default values, start the list of arguments without those that would not use default values. Here is an example: 

    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    using namespace std;
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    double __fastcall RequestOriginalPrice();
    double __fastcall CalculateNetPrice(double Price, double Tax = 5.75,
                                        double Discount = 25);
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {
        double OriginalPrice, FinalPrice;
        double TaxRate; // %
    
        OriginalPrice = RequestOriginalPrice();
        FinalPrice = CalculateNetPrice(OriginalPrice);
    
        cout << "\nAfter applying a 25% discount and a 5.75% tax rate";
        cout << "\nFinal Price = " << FinalPrice << "\n";
    
        cout << "\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
    double __fastcall RequestOriginalPrice()
    {
        double OrigPrice;
    
        cout << "Enter the original price of the item: ";
        cin >> OrigPrice;
        return OrigPrice;
    }
    //---------------------------------------------------------------------------
    double  __fastcall CalculateNetPrice(double Price, double Tax,
                                         double Discount)
    {
        double DiscountValue, TaxValue, NetPrice;
    
        DiscountValue = Price * Discount / 100;
        TaxValue = Tax / 100;
        NetPrice = Price - DiscountValue + TaxValue;
    
        return NetPrice;
    }
    //---------------------------------------------------------------------------

    Here is an example of running the program:

    Enter the original price of the item: 250.50
    
    After applying a 25% discount and a 5.75% tax rate
    Final Price = 187.933
    
    Press any key to continue...

    As you can see, the argument(s) that has(have) default value(s) must be last in the list of arguments.

Practical Learning: Using Default Arguments

 
  1. Start Borland C++ Builder and create a C++ project using the Console Wizard
  2. Save the project in a new folder named GCS5
  3. Save the unit as Main.cpp and save the project as GCS5
  4. Create a new unit and save it as Orders
  5. To provide default arguments to functions, in the Orders.h file, declare the following functions:
     
    //---------------------------------------------------------------------------
    #ifndef OrdersH
    #define OrdersH
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <string>
    using namespace std;
    //---------------------------------------------------------------------------
    namespace GeorgetownCleaners
    {
    // Price of items
    const double PriceShirt = 0.99;
    const double PricePants = 1.95;
    const double PriceOtherItems = 3.25;
    
    string  __fastcall GetCustomerName();
    int     __fastcall RequestNumberOfShirts();
    int     __fastcall RequestNumberOfPants();
    int     __fastcall RequestNumberOfOtherItems();
    double  __fastcall GetTaxRate();
    double  __fastcall CalculatePriceShirts(int Shirts,
                                            double Price = PriceShirt);
    double  __fastcall CalculatePricePants(int Pants, double = PricePants);
    double  __fastcall CalculatePriceOthers(int Others,
                                            double = PriceOtherItems);
    double  __fastcall CalculateTotalOrder(double Shirts,
                                           double Pants, double Others);
    double  __fastcall CalculateTaxAmount(double Total, double = 5.75);
    double  __fastcall CalculateTotalPrice(double Total, double Tax);
    void    __fastcall DisplayReceipt(string Name, int Shirts, int Pants,
                                      int Others, double Tax, double Total);
    }
    //---------------------------------------------------------------------------
    #endif
  6. In the Orders.cpp file, implement the functions as follows:
     
    //---------------------------------------------------------------------------
    
    #pragma hdrstop
    
    #include "Orders.h"
    //---------------------------------------------------------------------------
    #pragma package(smart_init)
    namespace GeorgetownCleaners
    {
    string __fastcall GetCustomerName()
    {
        string FirstName, LastName;
    
        cout << "Enter customer identification\n";
        cout << "First Name: "; cin >> FirstName;
        cout << "Last Name:  "; cin >> LastName;
    
        return FirstName + " " + LastName;
    }
    //---------------------------------------------------------------------------
    int __fastcall RequestNumberOfShirts()
    {
        int Shirts;
    
        cout << "Number of shirts: ";
        cin >> Shirts;
        return Shirts;
    }
    //---------------------------------------------------------------------------
    int __fastcall RequestNumberOfPants()
    {
        int Pants;
    
        cout << "Numbers of Pants: ";
        cin >> Pants;
        return Pants;
    }
    //---------------------------------------------------------------------------
    int __fastcall RequestNumberOfOtherItems()
    {
        int Items;
    
        cout << "# of other items: ";
        cin >> Items;
        return Items;
    }
    //---------------------------------------------------------------------------
    double __fastcall GetTaxRate()
    {
        double Rate;
    
        cout << "Enter the tax rate (such as 5.75): ";
        cin >> Rate;
        return Rate;
    }
    //---------------------------------------------------------------------------
    double __fastcall CalculatePriceShirts(int Shirts, double Price)
    {
        return Shirts * Price;
    } 
    //---------------------------------------------------------------------------
    double __fastcall CalculatePricePants(int Pants, double Price)
    {  
        return Pants * Price;
    }
    //---------------------------------------------------------------------------
    double __fastcall CalculatePriceOthers(int Others, double Price)
    {         
        return Others * Price;
    }
    //---------------------------------------------------------------------------
    double __fastcall CalculateTotalOrder(double Shirts, double Pants,
                               double Others)
    {
        return Shirts + Pants + Others;
    }
    //---------------------------------------------------------------------------
    double __fastcall CalculateTaxAmount(double Total, double Rate)
    {
        return Total * Rate / 100;
    }
    //---------------------------------------------------------------------------
    double __fastcall CalculateTotalPrice(double Total, double Tax)
    {
        return Total + Tax;
    }
    //---------------------------------------------------------------------------
    void __fastcall DisplayReceipt(string CustName, int Shirts, int Pants,
                                   int Others, double Tax, double Total)
    {
        // Display the result
        cout << "\n======================================";
        cout << "\n - Georgetown Cleaning Services -";
        cout << "\n--------------------------------------";
        cout << "\nCustomer Name: " << CustName;
        cout << "\n--------------------------------------";
        cout << "\nItem Type\t#\tUnit\tTotal";
        cout << "\nShirts\t\t" << Shirts << "\t" << PriceShirt
             << "\t" << CalculatePriceShirts(Shirts, PriceShirt);
        cout << "\nPants\t\t"  << Pants << "\t" << PricePants
             << "\t" << CalculatePricePants(Pants, PricePants);
        cout << "\nOthers\t\t" << Others << "\t" << PriceOtherItems
             << "\t" << CalculatePriceOthers(Others, PriceOtherItems);
        cout << "\n--------------------------------------";
        cout << "\n\tTax Amount:  $" << Tax;
        cout << "\n\tTotal Order: $" << Total;
        cout << "\n======================================";
    }
    }
    //---------------------------------------------------------------------------
  7. To call functions that have default arguments, change the calls in the main() function as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    #pragma hdrstop
    #include "Orders.h"
    //---------------------------------------------------------------------------
    using namespace std;
    using namespace GeorgetownCleaners;
    #pragma argsused
    void __fastcall Welcome()
    {
        cout << " - Welcome to Georgetown Cleaning Services -\n";
    }
    //---------------------------------------------------------------------------
    double __fastcall RequestAmountTended()
    {
        double Amount;
        // Get the amount tended
        cout << "\n\nAmount tended: $";
        cin >> Amount;
    
        return Amount;
    }
    //---------------------------------------------------------------------------
    double __fastcall CalculateAmountOwed(double Tended, double Total)
    {
        return Tended - Total;
    }
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {
        int NumberOfShirts,
            NumberOfPants,
            NumberOfOtherItems;
        string CustomerName;
    
        // Declare total prices by category
        double TotalPriceShirts, TotalPricePants, TotalPriceOthers;
        double TotalOrder, TaxRate, TaxAmount, NetPrice;
        double AmountTended, Difference;
    
        // Welcome the customer
        Welcome();
        CustomerName = GetCustomerName();
    
        NumberOfShirts = RequestNumberOfShirts();
        NumberOfPants  = RequestNumberOfPants();
        NumberOfOtherItems = RequestNumberOfOtherItems();
        TaxRate = GetTaxRate();
    
        // Calculate the total price of each item category
        TotalPriceShirts = CalculatePriceShirts(NumberOfShirts, PriceShirt);
        TotalPricePants  = CalculatePricePants( NumberOfPants, PricePants );
        TotalPriceOthers = CalculatePriceOthers(NumberOfOtherItems,
                                                PriceOtherItems);
        TotalOrder       = CalculateTotalOrder(TotalPriceShirts,
                                               TotalPricePants,
                                               TotalPriceOthers);
    
        TaxAmount        = CalculateTaxAmount(TotalOrder, TaxRate);
        NetPrice         = CalculateTotalPrice(TotalOrder, TaxAmount);
    
        // Display the result
        DisplayReceipt(CustomerName, NumberOfShirts, NumberOfPants,
                       NumberOfOtherItems, TaxAmount, NetPrice);
    
        AmountTended = RequestAmountTended();
        // Calculate the difference for the customer
        Difference = CalculateAmountOwed(AmountTended, TotalOrder);
    
        // Final message
        cout << "\nThe difference is $" << Difference << "\nThanks";
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  8. Test the application. Here is an example:
     
    - Welcome to Georgetown Cleaning Services -
    Enter customer identification
    First Name: Willie
    Last Name:  Banks
    Number of shirts: 2
    Numbers of Pants: 5
    # of other items: 2
    Enter the tax rate (such as 5.75): 5.75
    
    ======================================
     - Georgetown Cleaning Services -
    --------------------------------------
    Customer Name: Willie Banks
    --------------------------------------
    Item Type       #       Unit    Total
    Shirts          2       0.99    1.98
    Pants           5       1.95    9.75
    Others          2       3.25    6.5
    --------------------------------------
            Tax Amount:  $1.04822
            Total Order: $19.2782
    ======================================
    
    Amount tended: $20
    
    The difference is $1.77
    Thanks
    
    Press any key to continue...
  9. Return to Bcb

Constant Arguments

 

When a function receives an argument, it behaves one of two ways with regards to the value of the argument; it might modify the value itself or only use the argument to modify another argument or another of its own variables. If you know that a function should not alter the value of an argument, you should let the compiler know. This is a safeguard that serves at least two purposes. First, the compiler will make sure that the argument supplied stays intact; if the function tries to modify the argument, the compiler would throw an error, letting you know that an undesired operation took place. Second, this speeds up execution.

To let the compiler know that the value of an argument must stay constant, use the const keyword before the data type of the argument. The double CalculateDiscount() function above receives two arguments, the marked price of an item and the discount rate applied on it. This function uses the two values to calculate the amount of discount that a customer would receive. Since the marked price is set on the item in the store, the function does not modify its value; it only needs it in order to calculate the new price so the customer can see the difference. The function then returns the discount amount. To reinforce this fact and to prevent the CalculateDiscount() function from changing the value of the marked price, you can declare the argument as constant:

double CalculateDiscount(const double MarkedPrice, double DiscountApplied);

If you declare a function before implementing it, make sure you specify the argument as constant in both cases. Once again, only the signature of the function is important. If you are simply declaring the function, the name of the argument is not important, neither is its presence. Therefore, the above CalculateDiscount() function can as well be declared as follows:

double CalculateDiscount(const double, double);

You can pass just one argument as constant. You can almost pass a few or all arguments as constants. It depends on the role of the arguments in the implementation of the function.

Practical Learning: Using Constant Arguments

 
  1. To use an example of passing arguments as constants, change the CalculateAmountOwed() in the Main.cpp file as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    #pragma hdrstop
    #include "Orders.h"
    //---------------------------------------------------------------------------
    using namespace std;
    using namespace GeorgetownCleaners;
    #pragma argsused
    void __fastcall Welcome()
    {
        cout << " - Welcome to Georgetown Cleaning Services -\n";
    }
    //---------------------------------------------------------------------------
    double __fastcall RequestAmountTended()
    {
        double Amount;
        // Get the amount tended
        cout << "\n\nAmount tended: $";
        cin >> Amount;
    
        return Amount;
    }
    //---------------------------------------------------------------------------
    double __fastcall CalculateAmountOwed(const double Tended,
                                          const double Total)
    {
        return Tended - Total;
    }
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {
        . . . No Change
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  2. Test the program and return to Bcb.
     

Passing Arguments by Reference

 

When you declare a variable in a program, the compiler reserves an amount of space for that variable. If you need to use that variable somewhere in your program, you call it and make use of its value. There are two major issues related to a variable: its value and its location in the memory:

Passing Arguments By Reference

The location of a variable in memory is referred to as its address.

If you supply the argument using its name, as we have done so far, the compiler only makes a copy of the argumentís value and gives it to the calling function. Although the calling function receives the argumentís value and can use in any way, it cannot (permanently) alter it. C++ allows a calling function to modify the value of a passed argument if you find it necessary. If you want the calling function to modify the value of a supplied argument and return the modified value, you should pass the argument using its reference.

To pass an argument as a reference, when declaring the function, precede the argument name with an ampersand ď&Ē. You can pass one or more arguments as reference in the program or pass all arguments as reference. The decision as to which argument(s) should be passed by value or by reference is based on whether or not you want the called function to modify the argument and permanently change its value.

Here are examples of passing some arguments by reference:

void Area(double &Side); // The argument is passed by reference
bool Decision(char &Answer, int Age); // One argument is passed by reference
// All arguments are passed by reference
float Purchase(float &DiscountPrice, float &NewDiscount, char &Commission);

Once again, the signature of the function is important when declaring the function. The compiler would not care much about the name of an argument. Therefore, the above functions can be declared as follows:

void Area(double &); 
bool Decision(char &, int );
float Purchase(float &, float &, char &);

You add the ampersand when declaring a function and/or when defining it. When calling the function, supply only the name of the referenced argument(s). The above would be called with:

Area(Side);
Decision(Answer, Age);
Purchase(DiscountPrice, NewDiscount, Commission);

You will usually need to know what happens to the value passed to a calling function because the rest of the program may depend on it.

Imagine that you write a function that calculates employees weekly salary provided the total weekly hours and hourly rate. To illustrate our point, we will see how or whether one function can modify a salary of an employee who claims to have worked more than the program displays. The starting regular program would be as follows:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    float Hours, Rate, Wage;
    void Earnings(float h, float r);

    cout << "Enter the total Weekly hours: ";
    cin >> Hours;
    cout << "Enter the employee's hourly rate: ";
    cin >> Rate;

    cout << "\nIn the main() function,";
    cout << "\n\tWeekly Hours = " << Hours;
    cout << "\n\tSalary = " << Rate;
    cout << "\n\tWeekly Salary: " << Hours * Rate;

    cout << "\nCalling the Earnings() function";
    Earnings(Hours, Rate);
    cout << "\n\nAfter calling the Earnings() function, "
         << "in the main() function,";

    cout << "\n\tWeekly Hours = " << Hours;
    cout << "\n\tSalary = " << Rate;
    cout << "\n\tWeekly Salary: " << Hours * Rate;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------
void Earnings(float ThisWeek, float Salary)
{
    cout << "\n\nIn the Earnings() function,";
    cout << "\n\tWeekly Hours = " << ThisWeek;
    cout << "\n\tSalary = " << Salary;
    cout << "\n\tWeekly Salary= " << ThisWeek * Salary;
}
//---------------------------------------------------------------------------

If you test the program by typing 32 for the weekly hours and 6.45 for the salary, you would notice the weekly values are the same.

Imagine that the employee claims to have worked 42 hours instead of the passed weekly hours. You could create the following function to find out.

//---------------------------------------------------------------------------
void Earnings(float ThisWeek, float Salary)
{
    ThisWeek = 42;
    cout << "\n\nIn the Earnings() function,";
    cout << "\n\tWeekly Hours = " << ThisWeek;
    cout << "\n\tSalary = " << Salary;
    cout << "\n\tWeekly Salary= " << ThisWeek * Salary;
}
//---------------------------------------------------------------------------

If you test the program with a weekly hours value of 35.50 and a salary of 8.50, you would notice that the weekly salary is different inside of the Earnings() function but is kept the same in main(), before and after the Earnings() function:

Enter the total Weekly hours: 35.50
Enter the employee's hourly rate: 8.50

In the main() function,
        Weekly Hours = 35.5
        Salary = 8.5
        Weekly Salary: 301.75
Calling the Earnings() function

In the Earnings() function,
        Weekly Hours = 42
        Salary = 8.5
        Weekly Salary= 357

After calling the Earnings() function, in the main() function,
        Weekly Hours = 35.5
        Salary = 8.5
        Weekly Salary: 301.75

Press any key to continue...

As an example of passing an argument by reference, you could modify the declaration of the Earnings() function inside of the main() function as follows:

void Earnings(float &h, float r);

If you want a calling function to modify the value of an argument, you should supply its reference and not its value. You could change the function as follows:

//---------------------------------------------------------------------------
void Earnings(float &ThisWeek, float Salary)
{
    ThisWeek = 42;
    cout << "\n\nIn the Earnings() function,";
    cout << "\n\tWeekly Hours = " << ThisWeek;
    cout << "\n\tSalary = " << Salary;
    cout << "\n\tWeekly Salary= " << ThisWeek * Salary;
}
//---------------------------------------------------------------------------
 

Practical Learning: Passing Arguments by Reference

 
  1. To apply the passing of arguments by reference, change the Orders.h file as follows (there are many other changes in the file, such as constant arguments):
     
    //---------------------------------------------------------------------------
    #ifndef OrdersH
    #define OrdersH
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <string>
    using namespace std;
    //---------------------------------------------------------------------------
    namespace GeorgetownCleaners
    {
    // Price of items
    const double PriceShirt = 0.99;
    const double PricePants = 1.95;
    const double PriceOtherItems = 3.25;
    
    string  __fastcall GetCustomerName();
    void    __fastcall RequestNumberOfShirts(int &);
    void    __fastcall RequestNumberOfPants(int &);
    void    __fastcall RequestNumberOfOtherItems(int &);
    void    __fastcall GetTaxRate(double &);
    double  __fastcall CalculatePriceShirts(const int Shirts,
                                            double Price = PriceShirt);
    double  __fastcall CalculatePricePants(const int Pants, double = PricePants);
    double  __fastcall CalculatePriceOthers(const int Others,
                                            double = PriceOtherItems );
    double  __fastcall CalculateTotalOrder(const double Shirts,
                                           const double Pants,
                                           const double Others);
    double  __fastcall CalculateTaxAmount(const double Total, double = 5.75);
    double  __fastcall CalculateTotalPrice(const double Total, const double Tax);
    void    __fastcall DisplayReceipt(const string Name, const int Shirts,
                                      const int Pants, const int Others,
                                      const double Tax, const double Total);
    }
    //---------------------------------------------------------------------------
    #endif
  2. In the Orders.cpp file, change the functions as follows (check the other changes in the file):
     
    //---------------------------------------------------------------------------
    
    #pragma hdrstop
    
    #include "Orders.h"
    //---------------------------------------------------------------------------
    #pragma package(smart_init)
    namespace GeorgetownCleaners
    {
    string __fastcall GetCustomerName()
    {
        string FirstName, LastName;
    
        cout << "Enter customer identification\n";
        cout << "First Name: "; cin >> FirstName;
        cout << "Last Name:  "; cin >> LastName;
    
        return FirstName + " " + LastName;
    }
    //---------------------------------------------------------------------------
    void __fastcall RequestNumberOfShirts(int &Shirts)
    {
        cout << "Number of shirts: ";
        cin >> Shirts;
    }
    //---------------------------------------------------------------------------
    void __fastcall RequestNumberOfPants(int &Pants)
    {
        cout << "Numbers of Pants: ";
        cin >> Pants;
    }
    //---------------------------------------------------------------------------
    void __fastcall RequestNumberOfOtherItems(int &Items)
    {
        cout << "# of other items: ";
        cin >> Items;
    }
    //---------------------------------------------------------------------------
    void __fastcall GetTaxRate(double &Rate)
    {
        cout << "Enter the tax rate (such as 5.75): ";
        cin >> Rate;
    }
    //---------------------------------------------------------------------------
    double __fastcall CalculatePriceShirts(const int Shirts, double Price)
    {
        return Shirts * Price;
    } 
    //---------------------------------------------------------------------------
    double __fastcall CalculatePricePants(const int Pants, double Price)
    {  
        return Pants * Price;
    }
    //---------------------------------------------------------------------------
    double __fastcall CalculatePriceOthers(const int Others, double Price)
    {         
        return Others * Price;
    }
    //---------------------------------------------------------------------------
    double __fastcall CalculateTotalOrder(const double Shirts, const double Pants,
                                          const double Others)
    {
        return Shirts + Pants + Others;
    }
    //---------------------------------------------------------------------------
    double __fastcall CalculateTaxAmount(const double Total, double Rate)
    {
        return Total * Rate / 100;
    }
    //---------------------------------------------------------------------------
    double __fastcall CalculateTotalPrice(const double Total, const double Tax)
    {
        return Total + Tax;
    }
    //---------------------------------------------------------------------------
    void __fastcall DisplayReceipt(const string CustName, const int Shirts,
                                   const int Pants, const int Others,
                                   const double Tax, const double Total)
    {
        // Display the result
        cout << "\n======================================";
        cout << "\n - Georgetown Cleaning Services -";
        cout << "\n--------------------------------------";
        cout << "\nCustomer Name: " << CustName;
        cout << "\n--------------------------------------";
        cout << "\nItem Type\t#\tUnit\tTotal";
        cout << "\nShirts\t\t" << Shirts << "\t" << PriceShirt
             << "\t" << CalculatePriceShirts(Shirts, PriceShirt);
        cout << "\nPants\t\t"  << Pants << "\t" << PricePants
             << "\t" << CalculatePricePants(Pants, PricePants);
        cout << "\nOthers\t\t" << Others << "\t" << PriceOtherItems
             << "\t" << CalculatePriceOthers(Others, PriceOtherItems);
        cout << "\n--------------------------------------";
        cout << "\n\tTax Amount:  $" << Tax;
        cout << "\n\tTotal Order: $" << Total;
        cout << "\n======================================";
    }
    }
    //---------------------------------------------------------------------------
  3. In the Main.cpp file, call the functions as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    #pragma hdrstop
    #include "Orders.h"
    //---------------------------------------------------------------------------
    using namespace std;
    using namespace GeorgetownCleaners;
    #pragma argsused
    void __fastcall Welcome()
    {
        cout << " - Welcome to Georgetown Cleaning Services -\n";
    }
    //---------------------------------------------------------------------------
    void __fastcall RequestAmountTended(double &Amount)
    {
        // Get the amount tended
        cout << "\n\nAmount tended: $";
        cin >> Amount;
    }
    //---------------------------------------------------------------------------
    double __fastcall CalculateAmountOwed(const double Tended,
                                          const double Total)
    {
        return Tended - Total;
    }
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {
        int NumberOfShirts,
            NumberOfPants,
            NumberOfOtherItems;
        string CustomerName;
    
        // Declare total prices by category
        double TotalPriceShirts, TotalPricePants, TotalPriceOthers;
        double TotalOrder, TaxRate, TaxAmount, NetPrice;
        double AmountTended, Difference;
    
        // Welcome the customer
        Welcome();
        CustomerName = GetCustomerName();
    
        RequestNumberOfShirts(NumberOfShirts);
        RequestNumberOfPants(NumberOfPants);
        RequestNumberOfOtherItems(NumberOfOtherItems);
        GetTaxRate(TaxRate);
    
        // Calculate the total price of each item category
        TotalPriceShirts = CalculatePriceShirts(NumberOfShirts, PriceShirt);
        TotalPricePants  = CalculatePricePants( NumberOfPants, PricePants );
        TotalPriceOthers = CalculatePriceOthers(NumberOfOtherItems,
                                                PriceOtherItems);
        TotalOrder       = CalculateTotalOrder(TotalPriceShirts,
                                               TotalPricePants,
                                               TotalPriceOthers);
    
        TaxAmount        = CalculateTaxAmount(TotalOrder, TaxRate);
        NetPrice         = CalculateTotalPrice(TotalOrder, TaxAmount);
    
        // Display the result
        DisplayReceipt(CustomerName, NumberOfShirts, NumberOfPants,
                       NumberOfOtherItems, TaxAmount, NetPrice);
    
        RequestAmountTended(AmountTended);
        // Calculate the difference for the customer
        Difference = CalculateAmountOwed(AmountTended, TotalOrder);
    
        // Final message
        cout << "\nThe difference is $" << Difference << "\nThanks";
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  4. Test the program. Here is an example:
     
    - Welcome to Georgetown Cleaning Services -
    Enter customer identification
    First Name: Lucille
    Last Name:  Lotts
    Number of shirts: 1
    Numbers of Pants: 8
    # of other items: 6
    Enter the tax rate (such as 5.75): 5.75
    
    ======================================
     - Georgetown Cleaning Services -
    --------------------------------------
    Customer Name: Lucille Lotts
    --------------------------------------
    Item Type       #       Unit    Total
    Shirts          1       0.99    0.99
    Pants           8       1.95    15.6
    Others          6       3.25    19.5
    --------------------------------------
            Tax Amount:  $2.07517
            Total Order: $38.1652
    ======================================
    
    Amount tended: $50
    
    The difference is $13.91
    Thanks
    
    Press any key to continue...
  5. After testing the program, return to Bcb

Passing Arguments by Constant Reference

 

We have seen that passing an argument as a reference allows the compiler to retrieve the real value of the argument at its location rather than sending a request for a value of the variable. This speeds up the execution of the program. Also, when passing an argument as a constant, the compiler will make sure that the value of the passed argument is not modified.

If you pass an argument as reference, the compiler would access the argument from its location. The called function can modify the value of the argument. The advantage is that code execution is faster because the argument gives access to its address. The disadvantage could be that if the calling function modifies the value of the argument, when the function exits, the value of the argument would have (permanently) changed and the original value would be lost (actually, this can be an advantage as we have learned). If you do not want the value of the passed argument to be modified, you should pass the argument as a constant reference. When doing this, the compiler would access the argument at its location (or address) but it would make sure that the value of the argument stays intact.

To pass an argument as a constant reference, when declaring the function and when implementing it, type the const keyword, followed by the argument data type, followed by the ampersand operator "&", followed by a name for the argument. When declaring the function, the name of the argument is optional. Here is a function that receives an argument as a constant reference:

//---------------------------------------------------------------------------
double CalculateDiscount(const double &Original, double Rate)
{
    return Original * Rate / 100;
}
//---------------------------------------------------------------------------

You can mix arguments passed by value, those passed as reference, those passed by constant, and those passed by constant references. You will decide, based on your intentions, to apply whatever technique suits your scenario.

The following program illustrates the use of various techniques of passing arguments:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;

#pragma hdrstop

//---------------------------------------------------------------------------
#pragma argsused

double CalculateDiscount(const double &MarkedPrice, double = 20);
double PriceAfterDiscount(const double, const double);
double CalculateTaxAmount(const double &, double);
double CalculateNetPrice(const double &, const double &);
void DisplayResult(double, double, double, double, double);
//---------------------------------------------------------------------------
void RequestOriginalPrice(double &Price)
{
    cout << "Enter the original price: $";
    cin >> Price;
}
//---------------------------------------------------------------------------
void RequestDiscountRate(double &Discount)
{
    cout << "Enter discount rate(0.00 to 100.00): ";
    cin >> Discount;
}
//---------------------------------------------------------------------------
void RequestTaxRate(double& Tax)
{
    cout << "Enter the tax rate(0.00 to 100.00): ";
    cin >> Tax;
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    double OriginalPrice, DiscountRate, AfterDiscount, TaxRate;
    double DiscountAmount, TaxAmount, NetPrice;

    RequestOriginalPrice(OriginalPrice);
    RequestDiscountRate(DiscountRate);
    RequestTaxRate(TaxRate);

    DiscountAmount = CalculateDiscount(OriginalPrice, DiscountRate);
    AfterDiscount  = PriceAfterDiscount(OriginalPrice, DiscountAmount);
    TaxAmount      = CalculateTaxAmount(AfterDiscount, TaxRate);
    NetPrice       = CalculateNetPrice(AfterDiscount, TaxAmount);

    DisplayResult(OriginalPrice, DiscountAmount,
                  AfterDiscount, TaxAmount, NetPrice);

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------
double CalculateDiscount(const double &Original, double Rate)
{
    return Original * Rate / 100;
}
//---------------------------------------------------------------------------
double PriceAfterDiscount(const double Original, const double Discount)
{
    return Original - Discount;
}
//---------------------------------------------------------------------------
double CalculateTaxAmount(const double &Discount, double Rate)
{
    return Discount * Rate / 100;
}
//---------------------------------------------------------------------------
double CalculateNetPrice(const double &Discount, const double &TaxAmt)
{
    return Discount + TaxAmt;
}
//---------------------------------------------------------------------------
void DisplayResult(const double OrigPrice, const double DiscAmt,
                   const double Discount, const double TaxAmt,
                   const double FinalPrice)
{
    cout << "\n\nReceipt";
    cout << "\nOriginal Price:  $" << OrigPrice;
    cout << "\nDiscount Amount: $" << DiscAmt;
    cout << "\nAfter Discount:  $" << Discount;
    cout << "\nTax Amount:      $" << TaxAmt;
    cout << "\nNet Price:       $" << FinalPrice;
}
//---------------------------------------------------------------------------
 

Practical Learning: Passing Arguments by Constant References

 
  1. To illustrate the passing of arguments by constant references, change the Orders.h file as follows:
     
    //---------------------------------------------------------------------------
    #ifndef OrdersH
    #define OrdersH
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <string>
    using namespace std;
    //---------------------------------------------------------------------------
    namespace GeorgetownCleaners
    {
    // Price of items
    const double PriceShirt = 0.99;
    const double PricePants = 1.95;
    const double PriceOtherItems = 3.25;
    
    string  __fastcall GetCustomerName();
    void    __fastcall RequestNumberOfShirts(int &);
    void    __fastcall RequestNumberOfPants(int &);
    void    __fastcall RequestNumberOfOtherItems(int &);
    void    __fastcall GetTaxRate(double &);
    double  __fastcall CalculatePriceShirts(const int &Shirts,
                                            double Price = PriceShirt);
    double  __fastcall CalculatePricePants(const int &Pants,
                                           double = PricePants);
    double  __fastcall CalculatePriceOthers(const int &Others,
                                            double = PriceOtherItems );
    double  __fastcall CalculateTotalOrder(const double &Shirts,
                                           const double &Pants,
                                           const double &Others);
    double  __fastcall CalculateTaxAmount(const double &Total, double = 5.75);
    double  __fastcall CalculateTotalPrice(const double &Total,
                                           const double &Tax);
    void    __fastcall DisplayReceipt(const string Name, const int Shirts,
                                      const int Pants, const int Others,
                                      const double Tax, const double Total);
    }
    //---------------------------------------------------------------------------
    #endif
  2. In the Orders.cpp source file, change the functions as follows:
     
    //---------------------------------------------------------------------------
    
    #pragma hdrstop
    
    #include "Orders.h"
    //---------------------------------------------------------------------------
    #pragma package(smart_init)
    namespace GeorgetownCleaners
    {
    string __fastcall GetCustomerName()
    {
        . . . No Change
    //---------------------------------------------------------------------------
    double __fastcall CalculatePriceShirts(const int &Shirts, double Price)
    {
        return Shirts * Price;
    } 
    //---------------------------------------------------------------------------
    double __fastcall CalculatePricePants(const int &Pants, double Price)
    {  
        return Pants * Price;
    }
    //---------------------------------------------------------------------------
    double __fastcall CalculatePriceOthers(const int &Others, double Price)
    {         
        return Others * Price;
    }
    //---------------------------------------------------------------------------
    double __fastcall CalculateTotalOrder(const double &Shirts,
                                          const double &Pants,
                                          const double &Others)
    {
        return Shirts + Pants + Others;
    }
    //---------------------------------------------------------------------------
    double __fastcall CalculateTaxAmount(const double &Total, double Rate)
    {
        return Total * Rate / 100;
    }
    //---------------------------------------------------------------------------
    double __fastcall CalculateTotalPrice(const double &Total, const double &Tax)
    {
        return Total + Tax;
    }
    //---------------------------------------------------------------------------
    void __fastcall DisplayReceipt(const string CustName, const int Shirts,
                                   const int Pants, const int Others,
                                   const double Tax, const double Total)
    {
        . . .No Change
    }
    }
    //---------------------------------------------------------------------------
  3. Check the Main.cpp file:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    #pragma hdrstop
    #include "Orders.h"
    //---------------------------------------------------------------------------
    using namespace std;
    using namespace GeorgetownCleaners;
    #pragma argsused
    void __fastcall Welcome()
    {
        cout << " - Welcome to Georgetown Cleaning Services -\n";
    }
    //---------------------------------------------------------------------------
    void __fastcall RequestAmountTended(double &Amount)
    {
        // Get the amount tended
        cout << "\n\nAmount tended: $";
        cin >> Amount;
    }
    //---------------------------------------------------------------------------
    double __fastcall CalculateAmountOwed(const double &Tended,
                                          const double &Total)
    {
        return Tended - Total;
    }
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {
        . . . No Change
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  4. Test the program. Here is an example:
     
    - Welcome to Georgetown Cleaning Services -
    Enter customer identification
    First Name: Ken
    Last Name:  Allen
    Number of shirts: 4
    Numbers of Pants: 2
    # of other items: 4
    Enter the tax rate (such as 5.75): 5.75
    
    ======================================
     - Georgetown Cleaning Services -
    --------------------------------------
    Customer Name: Ken Allen
    --------------------------------------
    Item Type       #       Unit    Total
    Shirts          4       0.99    3.96
    Pants           2       1.95    3.9
    Others          4       3.25    13
    --------------------------------------
            Tax Amount:  $1.19945
            Total Order: $22.0594
    ======================================
    
    Amount tended: $40
    
    The difference is $19.14
    Thanks
    
    Press any key to continue...
  5. After testing the program, return to Bcb

Recursion

 

Recursion is the ability for a function to call itself. This allows you to perform an operation incrementally, using one function:

ReturnValue Function(Arguments, if any)
{
	Optional Action . . .
	Function();
	Optionan Action . . .
}

Like the functions we have used so far, a recursive function starts with a return value. If it would not return a value, you can define it with void. After its name, a recursive function can take one or more arguments. Most of the time, a recursive function takes at least one argument that it would then modify. In the body of the function, you can take the necessary actions. There are no particular steps to follow when implementing a recursive function. There are two main rules to observe:

  • In its body, the function must call itself
  • Before or after calling itself, the function must check a condition that would allow it to stop, otherwise, it might run continuously

These two conditions define the purpose of a recursive function. Consider the following Show() function:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused

void Show(int Number)
{
    if( Number > 0 )
    {
        cout << Number << endl;
        Number--;
        Show(Number);
    }
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    const int Nbr = 12;
    Show(Nbr);

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This function takes as argument an integer. In its body, the function is meant to display the value of its argument. To be able to display only positive values, the function checks whether the argument is higher than 0. If it is, it displays the value. To display another value, the function calls itself. To have a way to stop, the function can decrement the value it is asked to display. We take care of this before self-calling the function.

The above program would produce:

12
11
10
9
8
7
6
5
4
3
2
1

Press any key to continue...

 

 

Previous Copyright © 2005 FunctionX, Inc. Next