Home

Introduction to Functions

 

A Function as a Task

 

Introduction

A function is an assignment or a task that must be performed to complement the other part(s) of a 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 Declaration

In order to create and use a 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();

An assignment, considered a function, is made of three parts: its purpose, its needs, and the expectation. Based on this formula, the expectation you have from a function is the ReturnType factor. In later sections, we will review the possible return types available in C++. The simplest return type you can use is called, and represented as, void. Using this keyword, the simplest formula we can use is:

void FunctionName();
 

Function Names

A function name follows the same rules we have applied to our variables so far except that, in our lessons, the name of a function will start in uppercase. 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. Examples of names of functions are Add, Start, Assign, Play, etc.

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.

Function Definition 

 

Introduction

In order to use a function in your program, you have to let the compiler know what the function does. To let the compiler know what the function is meant to do, you have to “define” it; which also means describing its behavior. The formula to define a function is:

void 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.

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, here is an example:

void Message() {};

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;
}

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:

int main()
{
	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;

void Message()
{
	cout << "This is C++ in its truest form.";
}

int main()
{
	Message(); // Calling the Message() function

	return 0;
}

Calling a Function Before Defining it

The example we saw above requires that you define a function before calling it. C/C++, like many languages, allows you to call a function before defining it. Unlike many languages, in C++, when calling a function, the compiler must be aware of the function. This means that, you must at least declare a function before calling it. After calling the function, you can then define it as you see fit. Here is an example:

#include <iostream>
using namespace std;

int main()
{
	void Message();

	cout << "We will start with the student registration process.";
	Message(); // Calling the Message() function

	return 0;
}

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 <cstdio>
using namespace std;

int main()
{
	cout << "This is C++ in its truest form...\n\n";

	getchar();
	return 0;
}

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.

The Type of 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();

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();
char FunctionName();
bool FunctionName();
string FunctionName();

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;
}

int main()
{
	int Major;	

	cout << "Welcome to the student orientation program.";
	cout << "Select your desired major:";

	Major = GetMajor();

	cout << "You select " << Major; cout << "\n";
	return 0;
}

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;

int 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;
}
 
 

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);
char Answer();
void Message(float Distance);
bool InTheBox(char Mine);
string StudentName();
double RectangleArea(double Length, double Width);
void DefaultBehavior(int Key, double Area, char MI, float Ter);
 

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

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
Tax Amount = Item Price * 
100

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

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
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);

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);

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.

  • If a function takes two arguments, you can declare it with default values. 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 (because the second already has a (default) value):

    #include <iostream>
    using namespace std;
    
    double CalculateNetPrice(double tax, double discount = 25)
    {
    	double origPrice;	
    
    	cout << "Enter the original price of the item: ";
    	cin >> origPrice;
    
    	double discountValue = origPrice * discount / 100;
    	double taxValue = tax / 100;
    	double netPrice = origPrice - discountValue + taxValue;
    
    	return NetPrice;
    }
    
    int main()
    {
    	double taxRate = 5.50; // = 5.50%
    	double finalPrice;
    
    	finalPrice = CalculateNetPrice(taxRate);
    
    	cout << "\nFinal Price = " << finalPrice << "\n\n";	
    
    	return 0;
    }

    Here is an example of running the program:

    Enter the original price of the item: 245.55Final Price = 184.218Press 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.

  • 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 (right side) 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.
 

Techniques of Using Functions

 

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.


 
The Moment Of Inertia

Here is an example that calculates the moment of inertia with regard to the X axis:

#include <iostream>
using namespace std;

// Rectangle
double MomentOfInertia(double b, double h)
{
	return b * h * h * h / 3;
}

int main()
{
	double Base, Height;

	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" << "\n\n";

	return 0;

}

Here are the formulas to calculate the moment of inertia for a semi-circle:
The Moment of Inertia for a 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.
Here is an example that calculates the moment of inertia with regard to the X 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;
}

// 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;
}
 

Inline Functions

When you call a function B() from function A(), function A() sends a request and must get to Function B(). This is sometimes cumbersome for long functions. 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 to function A(), the compiler would include a copy of function A() into function 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);  

    return 0;
}

Here is an example of running the program:

Enter the side of the square: 14.55
The area of the square is 211.702

You can also use the keyword on an inline function. To declare a function as inline and, type both words at the beginning of the declaration. The following program requests the hourly salary from the user. Then it calculates the periodic earnings: 

#include <iostream>
using namespace std;

void inline RequestSalary(double& h);
inline double Daily(double h);
double inline Weekly(double h);
inline double BiWeekly(double h);
double inline Monthly(double h);
double inline Yearly(double h);

int main()
{
    double HourlySalary;

    cout << "This program allows you to evaluate your salary "
           << "for different periods\n";

    RequestSalary(HourlySalary);

    cout << "\nBased on the hourly rate you supplied, here are your "
           << "periodic earnings";
    cout << "\n\tHourly:    $" << HourlySalary;
    cout << "\n\tDaily:     $" << Daily(HourlySalary);
    cout << "\n\tWeekly:    $" << Weekly(HourlySalary);
    cout << "\n\tBi-Weekly: $" << BiWeekly(HourlySalary);
    cout << "\n\tMonthly:   $" << Monthly(HourlySalary);
    cout << "\n\tYearly:    $" << Yearly(HourlySalary);

    cout << "\n\n";  
    return 0;
}

void inline RequestSalary(double& x)
{
    cout << "Enter your hourly salary: $";
    cin >> x;
}

inline double Daily(double x)
{
    return x * 8;
}

double inline Weekly(double x)
{
    return Daily(x) * 5;
}

inline double BiWeekly(double x)
{
    return Weekly(x) * 2;
}

double inline Monthly(double x)
{
    return Weekly(x) * 4;
}

double inline Yearly(double h)
{
    return Monthly(h) *  12;
}

Here is an example of running the program:

This program allows you to evaluate your salary for different periods
Enter your hourly salary: $15.55

Based on the hourly rate you supplied, here are your periodic earnings
        Hourly:    $15.55
        Daily:     $124.4
        Weekly:    $622
        Bi-Weekly: $1244
        Monthly:   $2488
        Yearly:    $29856

Previous Copyright © 2000-2009 FunctionX, Inc. Next