A function is an assignment or a task you are asking
C++ to perform for the functionality of your program. There are two
kinds of functions: those supplied to you and those you will be writing.
The functions that are supplied to you are usually in three categories:
those built-in Microsoft Windows operating system, those written in C++
(they are part of the C++ language), and those written by Borland (they
are supplied to you with the compiler, included in the various libraries
that are installed with the compiler). The use of these functions is the
same regardless of the means you get them; you should know what a
function looks like and how to use one, what functions are already
available, where they are located, and what a particular function does,
how and when to use them.
In order to create and use your function, you must let the
compiler know. Letting the compiler know about your function means you
“declare” it. The syntax of declaring a function is:
ReturnType FunctionName (Needs);
In English, an assignment considered a function is made of
three parts: its purpose, its needs, and the expectation.
The purpose of a function identifies what the function is
meant to do. When a function has carried its assignment, it provides a result.
For example, if a function were supposed to calculate the area of a square, the
result would be the area of a square. The result of a function used to get a
student’s first name would be a word representing a student’s first name.
When you expect a specific result from a function, such as
the area of a square, the result would be a numeric value; another kind of
result could be a word, etc. The result of a function is called a return value.
A function is also said to return a value.
There are two forms of expectations you will have from a
function: to return a specific value or to perform a simple assignment. If you
want the function to perform an assignment without giving you back a result,
such a function is qualified as void and would be declared as
void FunctionName(Needs);
A return value, if not void, can be any of the data
types we have studied so far. This means that a function can return a char,
an int, a float, a double, a bool, or a string.
Here are examples of declaring functions by defining their return values:
double FunctionName(Needs);
char FunctionName(Needs);
bool FunctionName(Needs);
string FunctionName(Needs);
A function name follows the same rules we have applied to
our variables so far. In addition, use a name that specifies what the function
is expected to do. Usually, a verb is appropriate for a function that performs
an action; an example would be add, start, assign, play, etc.
The names of most functions in C++ Builder start in
uppercase. We will follow the same convention in this book. Therefore, the above
names would be: Add, Start, Assign, Play.
If the assignment of a function is a combination of words,
such as converting a temperature from Celsius to Fahrenheit, start the name of
the function with a verb and append the necessary words each starting in
uppercase (remember that the name of a function is in one word). Examples
include ConvertToFahrenheit, CalculateArea, LoadFromFile, etc. Some functions
will not include a verb. They can simply represent a word such as Width, Index,
New. They can also be a combination of words; examples include DefaultName,
BeforeConstruction, or MethodOfAssignment. Here are examples of function names
double CalculateArea(Needs);
char Answer(Needs);
bool InTheBox(Needs);
string StudentName(Needs);
Introduction to Parameters
|
|
In order to carry its assignment, a function might be
supplied something. For example, when a function is used to calculate the area
of a square, you have to supply the side of the square, then the function will
work from there. On the other hand, a function used to get a student’s first
name does not have a need; its job is to supply or return something.
Some functions have needs and some do not. The needs of a
function are provided between parentheses. These needs could be as varied as
possible as we will learn later. If a function does not have a need, leave its
parentheses empty.
|
In some
references, instead of leaving the parentheses empty, the programmer
would write void. A function whose parentheses are empty or whose
parentheses display void performs the same. |
Here are examples of declaring functions:
double CalculateArea();
char Answer();
void Message(void);
bool InTheBox(void);
string StudentName();
|
In order to use a function in your program, you have to let
the compiler know what the function does. Sometimes (depending on where the
function is located in your program), you will not have to declare the function
before using it; but you must always tell the compiler what behavior you are
expecting.
We have seen that the syntax of declaring a function was:
ReturnType FunctionName();
To let the compiler know what the function is meant to do,
you have to “define” it. Defining a function means describing its behavior.
The syntax of defining a function is:
ReturnType FunctionName() {Body}
You define a function using the rule we applied with the
main() function. Define it starting with its return value (if none, use void),
followed by the function name, its argument (if any) between parentheses, and
the body of the function. Once you have defined a function, other functions can
use it.
As an assignment, a function has a body. The body of the
function describes what the function is supposed to do. The body starts with an
opening curly bracket “{“ and ends with a closing curly bracket “}”.
Everything between these two symbols belongs to the function. From what we have
learned so far, examples of functions would be:
double CalculateArea() {};
char Answer() {};
The most used function in C++ is called main().
In the body of the function, you describe the assignment the
function is supposed to perform. As simple as it looks, a function can be used
to display a message. Here is an example:
void Message()
{
cout << "This is C++ in its truest form.";
}
|
A function can also implement a complete behavior. For
example, on a program used to perform geometric shape calculations, you can use
different functions to handle specific tasks. Imagine you want to calculate the
area of a square. You can define a particular function that would request the
side of the square:
cout << “Enter the side of the square: “;
cin >> Side;
and let the function calculate the area using the formula Area = Side * Side.
Here is an example of such a function:
void SquareArea()
{
double Side;
cout << "\nEnter the side of the square: ";
cin >> Side;
cout << "\nSquare characteristics:";
cout << "\nSide = " << Side;
cout << "\nArea = " << Side * Side;
}
|
To create a more and effective program, divide jobs among
functions and give each function only the necessary behavior and a specific
assignment. A good program is not proven by long and arduous functions.
Practical Learning: Defining a Function
|
|
- Create a new C++ project using the Console Wizard
- Save the project as GCS2 in a new
folder called GCS2
- Save the unit as Main.cpp
- Change the contents of the file as follows:
//---------------------------------------------------------------------------
// Georgetown Cleaning Services
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
void Welcome();
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
void Welcome()
{
cout << " - Welcome to Georgetown Cleaning Services -\n";
}
//---------------------------------------------------------------------------
|
- To test the program, press F9.
One of the main reasons of using various functions in your
program is to isolate assignments; this allows you to divide the jobs among
different entities so that if something is going wrong, you might easily know
where the problem is. Functions trust each other, so much that one function does
not have to know HOW the other function performs its assignment. One function
simply needs to know what the other function needs and supply it.
Once a function has been defined, other functions can use
the result of its assignment. Imagine you define two functions A and B.
If Function A needs to use the result of Function B,
function A has to use the name of function B. This means Function A needs to
“call” Function B:
When calling one function from another function, provide
neither the return value nor the body, simply type the name of the function and
its list of arguments, if any. For example, to call a function named Welcome()
from the main() function, simply type it, like this:
int main(int argc, char* argv[])
{
Message(); // Calling the Message() function
return 0;
}
|
The compiler treats the calling of a function depending on
where the function is declared with regards to the caller. You can declare a
function before calling it. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
void Message()
{
cout << "This is C++ in its truest form.";
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
Message(); // Calling the Message() function
cout << "\n\nPress any key to continue...";
getchar();
return 0;
}
//---------------------------------------------------------------------------
|
If a function is defined after its caller, you should
declare it inside of the caller first. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
void Message();
cout << "We will start with the student registration process.\n";
Message(); // Calling the Message() function
cout << "\n\nPress any key to continue...";
getchar();
return 0;
}
//---------------------------------------------------------------------------
void Message()
{
cout << "Welcome to the Red Oak High School.";
}
//---------------------------------------------------------------------------
|
Practical Learning: Calling a Function
|
|
- From what we have learned so far, change the program as follows:
//---------------------------------------------------------------------------
// Georgetown Cleaning Services
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
void Welcome();
// Welcome the customer
Welcome();
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
void Welcome()
{
cout << " - Welcome to Georgetown Cleaning Services -\n";
}
//---------------------------------------------------------------------------
|
- To test the program, on the main menu, click Run -> Run.
- To return to Bcb, press any key.
- To save the program, on the Standard toolbar, click the Save All button.
A function that does not return a value is declared and
defined as void. Here is an example:
void Introduction()
{
cout << "This program is used to calculate the areas of some shapes.\n"
<< "The first shape will be a square and the second, a rectangle.\n"
<< "You will be requested to provide the dimensions and the program "
<< "will calculate the areas";
}
|
Any function could be a void type as long as you are
not expecting it to return a specific value. A void function with a more
specific assignment could be used to calculate and display the area of a square.
When a function is of type void, it cannot be
displayed as part of the cout extractor and it cannot be assigned to a
variable (since it does not return a value). Therefore, a void function
can only be called. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
void FahrenheitToCelsius()
{
int Fahrenheit, Celsius;
cout << "Conversion from Fahrenheight to Celsius\n";
cout << "Type the temperature in Fahrenheit: ";
cin >> Fahrenheit;
Celsius = 5 * (Fahrenheit - 32) / 9;
cout << endl << Fahrenheit << "F = " << Celsius << "C";
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
FahrenheitToCelsius();
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
Here is an example of running the program:
Conversion from Fahrenheight to Celsius
Type the temperature in Fahrenheit: 98
98F = 36C
Press any key to continue...
Practical Learning: Using void Functions
|
|
- Change the contents of the file as follows:
//---------------------------------------------------------------------------
// Georgetown Cleaning Services
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
void Welcome()
{
cout << " - Welcome to Georgetown Cleaning Services -\n";
}
//---------------------------------------------------------------------------
void ProcessAnOrder()
{
// Declare the number of items
int NumberOfShirts,
NumberOfPants,
NumberOfOtherItems;
// Price of items
const double PriceShirt = 0.99;
const double PricePants = 1.95;
const double PriceOtherItems = 3.25;
// Declare total prices by category
double TotalPriceShirt, TotalPricePants, TotalPriceOther;
double TotalOrder, AmountTended, Difference;
// Welcome the customer
cout << "Number of shirts: ";
cin >> NumberOfShirts;
cout << "Number of Pants: ";
cin >> NumberOfPants;
cout << "# of other items: ";
cin >> NumberOfOtherItems;
// Calculate the total price of each item category
TotalPriceShirt = NumberOfShirts * PriceShirt;
TotalPricePants = NumberOfPants * PricePants;
TotalPriceOther = NumberOfOtherItems * PriceOtherItems;
TotalOrder = TotalPriceShirt + TotalPricePants + TotalPriceOther;
// Display the result
cout << "\n - Georgetown Cleaning Services -\n";
cout << "\nFor a cleaning order of "
<< NumberOfShirts << " shirts and "
<< NumberOfPants + NumberOfOtherItems << " other items, "
<< "\nthat will be: $" << TotalOrder;
// Get the amouont tended
cout << "\n\nAmount tended: $";
cin >> AmountTended;
// Calculate the difference for the customer
Difference = AmountTended - TotalOrder;
// Final message
cout << "\nThe difference is $" << Difference << "\nThanks";
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
Welcome();
ProcessAnOrder();
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
- Test the program. Here is an example:
- Welcome to Georgetown Cleaning Services -
Number of shirts: 5
Number of Pants: 2
# of other items: 2
- Georgetown Cleaning Services -
For a cleaning order of 5 shirts and 4 other items,
that will be: $15.35
Amount tended: $20
The difference is $4.65
Thanks
Press any key to continue...
|
- Return to Bcb
Techniques of Returning Values
|
|
If you declare a function that is returning anything else
than void, the compiler will need to know what value the function
returns. The return value must be the same type declared. The value is returned
using the return keyword.
If a function is declared as a char, make sure it returns a character
(only one character). Here is an example:
char Answer()
{
char a;
cout << "Do you consider yourself a reliable employee (y=Yes/n=No)? ";
cin >> a;
return a;
}
|
Whether a function returns a value or it of void type, it
can be called in another function the same way we have done with void functions
so far. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
char Answer()
{
char a;
cout << "Do you consider yourself a reliable employee (y=Yes/n=No)? ";
cin >> a;
return a;
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
Answer();
cout << "\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
Here is an example of running the program:
Do you consider yourself a reliable employee (y=Yes/n=No)? g
Press any key to continue...
If a function returns a value, that value can be assigned to
another value in the calling function. To do this, assign the called function to
a local variable. Remember to provide the parentheses to the called function
(some languages (such as Pascal or Basic, etc) do not require the parentheses).
Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
char Answer()
{
char a;
cout << "Do you consider yourself a reliable employee (y=Yes/n=No)? ";
cin >> a;
return a;
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
char Ans;
Ans = Answer();
cout << "\nApplicant's Answer: " << Ans;
cout << "\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
Here is an example of running the program:
Do you consider yourself a reliable employee (y=Yes/n=No)? Y
Applicant's Answer: Y
Press any key to continue...
A function can also handle a complete assignment and only
hand a valid value to other desired functions. Imagine you want to process
member’s applications at a sports club. You can define a function that would
request the first and last names; other functions that need a member’s full
name would request it from such a function without worrying whether the name is
complete. The following function is in charge of requesting both names. It
returns a full name that any desired function can use:
string GetMemberName()
{
string FName, LName, FullName;
cout << "New Member Registration.\n";
cout << "First Name: ";
cin >> FName;
cout << "Last Name: ";
cin >> LName;
FullName = FName + " " + LName;
return FullName;
}
|
Practical Learning: Returning Values
|
|
- To apply a basic technique of returning a value, change the content of the
file as follows:
//---------------------------------------------------------------------------
// Georgetown Cleaning Services
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
void Welcome()
{
cout << " - Welcome to Georgetown Cleaning Services -\n";
}
//---------------------------------------------------------------------------
int RequestNumberOfShirts()
{
int Shirts;
cout << "Number of shirts: ";
cin >> Shirts;
return Shirts;
}
//---------------------------------------------------------------------------
int RequestNumberOfPants()
{
int Pants;
cout << "Numbers of Pants: ";
cin >> Pants;
return Pants;
}
//---------------------------------------------------------------------------
int RequestNumberOfOtherItems()
{
int Items;
cout << "# of other items: ";
cin >> Items;
return Items;
}
//---------------------------------------------------------------------------
double RequestAmountTended()
{
double Amount;
// Get the amouont tended
cout << "\n\nAmount tended: $";
cin >> Amount;
return Amount;
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
// Declare the number of items
int NumberOfShirts,
NumberOfPants,
NumberOfOtherItems;
// Price of items
const double PriceShirt = 0.99;
const double PricePants = 1.95;
const double PriceOtherItems = 3.25;
// Declare total prices by category
double TotalPriceShirt, TotalPricePants, TotalPriceOther;
double TotalOrder, AmountTended, Difference;
// Welcome the customer
Welcome();
NumberOfShirts = RequestNumberOfShirts();
NumberOfPants = RequestNumberOfPants();
NumberOfOtherItems = RequestNumberOfOtherItems();
// Calculate the total price of each item category
TotalPriceShirt = NumberOfShirts * PriceShirt;
TotalPricePants = NumberOfPants * PricePants;
TotalPriceOther = NumberOfOtherItems * PriceOtherItems;
TotalOrder = TotalPriceShirt + TotalPricePants + TotalPriceOther;
// Display the result
cout << "\n - Georgetown Cleaning Services -\n";
cout << "\nFor a cleaning order of "
<< NumberOfShirts << " shirts and "
<< NumberOfPants + NumberOfOtherItems << " other items, "
<< "\nthat will be: $" << TotalOrder;
AmountTended = RequestAmountTended();
// Calculate the difference for the customer
Difference = AmountTended - TotalOrder;
// Final message
cout << "\nThe difference is $" << Difference << "\nThanks";
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
- Test the program. Here is an example:
- Welcome to Georgetown Cleaning Services -
Number of shirts: 12
Numbers of Pants: 6
# of other items: 2
- Georgetown Cleaning Services -
For a cleaning order of 12 shirts and 8 other items,
that will be: $30.08
Amount tended: $40
The difference is $9.92
Thanks
Press any key to continue...
|
- After testing the program, press Enter to return to Bcb.
So far, we have learned that functions provide a safe
technique to make the main() function less crowded. Furthermore, you can isolate
your functions in their own file. After creating creating such a file, you can
simply include it in the file that contains the main() function or in any other
file that would need those functions. You can create your functions in a file
called a source file. The Source File has a .cpp extension. By default, the
first source file is called File1.cpp. If you create additional files, they
would have incremental names such as File2.cpp, File3.cpp, etc. If you want to
change a source file name, you must save it and rename it.
To create a source file, from the New property page of the
New Items dialog box, select the Cpp File icon and implement the functions.
Here is an example of a source file:
//---------------------------------------------------------------------------
#include <iostream>
using namespace std;
//---------------------------------------------------------------------------
double RequestOriginalPrice()
{
double Price;
cout << "Enter the original price: $";
cin >> Price;
return Price;
}
//---------------------------------------------------------------------------
double RequestDiscountRate()
{
double Discount;
cout << "Enter discount rate(0.00 to 100.00): ";
cin >> Discount;
return Discount;
}
//---------------------------------------------------------------------------
double RequestTaxRate()
{
double Tax;
cout << "Enter the tax rate(0.00 to 100.00): ";
cin >> Tax;
return Tax;
}
//---------------------------------------------------------------------------
|
If you want to use the functions of such a source file in
another file, first include the file with
#include "FileName.cpp"
Then you can call any of its functions as you see fit.
Suppose the above function was saved as File1.cpp, here is how its central
function can be usedfunc:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
#include "File1.cpp"
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
double OriginalPrice, DiscountRate, PriceAfterDiscount, TaxRate;
double DiscountAmount, TaxAmount, NetPrice;
OriginalPrice = RequestOriginalPrice();
DiscountRate = RequestDiscountRate();
TaxRate = RequestTaxRate();
DiscountAmount = OriginalPrice * DiscountRate / 100;
PriceAfterDiscount = OriginalPrice - DiscountAmount;
TaxAmount = PriceAfterDiscount * TaxRate / 100;
NetPrice = PriceAfterDiscount + TaxAmount;
cout << "\n\nReceipt";
cout << "\nOriginal Price: $" << OriginalPrice;
cout << "\nDiscount Amount: $" << DiscountAmount;
cout << "\nAfter Discount: $" << PriceAfterDiscount;
cout << "\nTax Amount: $" << TaxAmount;
cout << "\nNet Price: $" << NetPrice;
cout << "\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
Here is an example of running the program:
Enter the original price: $120.50
Enter discount rate(0.00 to 100.00): 20
Enter the tax rate(0.00 to 100.00): 5.75
Receipt
Original Price: $120.5
Discount Amount: $24.1
After Discount: $96.4
Tax Amount: $5.543
Net Price: $101.943
Press any key to continue...
|
Practical Learning: Creating a Source File
|
|
- Start a new application. Create it using the Console Wizard and make sure
you select the C++ radio button in the Console Wizard dialog box.
- To save the project, on the Standard toolbar, click the Save All button
- Locate the folder that contains your exercises and click the Create New
Folder button
- Type GCS3 and press Enter.
Double-click GCS3 to display it in the Save In combo box.
- Replace the name Unit1 with Main and
make sure that the Save As Type combo box is displaying C++Builder Unit (*.cpp).
- Press Enter
- Replace the name of the project with CleaningOrders
and press Enter.
- To create a source file, on the main menu, click File -> New…
- From the New property page of the New Items dialog box, click the Cpp File
icon
- Click OK
- To save the source file, on the main menu, click File -> Save
- In the Save File1 As dialog box, replace the name of the file with Orders
and click Save
- In the empty file, type:
#include <iostream>
#include <conio>
using namespace std;
//---------------------------------------------------------------------------
void Welcome()
{
cout << " - Welcome to Georgetown Cleaning Services -\n";
}
//---------------------------------------------------------------------------
int RequestNumberOfShirts()
{
int Shirts;
cout << "Number of shirts: ";
cin >> Shirts;
return Shirts;
}
//---------------------------------------------------------------------------
int RequestNumberOfPants()
{
int Pants;
cout << "Numbers of Pants: ";
cin >> Pants;
return Pants;
}
//---------------------------------------------------------------------------
int RequestNumberOfOtherItems()
{
int Items;
cout << "# of other items: ";
cin >> Items;
return Items;
}
//---------------------------------------------------------------------------
double RequestAmountTended()
{
double Amount;
// Get the amouont tended
cout << "\n\nAmount tended: $";
cin >> Amount;
return Amount;
}
//---------------------------------------------------------------------------
|
- To use the functions of the above source file, click the Main.cpp tab to
access the main() function.
- Change the file as follows:
//---------------------------------------------------------------------------
// Georgetown Cleaning Services
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
#include "Orders.cpp"
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
// Declare the number of items
int NumberOfShirts,
NumberOfPants,
NumberOfOtherItems;
// Price of items
const double PriceShirt = 0.99;
const double PricePants = 1.95;
const double PriceOtherItems = 3.25;
// Declare total prices by category
double TotalPriceShirt, TotalPricePants, TotalPriceOther;
double TotalOrder, AmountTended, Difference;
// Welcome the customer
Welcome();
NumberOfShirts = RequestNumberOfShirts();
NumberOfPants = RequestNumberOfPants();
NumberOfOtherItems = RequestNumberOfOtherItems();
// Calculate the total price of each item category
TotalPriceShirt = NumberOfShirts * PriceShirt;
TotalPricePants = NumberOfPants * PricePants;
TotalPriceOther = NumberOfOtherItems * PriceOtherItems;
TotalOrder = TotalPriceShirt + TotalPricePants + TotalPriceOther;
// Display the result
cout << "\n - Georgetown Cleaning Services -\n";
cout << "\nFor a cleaning order of "
<< NumberOfShirts << " shirts and "
<< NumberOfPants + NumberOfOtherItems << " other items, "
<< "\nthat will be: $" << TotalOrder;
AmountTended = RequestAmountTended();
// Calculate the difference for the customer
Difference = AmountTended - TotalOrder;
// Final message
cout << "\nThe difference is $" << Difference << "\nThanks";
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
- To save the project, on the main menu, click file -> Save All
- Test the program. Here is an example:
- Welcome to Georgetown Cleaning Services -
Number of shirts: 15
Numbers of Pants: 0
# of other items: 1
- Georgetown Cleaning Services -
For a cleaning order of 15 shirts and 1 other items,
that will be: $18.1
Amount tended: $20
The difference is $1.9
Thanks
Press any key to continue...
|
- Return to Bcb
If you are writing a program with files that you intend to
distribute, and if you create source files as above, you may have to also
distribute them. This can lead to other people manipulating your code. The C++
compilers allow you to create the foundation of your files and variables in a
separate file called a header file. This allows you to implement your functions
in the source file without having to distribute your source file, in which case
other people do not need to know how your functions are implemented. Again, this
technique of using both header and source files can help you protect your
intellectual work by making available only the header file (and possibly a
library or executable that contains the source file(s)).
To create a header file, from the New property page of the
New Items dialog box, select the Header File icon and declare the variables and
functions. Here is an example of a header file:
double RequestOriginalPrice();
double RequestDiscountRate();
double RequestTaxRate();
As done with the source file, you can define all your
functions in header file. You can also define just a few functions and simply
declare other that would be implemented in another file.
If you create a file that contains some declared functions
that are not defined, you can define such functions in a separate source file,
such as the source file we used above. If the functions of a header file have
been defined or implemented in a source file, to use such functions in another
file, simply include their header file. The compiler would try to find where the
functions are implemented. If the compiler cannot find their implementations,
you may receive an error. Therefore, when including a header file in another
file, make sure that a function that is called in the new file has been
implemented somewhere. Here is an example:
Header File: File1.h
|
double RequestOriginalPrice();
double RequestDiscountRate();
double RequestTaxRate();
|
Source File: File1.cpp
|
//---------------------------------------------------------------------------
#include <iostream>
using namespace std;
#include "File1.h"
//---------------------------------------------------------------------------
double RequestOriginalPrice()
{
double Price;
cout << "Enter the original price: $";
cin >> Price;
return Price;
}
//---------------------------------------------------------------------------
double RequestDiscountRate()
{
double Discount;
cout << "Enter discount rate(0.00 to 100.00): ";
cin >> Discount;
return Discount;
}
//---------------------------------------------------------------------------
double RequestTaxRate()
{
double Tax;
cout << "Enter the tax rate(0.00 to 100.00): ";
cin >> Tax;
return Tax;
}
//---------------------------------------------------------------------------
|
Source File: Main.cpp
|
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
#include "File1.h"
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
double OriginalPrice, DiscountRate, PriceAfterDiscount, TaxRate;
double DiscountAmount, TaxAmount, NetPrice;
OriginalPrice = RequestOriginalPrice();
DiscountRate = RequestDiscountRate();
TaxRate = RequestTaxRate();
DiscountAmount = OriginalPrice * DiscountRate / 100;
PriceAfterDiscount = OriginalPrice - DiscountAmount;
TaxAmount = PriceAfterDiscount * TaxRate / 100;
NetPrice = PriceAfterDiscount + TaxAmount;
cout << "\n\nReceipt";
cout << "\nOriginal Price: $" << OriginalPrice;
cout << "\nDiscount Amount: $" << DiscountAmount;
cout << "\nAfter Discount: $" << PriceAfterDiscount;
cout << "\nTax Amount: $" << TaxAmount;
cout << "\nNet Price: $" << NetPrice;
cout << "\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
If you define a function in a source file without having
declared in the header file but try accessing in another file, even if you
include the header of the other function, the function would not be accessible
and you would receive an error.
To make sure that the header file has not been created
anywhere in the program, you can ask the compiler to check it. This is done
using the #ifndef preprocessor followed by a one-word name for the file.
Once the compiler has made sure that the header file is unique, you can ask the
compiler to define it. At the end of the file (that is, when the objects of the
file have been declared), signal the closing of the file with the #endif
preprocessor.
Here is an example:
#ifndef DisountStore_H
#define DisountStore_H
double RequestOriginalPrice();
double RequestDiscountRate();
double RequestTaxRate();
#endif // DisountStore_H
|
Practical Learning: Creating a Header File
|
|
- To create a header file, on the main menu of the C++ Builder, click File
-> New…
- From the New property page of the New Items dialog box, click the Header
File icon
- Click OK
- To save the header file, on the main menu, click File -> Save
- In the File Name edit box, type Orders.h and make sure you include
the .h extension
- Click Save
- In the empty file, type:
//---------------------------------------------------------------------------
void Welcome();
int RequestNumberOfShirts();
int RequestNumberOfPants();
int RequestNumberOfOtherItems();
double RequestAmountTended();
//---------------------------------------------------------------------------
|
- Click the Orders.cpp tab and include the Orders.h header file as follows:
- Replace the empty file with:
#include <iostream>
#include <conio>
using namespace std;
#include "Orders.h"
//---------------------------------------------------------------------------
void Welcome()
{
cout << " - Welcome to Georgetown Cleaning Services -\n";
}
//---------------------------------------------------------------------------
int RequestNumberOfShirts()
. . .
|
- Click the Main.cpp tab to access the main() function.
- Change the file as follows:
//---------------------------------------------------------------------------
// Georgetown Cleaning Services
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
#include "Orders.h"
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
. . .
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
- To save the project, on the main menu, click file -> Save All
- Test the program. Here is an example:
- Welcome to Georgetown Cleaning Services -
Number of shirts: 1
Numbers of Pants: 1
# of other items: 0
- Georgetown Cleaning Services -
For a cleaning order of 1 shirts and 1 other items,
that will be: $2.94
Amount tended: $5
The difference is $2.06
Thanks
Press any key to continue...
|
- Return to Bcb
The functions in this section calculate the Simple Interest:
Interest |
= |
Principal * Rate * Time |
I |
= |
P * r * t |
Then we calculate the Maturity Value as follows:
Maturity Value |
= |
Principal + Interest |
S |
= |
P + I |
We also calculate the Bank Discount as follows:
Discount |
= |
Maturity Value * Discount Rate * Term of Discount |
D |
= |
S * d * t |
Finally, we calculate the Proceeds as follows:
Proceeds |
= |
Maturity Value - Bank Discount |
P |
= |
S - D |
Functions Local Definition
|
|
|
Like a variable, a function can be part of a namespace.
Such a function belongs to the namespace and enjoys all the advantages
of the members of a namespace. To declare a function in a namespace,
type its return type, followed by a name, followed by the argument(s) if
any inside of parentheses. Here is an example: |
//---------------------------------------------------------------------------
namespace InterestAndDiscount
{
double Principal;
double Rate;
double Time;
double CalcInterest();
double CalcMaturityValue();
}
//---------------------------------------------------------------------------
|
A member function of a namespace is accessed following the
same rules we applied to member variables, using the scope access operator ::
There are two main ways you can implement a member function.
In the body of the namespace, which is a local implementation, delimit the body
of the function with an opening curly bracket “{“ and a closing curly
bracket “}”. A function that is a member of a namespace has complete access
to the member variables of the same namespace. Therefore, you do not have to
pass the member variables as arguments to the member functions. Here is an
example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
namespace InterestAndDiscount
{
double Principal;
double Rate;
double Time;
double CalcInterest()
{
double RateValue = Rate / 100;
return Principal * RateValue * Time;
}
double CalcMaturityValue()
{
return Principal + CalcInterest();
}
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
InterestAndDiscount::Principal = 6500; // $
InterestAndDiscount::Rate = 14.00;// %
InterestAndDiscount::Time = 2; // Years
cout << "Interest on a loan";
cout << "\nPrincipal: $" << InterestAndDiscount::Principal;
cout << "\nRate: " << InterestAndDiscount::Rate << "%";
cout << "\nTime: " << InterestAndDiscount::Time << " years";
cout << "\nInterest: $" << InterestAndDiscount::CalcInterest();
cout << "\nMaturity Value: $" << InterestAndDiscount::CalcMaturityValue();
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
This would produce:
Interest on a loan
Principal: $6500
Rate: 14%
Time: 2 years
Interest: $1820
Maturity Value: $8320
Press any key to continue...
|
If a nested namespace has its own functions, you can also
implement them in the body of the nested namespace. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
namespace InterestAndDiscount
{
double Principal;
double Rate;
double Time;
double Interest()
{
return Principal * (Rate / 100) * Time;
}
double MaturityValue()
{
return Principal + Interest();
}
namespace BankDiscount
{
double Maturity;
duble DiscountRate;
double TermOfDiscount;
double Discount()
{
return Maturity * (DiscountRate / 100) * TermOfDiscount;
}
double Proceeds()
{
return Maturity - Discount();
}
}
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
InterestAndDiscount::Principal = 28500; // $
InterestAndDiscount::Rate = 12.35; // 12.35%
InterestAndDiscount::Time = 6; // Years
InterestAndDiscount::BankDiscount::Maturity = 1000; // $
InterestAndDiscount::BankDiscount::DiscountRate = 14.35;
InterestAndDiscount::BankDiscount::TermOfDiscount = 0.35;
cout << "Interest on a loan";
cout << "\nPrincipal: $" << InterestAndDiscount::Principal;
cout << "\nRate: " << InterestAndDiscount::Rate << " %";
cout << "\nTime: " << InterestAndDiscount::Time << " years";
cout << "\nInterest: $" << InterestAndDiscount::Interest();
cout << "\nMaturity Value: $" << InterestAndDiscount::MaturityValue();
cout << "\n\nBank Discount: $"
<< InterestAndDiscount::BankDiscount::Discount();
cout << "\nProceeds: $"
<< InterestAndDiscount::BankDiscount::Proceeds();
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
After locally implementing the member functions of a nested
namespace, you can access its members and display their value in the main()
function as seen above.
With the using namespace routine, you can improve the
access to the members of a namespace as follows:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
namespace InterestAndDiscount
{
. . .
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
using namespace InterestAndDiscount;
Principal = 28500; // $
Rate = 12.35; // 12.35%
Time = 6; // Years
cout << "Interest on a loan";
cout << "\nPrincipal: $" << Principal;
cout << "\nRate: " << Rate << " %";
cout << "\nTime: " << Time << " years";
cout << "\nInterest: $" << Interest();
cout << "\nMaturity Value: $" << MaturityValue();
using namespace InterestAndDiscount::BankDiscount;
Maturity = 1000; // $
DiscountRate = 15.25;
TermOfDiscount = 0.35;
cout << "\n\nBank Discount: $" << Discount();
cout << "\nProceeds: $" << Proceeds();
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
This would produce:
Interest on a loan
Principal: $28500
Rate: 12.35 %
Time: 6 years
Interest: $21118.5
Maturity Value: $49618.5
Bank Discount: $53.375
Proceeds: $946.625
Press any key to continue...
To implement a member function outside the body of a
namespace, type the return value, followed by the name of the namespace,
followed by the scope access operator “::”. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
namespace InterestAndDiscount
{
double Principal;
double Rate;
double Time;
double Interest();
double MaturityValue();
}
//---------------------------------------------------------------------------
double InterestAndDiscount::Interest()
{
return Principal * (Rate / 100) * Time;
}
//---------------------------------------------------------------------------
double InterestAndDiscount::MaturityValue()
{
return Principal + Interest();
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
using namespace InterestAndDiscount;
Principal = 28500; // $
Rate = 12.35; // 12.35%
Time = 6; // Years
cout << "Interest on a loan";
cout << "\nPrincipal: $" << Principal;
cout << "\nRate: " << Rate << " %";
cout << "\nTime: " << Time << " years";
cout << "\nInterest: $" << Interest();
cout << "\nMaturity Value: $" << MaturityValue();
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
To implement the member functions of a nested namespace
outside of the parent namespace, you must qualify each member function to
specify the function (or the variable) you are calling. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
namespace InterestAndDiscount
{
double Principal;
double Rate;
double Time;
double Interest();
double MaturityValue();
namespace BankDiscount
{
double Maturity;
double DiscountRate;
double TermOfDiscount;
double Discount();
double Proceeds();
}
}
//---------------------------------------------------------------------------
double InterestAndDiscount::Interest()
{
return Principal * (Rate / 100) * Time;
}
//---------------------------------------------------------------------------
double InterestAndDiscount::MaturityValue()
{
return Principal + Interest();
}
//---------------------------------------------------------------------------
double InterestAndDiscount::BankDiscount::Discount()
{
return Maturity * (DiscountRate / 100) * TermOfDiscount;
}
//---------------------------------------------------------------------------
double InterestAndDiscount::BankDiscount::Proceeds()
{
return Maturity - Discount();
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
using namespace InterestAndDiscount;
using namespace InterestAndDiscount::BankDiscount;
Principal = 28500;
Rate = 12.35;
Time = 6;
cout << "Interest on a loan";
cout << "\nPrincipal: $" << Principal;
cout << "\nRate: " << Rate << " %";
cout << "\nTime: " << Time << " years";
cout << "\nInterest: $" << Interest();
cout << "\nMaturity Value: $" << MaturityValue();
Maturity = 1000;
DiscountRate = 15.25;
TermOfDiscount = 0.35;
cout << "\n\nBank Discount: $" << Discount();
cout << "\nProceeds: $" << Proceeds();
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
Namespaces and External Functions
|
|
The member variables of a namespace are variables like any
of those we have used so far. They can request their values from an outside
function. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
namespace InterestAndDiscount
{
double Principal;
double Rate;
double Time;
double Interest();
double MaturityValue();
namespace BankDiscount
{
double Maturity;
double DiscountRate;
double TermOfDiscount;
double Discount();
double Proceeds();
}
}
//---------------------------------------------------------------------------
double InterestAndDiscount::Interest()
{
return Principal * (Rate / 100) * Time;
}
//---------------------------------------------------------------------------
double InterestAndDiscount::MaturityValue()
{
return Principal + Interest();
}
//---------------------------------------------------------------------------
double InterestAndDiscount::BankDiscount::Discount()
{
return Maturity * (DiscountRate / 100) * TermOfDiscount;
}
//---------------------------------------------------------------------------
double InterestAndDiscount::BankDiscount::Proceeds()
{
return Maturity - Discount();
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
using namespace InterestAndDiscount;
double RequestPrincipal();
double RequestRate();
double RequestTime();
cout << "Loan Processing";
cout << "\nEnter the following values\n";
Principal = RequestPrincipal();
Rate = RequestRate();
Time = RequestTime();
cout << "\nInterest on a loan";
cout << "\nPrincipal: $" << Principal;
cout << "\nRate: " << Rate << " %";
cout << "\nTime: " << Time << " years";
cout << "\nInterest: $" << Interest();
cout << "\nMaturity Value: $" << MaturityValue();
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
double RequestPrincipal()
{
double P;
cout << "Enter the Principal: $";
cin >> P;
return P;
}
//---------------------------------------------------------------------------
double RequestRate()
{
int R;
cout << "Enter the Rate (between 0 and 100): ";
cin >> R;
return R;
}
//---------------------------------------------------------------------------
double RequestTime()
{
int T;
cout << "How many years you need for the loan? ";
cin >> T;
return T;
}
//---------------------------------------------------------------------------
|
Here is an example of running the program:
Loan Processing
Enter the following values
Enter the Principal: $30000
Enter the Rate (between 0 and 100): 16
How many years you need for the loan? 5
Interest on a loan
Principal: $30000
Rate: 16 %
Time: 5 years
Interest: $24000
Maturity Value: $54000
|
|