|
Introduction to Functions |
|
Introduction to Functions |
|
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 the operating system, those written in C++ (they are part of the C++ language), and those supplied with your programming environment. The use of these functions is the same regardless of the means you get them; you should know what a function looks like, how to create one, what functions are already available, where they are located, and what a particular function does, how and when to use it. |
|
Function Definition |
|
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. |
|
Return Value |
|
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 is 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. 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: a specific value or 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); |
|
Function Names |
|
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 this book will start in uppercase. 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); |
|
Arguments – 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 may not have a need; its job would be 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. 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. In this book, if a function does not have a need, we will leave its parentheses empty. Some functions will have only one need, some others will have many. A function’s need is called an Argument. If a function has a lot of needs, these are its arguments. The argument is a valid variable and is defined by its data type and a name. For example, if a function is supposed to calculate the area of a square and it is expecting to receive the side of the square, you can declare it as double CalculateArea(double Side); A function used to get a student’s first name could be declared as: string FirstName(); Here are examples of declaring functions; some take arguments, some don’t: double CalculateArea(double Side); |
|
Defining Functions |
|
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(Arguments); To let the compiler know what the function is meant to do, you have to “define” it; which also means describing its behavior. The syntax of defining a function is: ReturnType FunctionName(Needs) {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. |
|
Function Body |
|
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(double Side) {}; 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: “; 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;
}
|
|
Calling Functions |
|
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 does, and what that other function needs. 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 that Function A has 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: main()
{
Message(); // Calling the Message() function
}
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;
void Message()
{
cout << "This is C++ in its truest form.";
}
main()
{
Message(); // Calling the Message() function
}
If a function is defined after its caller, you must declare it prior to calling it. Here is an example: #include <iostream.h>
main()
{
void Message();
cout << "We will start with the student registration process.";
Message(); // Calling the Message() function
}
void Message()
{
cout << "Welcome to the Red Oak High School.";
}
To use any of the functions that ship with the compiler, first include the library in which the function is defined, then call the necessary function. Here is an example that calls the getchar() function: #include <iostream>
#include <stdio.h>
using namespace std;
main()
{
cout << "This is C++ in its truest form...\n\n";
getchar();
}
|
|
Techniques of Returning a Value |
|
void Functions |
|
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. Here is an example: void SquareArea()
{
double Side;
cout << "\nEnter the side of the square: ";
cin >> Side;
cout << "\nSquare characteristics:";
cout << "\nSide = " << Side;
cout << "\nArea = " << Side * Side;
}
When a function is of type void, it cannot be displayed on the same line with 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. |
|
Returning a Value |
|
If you declare a function that is returning anything (a function that is not void), the compiler will need to know what value the function returns. The return value must be the same type declared. The value is set with 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;
}
A good function can also handle a complete assignment and only hand a valid value to other calling 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;
}
The return value can also be an expression. Here is an example: double SquareArea(double Side)
{
return (Side * Side);
}
A return value could also be a variable that represents the result. Here is example: double SquareArea(double Side)
{
double Area;
Area = Side * Side;
return Area;
}
If a function returns a value (other than void), a calling function can assign its result to a local variable like this: Major = GetMajor(); Here is an example: #include <iostream>
using namespace std;
int GetMajor()
{
int Choice;
cout << "\n1 - Business Administration";
cout << "\n2 - History";
cout << "\n3 - Geography";
cout << "\n4 - Education";
cout << "\n5 - Computer Sciences";
cout << "\nYour Choice: ";
cin >> Choice;
return Choice;
}
main()
{
int Major;
cout << "Welcome to the student orientation program.";
cout << "Select your desired major:";
Major = GetMajor();
cout << "You select " << Major; cout << "\n";
}
You can also directly display the result of a function using the cout operator. In this case, after typing cout and its << operator, type the function name and its arguments names, if any. So far, the compiler was displaying a warning because our main() function was not returning anything. In C++, a function should always display a return type, otherwise, make it void. If you declare a function without a return type, by default, the compiler considers that such a function should return an integer. Therefore, the main() function we have used so far should return an integer as follows: #include <iostream>
using namespace std;
main()
{
cout << "This is C++ in its truest form...\n\n";
return 0;
}
Strictly stated, the main() function can return any integer, which simply indicates that the program has ended. Returning 0 means that the program has terminated successfully. Since the main() function now returns an integer, you should indicate this on its declared line. A better version of the above main() function would be: #include <iostream>
using namespace std;
int main()
{
cout << "This is C++ in its truest form...\n\n";
return 0;
}
|
|
Techniques of Passing Arguments |
|
In order to perform its assignment, a function may need arguments. Any function that wants to use the result of another function must supply the other function’s required arguments, if any. When declaring a function that uses arguments, specify each argument with a data type and a name. |
|
Passing Arguments by Value |
|
To use a function inside of another function, that is, to call a function from another function, specify the name of the function and its list of arguments (if any) inside of parentheses; only the name of each argument is needed. You can declare a function like this: float GetHours(string FullName); To call such a function from another, you would use: GetHours(FullName); Here is an example: #include <iostream>
#include <string>
using namespace std;
string GetName()
{
string FirstName, LastName, FN;
cout << "Employee's First Name: ";
cin >> FirstName;
cout << "Employee's Last Name: ";
cin >> LastName;
FN = FirstName + " " + LastName;
return FN;
}
int main()
{
string FullName;
double Hours;
double GetHours(string FullName);
FullName = GetName();
Hours = GetHours(FullName);
cout << "\nEmployee's Name: " << FullName;
cout << "\nWeekly Hours: " << Hours << " hours\n\n";
return 0;
}
double GetHours(string FullName)
{
double Mon, Tue, Wed, Thu, Fri, TotalHours;
cout << endl << FullName << "'s Weekly Hours\n";
cout << "Monday: "; cin >> Mon;
cout << "Tuesday: "; cin >> Tue;
cout << "Wednesday: "; cin >> Wed;
cout << "Thursday: "; cin >> Thu;
cout << "Friday: "; cin >> Fri;
TotalHours = Mon + Tue + Wed + Thu + Fri;
return TotalHours;
}
Here is an example of running the program: Employee's First Name: Frank Employee's Last Name: Dassault Frank Dassault's Weekly Hours Monday: 8.00 Tuesday: 8.50 Wednesday: 9.00 Thursday: 8.00 Friday: 8.00 Employee's Name: Frank Dassault Weekly Hours: 41.5 hours Press any key to continue... When declaring a function, the compiler does not require that you supply a name for each argument, it only needs to know what type of argument(s) and how many arguments a function takes. This means that the GetHours() function could have been declared as float GetHours(string); Furthermore, the compiler does not care about the name you give an argument when declaring a function. Imagine you want to write a function that would calculate an item’s purchase price based on the item’s store price added the tax. The tax rate is a percentage value. This means that a tax rate set at 7.50% in C++ terms is equal to 0.075 (because 7.50/100 = 0.075). The tax amount collected on a purchase is taken from an item’s price; its formula is: TaxRate The formula of calculating the final price of an item is: Final Price = Item Price + Tax Amount Here is an example: #include <iostream>
using namespace std;
int main()
{
double ItemPrice, TaxRate;
double PurchasePrice(double ItemPrice, double TaxRate);
cout << "Enter the price of the item: ";
cin >> ItemPrice;
cout << "Enter the tax rate: ";
cin >> TaxRate;
cout << "\nThe final price is: " << PurchasePrice(ItemPrice, TaxRate);
cout << "\n\n";
return 0;
}
double PurchasePrice(double ItemPrice, double TaxRate)
{
double Price;
Price = ItemPrice + (ItemPrice * TaxRate / 100);
return Price;
}
Here is an example of running the program: Enter the price of the item: 125.95 Enter the tax rate: 5.75 The final price is: 133.192 Press any key to continue... |
|
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. |
![]() |
|
The location of a variable in memory is referred to as its address. If you supply the argument using its name, 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 0, 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 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); 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>
using namespace std;
int main()
{
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;
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. 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;
}
|
|
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 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>
using namespace std;
double CalculateNetPrice(double DiscountRate)
{
double OrigPrice;
cout << "Please enter the original price: ";
cin >> OrigPrice;
return OrigPrice - (OrigPrice * DiscountRate / 100);
}
int main()
{
double FinalPrice;
double Discount = 15; // That is 25% = 25
FinalPrice = CalculateNetPrice(Discount);
cout << "\nFinal Price = " << FinalPrice << "\n\n";
return 0;
}
Most of the time, a function such as ours 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 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>
using namespace std;
double CalculateNetPrice(double DiscountRate = 25)
{
double OrigPrice;
cout << "Please enter the original price: ";
cin >> OrigPrice;
return OrigPrice - (OrigPrice * DiscountRate / 100);
}
int main()
{
double FinalPrice;
FinalPrice = CalculateNetPrice();
cout << "\nFinal Price = " << FinalPrice << "\n\n";
return 0;
}
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 = followed by the desired value. Here is an example: #include <iostream>
using namespace std;
double CalculateNetPrice(double Tax = 5.75, double Discount = 25,
double OrigPrice = 245.55)
{
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;
}
int main()
{
double FinalPrice;
FinalPrice = CalculateNetPrice();
cout << "Final Price: $" << FinalPrice << "\n\n";
return 0;
}
Here is the result produced: Original Price: $245.55 Discount Rate: 25% Tax Amount: $5.75 Final Price: $184.22 Press any key to continue... If a function receives 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.
|
|
Function Overloading |
|
A C++ program involves a great deal of names that represent variables and functions of various kinds. The compiler does not allow two variables to have the same name in the same function. Although two functions should have unique names in the same program, C++ allows you to use the same name for different functions of the same program following certain rules. The ability to have various functions with the same name in the same program is called function overloading. The most important rule about function overloading is to make sure that each one of these functions has a different number or different type(s) of arguments. |
|
The moment of inertia is the ability of of a beam to resist bending. It is calculated with regard to the cross section of the beam. Because it depends on the type of section of the beam, its calculation also depends on the type of section of the beam. In this exercise, we will review different formulas used to calculate the moment of inertia. Since this exercise is for demonstration purposes, you do not need to be a Science Engineering major to understand it. |
Here is an example that calculates the moment of inertia with regard to the X
axis:
Here are the formulas to calculate the moment of inertia for a semi-circle:
A circle, and thus a semi-circle, requires only a radius. Since the other version of the MomentOfInertia() function requires two arguments, we can overload it by providing only one argument, the radius. Here is an example that calculates the moment of inertia with regard to the X or base axis, overloading the MomentOfInertia() function as follows: |
#include <iostream>
using namespace std;
// Rectangle
double MomentOfInertia(double b, double h)
{
return b * h * h * h / 3;
}
// Semi-Circle
double MomentOfInertia(double R)
{
const double PI = 3.14159;
return R * R * R * R * PI/ 8;
}
int main()
{
double Base, Height, Radius;
cout << "Enter the dimensions of the Rectangle\n";
cout << "Base: "; cin >> Base;
cout << "Height: "; cin >> Height;
cout << "\nMoment of inertia with regard to the X axis: ";
cout << "I = " << MomentOfInertia(Base, Height) << "mm";
cout << "\n\nEnter the radius: "; cin >> Radius;
cout << "Moment of inertia of a semi-circle with regard to the X axis: ";
cout << "I = " << MomentOfInertia(Radius) << "mm\n\n";
return 0;
}
|
Here are the formulas to calculate the moment of inertia of a triangle:
![]() |
|
As you can see, the rectangle and the triangle are using the same dimension types. This means that we can provide only the same kinds of arguments, the base and the height, to calculate the moment of inertia. This also means C++ will not allow us to write two functions that have the same name, the same number of arguments, and the same types of arguments because that would violate the rule of function overloading. In order to overload the MomentOfInertia() function, we will add an argument that will never be used; this argument will serve only as a “witness” to set the difference between both versions of the function. This “witness” argument can be anything: an integer, a character, a string, a float, etc. For our example, we will make it a simple integer. To use the version applied to the triangle, we will provide this argument to overload the
MomentOfInertia() function. When called with only two arguments, the rectangle version will apply. |
#include <iostream>
using namespace std;
// Rectangle
double MomentOfInertia(double b, double h)
{
return b * h * h * h / 3;
}
// Semi-Circle
double MomentOfInertia(double R)
{
const double PI = 3.14159;
return R * R * R * R * PI/ 8;
}
// Triangle
double MomentOfInertia(double b, double h, int)
{
return b * h * h * h / 12;
}
int main()
{
double Base = 7.74, Height = 14.38, Radius = 12.42;
cout << "Rectangle\n"
<< "Moment of inertia with regard to the X axis: ";
cout << "I = " << MomentOfInertia(Base, Height) << "mm\n\n";
cout << "Semi-Circle\n"
<< "Moment of inertia with regard to the X axis: ";
cout << "I = " << MomentOfInertia(Radius) << "mm\n\n";
cout << "Enter the dimensions of the triangle\n";
cout << "Base: "; cin >> Base;
cout << "Height: "; cin >> Height;
cout << "\nTriangle\n" << "Moment of inertia with regard to the X axis: ";
cout << "I = " << MomentOfInertia(Base, Height, 1) << "mm\n\n";
return 0;
}
|
|
Constant Arguments |
|
When a function receives an argument, it performs one of two actions with regards to the value of the argument; it may modify the value itself or only use the argument to modify another argument or another of its own variables. If you know that the function is not supposed to 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 time. 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. For example, if you declare a function like void Area(const string Side), the Area() is not supposed to modify the value of the Side argument. Consider a function that is supposed to calculate and return the perimeter of a rectangle if it receives the length and the width from another function, namely main(). Here is a program that would satisfy the operation (notice the Perimeter() function that takes two arguments): int main()
{
float Length, Width;
cout << "Rectangle dimensions.\n";
cout << "Enter the length: ";
cin >> Length;
cout << "Enter the width: ";
cin >> Width;
cout << "\nThe perimeter of the rectangle is: " << Perimeter(Length, Width);
cout << "\n\n";
return 0;
}
As you can see, the Perimeter() function does not change the values of the length or the width. To make the length and the width arguments constant, you would change the declaration of the Perimeter() function as follows: float Perimeter(const float l, const float w); You can make 0, just one, or more arguments constants, and there is no order on which arguments can be made constant. Here is an example |
#include <iostream>
using namespace std;
// Rectangle
double MomentOfInertia(const double b, const double h)
{
return b * h * h * h / 3;
}
// Semi-Circle
double MomentOfInertia(const double R)
{
const double PI = 3.14159;
return R * R * R * R * PI/ 8;
}
// Triangle
double MomentOfInertia(const double b, const double h, int)
{
return b * h * h * h / 12;
}
int main()
{
double Base = 7.74, Height = 14.38, Radius = 12.42;
cout << "Rectangle\n"
<< "Moment of inertia with regard to the X axis: ";
cout << "I = " << MomentOfInertia(Base, Height) << "mm\n\n";
cout << "Semi-Circle\n"
<< "Moment of inertia with regard to the X axis: ";
cout << "I = " << MomentOfInertia(Radius) << "mm\n\n";
cout << "\nTriangle\n"
<< "Moment of inertia with regard to the X axis: ";
cout << "I = " << MomentOfInertia(Base, Height, 1) << "mm\n\n";
return 0;
}
|
|
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 copy of the variable. Also, when passing an argument as a constant, the compiler will make sure that the value of the passed argument is not modified. At first glance, passing an argument as a constant reference appears contradictory, in view of what we currently know about constants and references. If you pass an argument as reference, the compiler would access the argument at its location. The called function can modify the value of the argument. The advantage is that the 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 previously). 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 CalculateNetPrice(const double& Tax)
{
double Original;
const double Discount = 25;
Original = GetOriginalPrice();
double DiscountValue = Original * Discount / 100;
double TaxValue = Tax / 100;
double NetPrice = Original - DiscountValue + TaxValue;
return NetPrice;
}
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>
using namespace std;
// Passing an argument by reference
void GetOriginalPrice(double& OriginalPrice)
{
cout << "Enter the original price of the item: $";
cin >> OriginalPrice;
}
// Passing an argument as a constant reference
// Passing arguments by value
double CalculateNetPrice(const double& Original, double Tax, double Discount)
{
Discount = Original * Discount / 100;
Tax = Tax / 100;
double NetPrice = Original - Discount + Tax;
return NetPrice;
}
int main()
{
double TaxRate = 5.50; // = 5.50%
const double Discount = 25;
double Price;
double Original;
void Receipt(const double& Orig, const double& Taxation,
const double& Dis, const double& Final);
GetOriginalPrice(Original);
Price = CalculateNetPrice(Original, TaxRate, Discount);
Receipt(Original, TaxRate, Discount, Price);
cout << "\n\n";
return 0;
}
void Receipt(const double& Original, const double& Tax,
const double& Discount, const double& FinalPrice)
{
cout << "\nReceipt";
cout << "\nOriginal Price: $" << Original;
cout << "\nTax Rate: " << Tax << "%";
cout << "\nDiscount Rate: " << Discount << "%";
cout << "\nFinal Price: $" << FinalPrice;
}
|
|
Inline Functions |
|
When you call a function B() from a function A(), function A() sends a request and must get to Function B(). Whenever your program includes a small function, C++ allows you to include such a function where it is being called. When function B() calls function A(), instead of sending a request fo funtion A(), the compiler would include a copy of function A() into funtion B() where it is being called. Such a function (function A()) is qualified inline. To create a function as inline, use the inline keyword when declaring the function as well as when defining it. Here is an example that makes use of an inline function: #include <iostream>
using namespace std;
inline void Area(float Side)
{
cout << "The area of the square is " << Side * Side;
}
int main()
{
float s;
cout << "Enter the side of the square: ";
cin >> s;
Area(s);
cout << "\n\n";
return 0;
}
|
|
Static Variables |
|
Consider the following program: #include <iostream>
using namespace std;
void Starter(int y)
{
double a = 112.50;
double b = 175.25;
a = a / y;
b = b + 2;
cout << "y = " << y << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "b / a = " << b / a << "\n\n";
}
int main()
{
Starter(2);
Starter(2);
Starter(2);
Starter(2);
return 0;
}
When executed, this program would produce: y = 2 a = 56.25 b = 177.25 b / a = 3.15111 y = 2 a = 56.25 b = 177.25 b / a = 3.15111 y = 2 a = 56.25 b = 177.25 b / a = 3.15111 y = 2 a = 56.25 b = 177.25 b / a = 3.15111 Press any key continue.. The Starter() function receives one argument passed when it is called. The called function also receives the same argument every time. Looking at the result, the argument passed to the function and the local variables declared inside of the called function keep the same value every time the function is called. That is, when the Starter() function is exited, the values remain the same. We know that, when a function is defined, any variable declared locally belongs to the function and its influence cannot expand beyond the presence of the function. If you want a locally declared variable to keep its changed value when its host function is exited, declare such a variable as static. To declare a static variable, type the keyword static on the left of the variable’s data type. For example, if you plan to declare a Radius variable as static in an Area() function, you could write: double Area(){ static double Radius;} You should always initialize a static variable before using it; that is, when declaring it. To make the local variables of our Starter() function static, we can declare them as follows: void Starter(int y)
{
static double a = 112.50;
static double b = 175.25;
a = a / y;
b = b + 2;
cout << "y = " << y << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "b / a = " << b / a << "\n\n";
}
This time, when executing the program, it would produce: y = 2 a = 56.25 b = 177.25 b / a = 3.15111 y = 2 a = 28.125 b = 179.25 b / a = 6.37333 y = 2 a = 14.0625 b = 181.25 b / a = 12.8889 y = 2 a = 7.03125 b = 183.25 b / a = 26.0622 Press any key continue... Notice that, this time, each local variable keeps its newly changed value when the function exits. Since a function’s argument can receive different values as the function is called different times, we can test our program by passing different values to its argument as follows: #include <iostream>
using namespace std;
void Starter(int y)
{
static double a = 112.50;
static double b = 175.25;
a = a / y;
b = b + 2;
cout << "y = " << y << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "b / a = " << b / a << "\n\n";
}
int main()
{
Starter(2);
Starter(5);
Starter(14);
Starter(25);
return 0;
}
The current version of the program would produce: y = 2 a = 56.25 b = 177.25 b / a = 3.15111 y = 5 a = 11.25 b = 179.25 b / a = 15.9333 y = 14 a = 0.803571 b = 181.25 b / a = 225.556 y = 25 a = 0.0321429 b = 183.25 b / a = 5701.11 Press any key continue.. |
|
|
||
| Previous | Copyright © 2000-2002 FunctionX | Next |
|
|
||