You are on page 1of 712

Created By www.ebooktutorials.blogspot.

in
Introduction to C++ Variable and Data Types Namespaces Operators and Operands Introduction to Functions Exploring Functions C++ Projects and Linkage Logical Comparisons Conditional Statements Constructing Expressions

Intermediate Operations Introduction to Arrays Introduction to Pointers Arrays and Pointers Pointers and Functions Strings Data Input/Output Exception Handling

User-Defined Types Introduction to Classes Object Initialization and Tuning Object Construction and Destruction Arrays and Pointers of Classes Operator Overloading Combining Objects Exceptions and Classes Composition and Inheritance Polymorphism and Abstraction

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Introduction to C++
Introduction to Computers
Overview
A computer is a machine that receives instructions and produces a result after performing an appropriate assignment. Since it is a machine, it expects good and precise directives in order to do something. The end result depends on various factors ranging from the particular capabilities of the machine, the instructions it received, and the expected result. As a machine, the computer cannot figure out what you want. The computer doesn't think and therefore doesn't make mistakes. Computer programming is the art of writing instructions (programs) that ask the computer to do something and give a result. A computer receives instructions in many different forms, four of which are particularly important. The first instructions are given by the manufacturers of various hardware parts such as the microprocessor, the motherboard, the floppy and the CD-ROM drives, etc. These parts are usually made by different companies, setting different and various goals that their particular part can perform. The instructions given to the microprocessor, for example, tell it how to perform calculations, at what speed, and under which circumstances. The instructions given to the motherboard tell it to behave like a city where people and cars can move from one part of the town to another, back and forth, for various reasons; this allows information to flow from one part of the city, I mean one section of the computer, to another. Once the instructions given to the hardware parts are known, software engineers use that information to give the second sets of instructions to the computer. These instructions, known as an operating system, are usually written by one company. These second instructions tell the computer how to coordinate its different components so the result will be a combination of different effects. This time, the computer is instructed about where the pieces of information it receives are coming from, what to do with them, then where to send the result. This time also the operating system designers impose a lot of behaviors to the computer as a machine. Again this time, some computer languages are developed so that programmers can write applications as the third set of instructions. It is like developing languages that people in a city can use to talk to each other. Consider that from now on (once the OS is developed), people get into the habit of doing things according to their particular culture or taste, speaking different languages that their neighbor doesn't understand... Luckily, the computer, I should say the OS, understands all these languages (I can't guaranty that). Some of the operating systems on the market are: Microsoft Windows 3.X, Corel Linux, IBM OS\2, Microsoft Windows 9X, Apple OS 10, Red Hat Linux, Microsoft Windows Millennium, BeOS, Caldera Linux, Microsoft Windows 2000 etc. A particular OS (for example Microsoft Windows 98) depending on a particular processor (for example Intel Pentium) is sometimes referred to as a platform. Some of the computer languages running on Microsoft Windows operating systems are C++, Pascal, Basic, and their variants.

The actual third set of instructions are given to the computer by you, the programmer, using one or more of the languages that the operating system you are planning to use can understand. Your job is going to consist of writing applications. As a programmer, you write statements such as telling the computer, actually the operating system, that "If the user clicks this, do the following, but if he clicks that, do something else. If the user right clicks, display this; if he double-clicks that, do that." To write these instructions, called programs, you first learn to "speak" one of the languages of the OS. Then, you become more

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
creative... Some of the application programs in the market are Microsoft Word, Lotus ScreenCam, Adobe Acrobat, Jasc Paint Shop Pro, etc.
The last instructions are given by whoever uses your program, or your application. For example, if you had programmed Microsoft Word, you would have told the computer that "If a user clicks the New button on the Standard toolbar, I want you to display a new empty document. But if the user clicks File -> New..., I want you to 'call' the New dialog and provide more options to create a new document. If the same user right-clicks on any button on any of the toolbars, I want you to show, from a popup menu, all the toolbars available so she can choose which one she wants. But if she rightclicks on the main document, here is another menu I want you to display." At this time, you have probably realized that the users of your programs depend on your techniques as a developer to provide an easy to use application (that's what recruiters and employers call experience and creativity). You depend on the computer language that you are actually using (every computer language has its ups and downs). Your computer language depends on the operating system it is running on (different

operating systems have different strengths and weaknesses). The operating system depends on the microprocessor or the machine it is running in (the biggest difference between two microprocessors is the speeds at which each processes information). Your interest here is on the computer languages, since you are going to write programs. There are various computer languages, for different reasons, capable of doing different things. Fortunately, the computer can distinguish between different languages and perform accordingly. These instructions are given by the programmer who is using compilers, interpreters, etc, to write programs. Examples of those languages are Basic, C++, Pascal, etc.

Introduction to Header Files


C++ is a huge language so much that it uses various sets of instructions from different parts to do its work. Some of these instructions come in computer files that you simply "put" in your program. These instructions or files are also called libraries. To make your job easier, some of these libraries have already been written for you so that as you include them in your program, you already have a good foundation to continue your construction. Yet, some of these libraries have their limitations, which means you will expand them by writing or including your own libraries. As noted already, there are libraries previously written for you. One of them asks the computer to receive keyboard strokes from you the user (when you press a key) and another asks the machine (the computer performing some operations) to give back a result. The libraries are files that you place at the beginning of your program as if you were telling the computer to receive its preliminary instructions from another program before expanding on yours. The libraries are (also) called header files and, as computer files, they have the extension ".h". An example would be house.h, or person.h. As you see, they could have any name; when you start creating your own libraries, you will give your files custom and recognizable names. The first library we will be interested in is called iostream. It asks the computer to display stuff on the monitor's screen. To see how to put a library in your program, you put it at the beginning of the file. Here is an example: iostream.h To use a library in your program, you simply include it by using the word "include" before the name of the library, as follows: include iostream.h Since this is a computer language, the computer will follow particular instructions to perform appropriately, which will make this language distinct from the everyday languages. C++ has some words it treats specially and some that will completely depend on you the programmer. For example, the word "include" could be a special word used by C++ or a regular you want to use in your program. In this particular situation, if you want the computer to "know" that the word "include" means, "I want to include the following library", you will have to append a special sign to it. The pound sign "#" will do just that. Therefore, to include a library, you precede the include word with the # sign.

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Here is an example: #include iostream.h There are usually two kinds of libraries or files you will use in your programs: libraries that came with C++, and those that you write. To include your own library, you would enclose it between double quotes, like this #include "books.h" When you include a library that came with C++, you enclose it between < and > as follows: #include <iostream.h> Following this same technique, you can add as many libraries as you see fit. Before adding a file, you will need to know what that file is and why you need it. This will mostly depend on your application. For example, you can include a library called stdio like this: #include <iostream.h> #include <stdio.h>

Introduction to Namespaces
A namespace is a section of code, delimited and referred to using a specific name. A namespace is created to set apart a portion of code with the goal to reduce, otherwise eliminate, confusion. This is done by giving a common name to that portion of code so that, when referring to it, only entities that are part of that section would be referred to. Because C++ is so huge, its libraries are created in different namespaces, each with a particular name. To use an existing namespace in your program, you must know its name. To use such a namespace, you can type the using namespace expression followed by the name of the namespace and a semi-colon. For example, to use a namespace called django, you would type: using namespace django; One of the namespaces used in C++ is called std. Therefore, to use it, you can type: using namespace std; After typing this, any part of the namespace becomes available to you. The iostream library we mentioned above is part of the std namespace. When you use it, you don't need to include the extended of the iostream file. For this reason, you can start your program with: #include <iostream> using namespace std;

C++ Projects
C++ Instructions
C++ works by giving (separate) instructions to the computer. These instructions can be treated as assignments. On this site, such an assignment will be called a function. The primary function used in C++ is called main. To distinguish a function from the other types of things you will be using in your programs, a function's name is followed by an opening and a closing parentheses. For example, the main function will always be written at least as main(). When we perform a better study of functions, we will learn more about functions, their parentheses, and other related issues. When a program is written and you ask the computer to "execute" it, the first thing to look for is the main() function. This means that every C++ program should have the main() function. Because a function is an assignment, in order to perform its job, a function has a body; this is where the behavior (assignment) of the function would be "described". The body of a function starts with an opening curly bracket "{" and closes with a closing curly bracket "}". Everything in between belongs to, or is part of, the function. Therefore, the main() function can be written as: main() {} As we learned that we should (must) always include the libraries that we would need, our

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
program now would include main(). Whenever you create a program, it is important to isolate any inclusion of a library on its own line. Here is an example: #include <iostream> using namespace std; main(){} C++ is the computer language we are going to study to write programs. C++ is a very universal language, it can be used to write programs for Linux, MS Windows, Macintosh, BeOS, Unix, etc. C++ is very powerful and can be used to create other compilers or languages, it can also be used to write an operating system. This means that you can use C++ to create/write your own computer language. You can also use C++ to create/write your own compiler; this means that, using C++, you can create your own implementation of C++, Pascal, Basic, Perl, or any other existing or non-existing language. There are many products you can use to create a program in C++. Before a program is made available, it is called a project because you are working on it. Although in the beginning you will usually be working alone, most programs involve a lot of people. That is why during the development of a program or software product, it is called a project. Each one of the available environments provides its own technique(s) of creating a C++ program or working on a C++ project. Therefore, the person who, or the company that, made the environment available to you must tell you how to use that environment (it is neither your responsibility, nor the C++ Standards job to tell you how to create a program or how to start a project). I will try to cover those that I know. The programs we will be creating on this site are called console applications. They can also be called Bash programs (especially on Unix/Linux). The technique you follow to create a project depends on the environment you are using.

Executing a Program
To see what your program does, you need to realize that the lines we have typed are English language instructions asking C++ to perform the main() function. Unfortunately, the computer doesn't understand what all of this means (to a certain extent). The computer has its own language known as the machine language. So, we need to translate it in a language the computer can understand. A program was created to that effect and supplied to you with C++. This is what we call a compiler. In the past, a program used to be created from various parts all over the computer, some of the techniques are still used to "debug" a program to isolate problems or "bugs". Since this is a small program, we will just ask the computer to "execute" it and see the result. Throughout this site, the words (or verbs) "execute" and "run" will be used interchangeably to mean the same thing. The C++ language doesn't define how to create a project. When you buy or acquire a c++ compiler, its documentation should tell you how to create and execute a project. We describe here how how to create a project in most familiar environments. If you have an environment or compiler that is not in our list, consult its documentation to know how to use it.

One of our most valuable goals in writing a site is to avoid including in a program an issue that has not previously been addressed or explained. This site is written as a (general) reference towards the C++ language. To learn C++, you need a C++ compiler, and we describe how to create a C++ project with some of the most commonly used compilers or programming environments. As it happens, and as you may have noticed, different companies (and different individuals for that matter) choose to implement a language as they see fit.
Depending on the programming environment you are using, even depending on how you create your program (for example KDevelop, Borland C++ Builder, and Microsoft Visual C++ all provide more than one way to create or start a console application), sometimes you have a starting empty file or a file with a few lines. Whatever is in the file, you do not need to delete it. For example, KDevelop displays a commented message in the file. You should not delete that text and it will never interfere with your program. Borland C++ Builder opens a file with a couple of "#pragma" lines. You will never have any reason to delete those lines, although you can, without any risk; but since they do not affect your program, why waste your time deleting them? Depending on the programming environment you are using and how you create your program, the first file may display a line as #include <iostream.h> or another #include line. The file may also have a main() function already included. Here is how we will deal with this issue:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
If the file displays a line with #include Something, leave it as is. It will not negatively affect your program. Such a file has been tested If the file displays a line with #include <iostream.h>, leave it like that and continue with our other instructions If the file is empty or it does not include a line with #include at all, then you will just follow our instructions and type them as given If the file already includes the main() function, with a line like int main(Something), use that main() function for the exercises in this book. Unless stated otherwise, that function is ready for you and don't modify the Something part between the parentheses.
From now on, you will sometimes be asked to create a project. Follow the instructions of your compiler as we have seen above.

Project Creation
Creating and Executing a Dev-C++ 4 Application
Dev-C++ is a free programming environment. To get it, you can download it from http://www.bloodshed.net. If you decide to use it, you should help the developers with a financial contribution. 1. Start Dev-C++ 4

2. On the main menu, click File -> New Project... 3. On the New Project dialog box, click the Project property sheet if necessary. Click Console Application

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

4. Click OK. 5. On the subsequent New Project dialog box, type Exercise to change the name of the project:

6. Click OK. You will be asked to create a location for the project. 7. Click the Create New Folder button 8. Type Exercise1 and press Enter. 9. Double-click Exercise1 to display it in the Save In combo box: .

10. Click Save. 11. Because the project has already been saved, it is better to save your C++ files as you go. As it happens, Dev-C++ has already created the first C++ file for you. Change the contents of the file as follows: #include <iostream.h> #include <stdio.h> int main(int argc, char *argv[]) { cout << "C++ is Fun!!!"; getchar(); return 0; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

12. To save the current C++ file, on the Main toolbar, click the Save button 13. Type Exo as the name of the file. 14. Click Save. 15. To execute the program, on the main menu, click Execute -> Compile

16. After the program has been compiled, click Execute. 17. After viewing the program, press Enter to close the DOS window to return to Dev-C++

Borland C++BuilderX
Borland C++BuilderX is a commercial programming environment developed by Borland. To help programmers, Borland published a free version, called Personal Edition, that you can download and use for your lessons. 1. On the main menu of C++BuilderX, click File -> New... 2. In the Object Gallery dialog box, click New Console

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

3. Click OK 4. In the New Console Application - Step 1 of 3, enter the name of the new application in the Name edit box. In this case, you can type Exercise1

5. Click Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

6. In the New Console Application Wizard - Step 2 of 3, accept all defaults and click Next 7. In the New Console Application Wizard - Step 3 of 3, click the check box under Create 8. Click Untitled1 and delete it to replace it with Exercise

9. Click Finish 10. In the Project Content frame, double-click Exercise.cpp to display it in the right frame

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

11. To execute the application, on the main menu, click Run -> Run Project

Borland C++ Builder (Console) Applications


Borland C++ Builder is a commercial programming environment developed by Borland. To get, you usually must purchase it. 1. To create a console application in Borland C++ Builder, from the main menu, click File -> New (or File -> new -> Other):

2. From the New Items dialog box. click the Console Wizard button and click OK. 3. From the Console Wizard dialog box, click the C++ radio button and the Console Application check box (the other options are up to you but we will not use them in this tutorial):

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

4. Click OK. A skeleton program is created for you. For this lesson, I would ask you to delete everything that appears in the Code Editor and type the two lines above, but leave it there. I will not address what all those words mean at this time and we don't even need them and don't care. 5. Change the program as follows: //-------------------------------------------------------------------------#include <iostream. #include <conio> using namespace std; #pragma hdrstop //-------------------------------------------------------------------------#pragma argsused int main(int argc, char* argv[]) { cout << "\nPress any key to continue..."; getch(); return 0; } //-------------------------------------------------------------------------6. To execute the program, on the main menu, click Run -> Run 7. After viewing the result, press Enter to close the DOS window and return to Borland C++ Builder.

Linux C++ (Terminal) Applications


Most, or all, Linux distributions provide various free C++ compilers. The following instructions are from Red Hat Linux 7.2. 1. To create a C++ application, open the Home Directory (it should have a shortcut on the top left corner of the desktop; otherwise, from the Taskbar, click Start -> KDE menus -> Home Directory) 2. The title bar and the address combo box should display your username. For this exercise, I am logged with the root username. Therefore, my title bar and the address combo box display file:/root With your username selected, right-click in the right frame and click Create New -> Directory...

3. Type Exercise1 and click OK 4. On the right frame, make sure the Exercise1 directory is created (because I will refer to it). 5. Start a text editor. I use gedit, which is available at Start -> Programs -> Applications -> gedit

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
6. In the text editor, type the following: #include <iostream.h> int main() { cout << C++ is fun!!!\n; return 0; }

7. Save your file. If you are using gedit like me, on the main menu, click File -> Save As... 8. Under the Directory header in the left list, double-click the Up One Level button ../ If you see your user name in the left list, fine. Otherwise, double-click ../ again. 9. On the left list, double-click your user name (for me that would be root/) to open you personal directory 10. On the left list, double-click the Exercise1/ directory we created. 11. In the Selection: text box, type the name of the file as Exo.cpp and click OK 12. To execute the program, open the Terminal: Start -> System -> Terminal. In the Terminal window, you should see [UserName@localhost Username]$ For example, mine is [root@localhost root]$ 13. This ensures that you are in your personal directory. To change to the directory that hosts your exercise, type cd Exercise1 Now the new folder should be inside the square brackets. Mine is [Username@localhost Exercise1]$ 14. To compile the program, we will use the free g++ compiler. Therefore, type: g++ Exo.cpp 15. For example, on mine, I type [jezoo@localhost Exercise1]$ g++ Exo.cpp 16. You may receive one warning. For now, don't worry. 17. To execute the program, type ./a.out and press Enter 18. This is because the executable file, named a with the extension .out has been created one folder up from the actual location of the C++ file. For example, on mine, I type [root@localhost Exercise1]$ ./a.out

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

19. To check the a.out file that was created when compiling, return to the Home Directory window and navigate to the /home/UserName/Exercise1/Exo

KDevelop C++ Projects


KDevelop is a free programming environment available for the Linux operating system. In some cases, when installing the operating system, you may be prompted whether you want to install KDevelop. Even after the installation, you can add it. If you didn't install it or don't have it on CD or DVD, you can download it free from http://www.kdevelop.org. 1. To create program in KDevelop, start KDevelop by clicking Start -> Development >KDevelop

2. On the main menu, of KDevelop, click Project -> New... 3. From the ApplicationWizard dialog box, in the list or projects, under the Terminal section, click C++ and click Next.

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

4. In the Project Name edit box, type the name of the project. In this case, type Exercise2 and leave the other edit boxes "as is"; in other words, whatever they contain is fine

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

5. Uncheck all of the check boxes (make them empty). This is just an option. If you leave them checked, the compiler would generate (a lot of) code for you and I will not have had time to explain those things to you. 6. Click Next 7. Make sure the VCS Support is set to NONE and click Next. 8. Uncheck the headertemplate for .h-files check box (make it empty). Once again, we don't want the compiler to generate code that we haven't learned yet. 9. Click Next. 10. Uncheck the headertemplate for .cpp-files check box. 11. Click Next. 12. Notice the empty window: KDevelop is ready to create the project. 13. Click Create. 14. KDevelop will need a few seconds to create the project. When it has finished, its last line should be READY

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

15. Therefore, click Exit. 16. To create a (source) file, on the main menu, click File -> New... 17. From the New File dialog box, click C/C++ File (*.cpp,*.c,*.cc,*.C ...) 18. Type Main for the name of the file. Therefore, the Filename edit box should display Main.cpp (you can name the file anything you like, such as Exo or Exercise). 19. Make sure the Add to Project check box is checked and click OK. 20. Leave the grayed section on top of the file (it is just a set of comments that you don't need to delete; they will not affect your program). 21. In the empty section of the file, type: #include <iostream> using namespace std; int main() { cout << C++ is fun!!!\n; return 0; }

22. To execute the program, on the main menu, click Build -> Execute 23. After viewing the program, press Enter to close the bash window

Microsoft Visual C++ (5, 6) Console Applications


Visual C++ is a commercial programming environment developed by Microsoft. You must purchase it if you want to use it (normally, because there is a new version of Visual C++, you may not find Visual C++ 6 anymore from Microsoft). 1. Start Microsoft Visual C++. 2. On the main menu of Microsoft Visual C++ or Microsoft Visual Studio, click File -> New...

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
3. Click the Projects property sheet. 4. Click Win32 Console Application. 5. In the Location box, type a drive followed by a folder name. For example, type C:\Programs\MSVC 6. In the Project Name, type Exercise1

7. Click OK. 8. In the Win32 Console Application Step 1 of 1, click the An Empty Project radio button

9. Click Finish. 10. You will be presented with another dialog box. Click OK. 11. To create a C++ file, on the main menu, click File -> New... 12. In the New dialog box, make sure the Files property sheet is selected. 13. Click C++ Source File 14. In the File Name, type a name such as Exercise and click OK

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
15. From what we have learned so far, change the contents of the file as follows: #include <iostream> using namespace std; int main() { cout << "C++ is fun!!!\n"; return 0; } 16. To execute the program, on the main menu, click Build -> Execute Exercise1.exe 17. When asked to save the project, click Yes 18. After viewing the result, press Enter to close the DOS window and return to MSVC.

Microsoft Visual C++ .NET Console Applications


Visual C++ .NET is a commercial programming environment developed by Microsoft. It is usually shipped with Microsoft Visual Studio .NET but in some cases, you can purchase it alone. In fact, there is a version made for students and sold at a low price. 1. Start Microsoft Visual Studio .NET. 2. On the main menu of Microsoft Development Environment, click File -> New -> Project... 3. On the New Project dialog box, in the Location box (bottom of the dialog box), type a drive followed by a folder name such as C:\Programs\MSVC .Net 4. In the Project Type, click Visual C++ Projects 5. In the Templates list view, click Win32 Project 6. In the Name box, type Exercise1

7. Click OK. 8. In the Win32 Application Wizard - Exercise1 dialog box, click Application Settings 9. In the Application Type section, click the Console Application radio button 10. In the Additional Options section, click the Empty Project check box

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

11. Click Finish. 12. To create a new C++ file, on the main menu, click Project -> Add New Item... Or, on the Solution Explorer, right-click Exercise1 -> Add and click Add New Item... 13. In the Categories list, make sure Visual C++ or C++ is selected. 14. In the Templates list view, click C++ File (.cpp) 15. In the Name box, replace the contents with Exercise 16. Click Open 17. From what we know about C++ already, change the contents of the file with: #include <iostream> using namespace std; int main() { cout << "C++ is fun!!!\n"; return 0; } 18. To execute the program, on the main menu, click Build -> Execute Exercise1.exe 19. When asked to save the project, click Yes 20. After viewing the result, press Enter to close the DOS window and return to MSVC.

Code Fundamentals
Using cout
There are various ways data get in your program. The first means of entering data in a C++ program is by typing it from the keyboard. Another way would be to instruct the program to receive data from another program then process it. A program can also receive its data or part of it from other hardware devices such as a CD-ROM, a DVD-ROM, a modem, a video camera, etc. To display stuff on the monitor, C++ uses operators. The operator used to display something on the screen is called cout (pronounce see - out) (actually, cout is a class and not an operator, but we haven't learned what a class is). The cout word is followed by the extraction operator <<, then some simple rules to display anything. For example, to display a word or sentence, you include it in double quotes " and ". While you are giving these instructions, you type them in your program. Each C++ instruction

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
is terminated by a semi-colon ";". We have already seen that a program is a set of instructions you give to the computer. These instructions are given inside of functions. This means that an instruction is part of a function. The thing we want to display in our program will be performed by the main() function. In other words, the instruction to display something will be given in main(). Here is an example: #include <iostream> using namespace std; int main() { cout << "Computer Programming With C++"; return 0; }

Comments
The most basic documentation you will (have to) perform is to put comments as much as you can. Comments help you and other people who read your code to figure out what you were doing. Comments are not read by the compiler while executing your program. That means you write them in everyday conversation. There are two usual ways of including comments in your program. To comment the contents of one line, you start it with double forward slashes like this // Here is an example: // include the first library #include <iostream> using namespace std; int main() { // Here is a simple sentence cout << "Hi, this is my program!"; return 0; } // The end of my program You can include many lines of comments in your program. To do that, comment each line with the double slashes. An alternative is to start the beginning of the commented paragraph with /* and end the commented section with */ Here is another commented version of our program: // The exo.cpp program // Include the ostream library #include <iostream> using namespace std; int main() { /* Here is a simple sentence that I want to display when the program starts. It doesn't do much. I am planning to do more stuff in the future. */ cout << "Hi, this is my program!"; return 0; } // The end of my program

Home

Copyright 2000-2008 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Variables and Data Types


Variables
Introduction
Your programs will mainly allow the user of your application to interact with the computer. During this interaction, the user will deal with two categories of information: information that is already in the computer and information supplied by the user. Information that is already in the computer will come from various sources; some of that is from the pieces of hardware that compose the users machine, some of that is from the computer (the operating system and other applications that are running on the same computer), and some will have been created by you as part of your application. When interacting with the computer, the user will enter information mainly using the keyboard and/or the mouse. Regardless of what information the user is using, the things used or needed by your program are stored or will be stored in the computer. To process the information of your program or the requests that your program presents to the user, the computer uses two types of storage spaces. The hard drive is a static storage area that keeps its information all the time, almost regardless of what happens to your computer. Another type of storage used by the computer is referred to as Random Access Memory (RAM). This storage area keeps its information only when the computer is turned on. This means that the RAM looses its Information when the computer is turned off. Strictly stated, when the user opens or launches a program, part of the program goes into the RAM. If or when the application is not used anymore, which means that if the user closes the application, the part of memory that the application was using in the RAM is gone and the memory space that the application was using becomes available (we always hope things go that smooth). As an application developer, you will decide what types of information are necessary for your application and how these things would be used. When creating an application, you will provide these pieces of information to the computer, the computer then puts them together. When your program opens, part of your application gets loaded into the RAM. When the user is using your application, the information that your application requests also goes into the RAM while your application is processing such requests. Because your program will be made of many of these things, the computer needs to know what these things would be, and how much space each one of them would need. Because such a thing can change (vary) throughout your program, it is called a variable. Before using such a variable, you must first let the compiler know. Letting the compiler know about a variable is referred to Declaring the variable. The compiler will need two pieces of information concerning each variable: the amount of space the variable will need, and a name to recognize that variable. Therefore, the formula of declaring a variable is: SpaceOccupied VariableName;

C++ Names
When using the various necessary variables in your programs, you will need to identify each one of them. A variable is primarily recognized by its name. C++ provides rules for naming items in your program. The name of a variable: Starts with an underscore _ or a letter, lowercase or uppercase, such as a letter from a to z or from A to Z. Examples are Name, gender, _Students, pRice Can include letters, underscore, or digits. Examples are: keyboard, Master, Junction, Player1, total_grade, _Score_Side1 Cannot include special characters such as !, %, ], or $ Cannot include an empty space Cannot be any of the reserved words

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Should not be longer than 32 characters (although allowed) A name can consist of one word such as country. A name could also be a combination of more than one word, such as firstname or dateofbirth. The C++ compiler has a list of words reserved for its own use and you must not use any of these words to name your own objects or functions. The reserved words are: C++ Reserved Words auto bad_cast bad_typeid case catch char const_cast continue default double dynamic_cast else explicit extern false for friend goto int long mutable operator private protected reinterpret_cast return short static static_cast unsigned template this throw typedef typeid type_info unsigned using virtual wchar_t while

asm break const do except float inline new register sizeof switch try union volatile

bool class delete enum finally if namespace public signed struct true typename void

Most compilers also have their own list of reserved words. Because this depends on the compiler, we cannot review all of them. Avoid starting the name of a variable with two underscores such as __finally or __stdcall. C++ is case-sensitive; this means that CASE, Case, case, and CaSe are four completely different words. To make your programming experience easier and personal, you can add your own rules to those above. Some (most) companies also adopt a naming convention throughout their documentation. Throughout this site: A name of a variable will start in lowercase. In some situations, a name will start with an underscore, when needed. Examples are country, printer, _number If a name is made of a combination of words, after the first word that starts in lowercase, the first letter of each subsequent word will start in uppercase. Examples are firstName, dateOfBirth

Variables and Their Data Types


The amount of memory space necessary to store a variable is also referred to as a data type. A data type provides two valuable pieces of information to the compiler: what amount of space the variable will use, what kind of information will be allowed in that space. After declaring a variable, the compiler reserves a space in memory for that variable:

A variable, any variable, occupies more that one small cell of space in memory. It will always be your responsibility to decide how much space a variable needs, based on your goal.

C You In
Besides the cout extractor, C++ is equipped with another operator used to request values from the user. The user usually provides such a value by typing it using the keyboard. The cin (pronounce see in) operator is used for that purpose; it displays a blinking cursor on the monitor to let the user know that a value is expected. Unlike the cout operator, the cin uses two greater than signs >> followed by the name of the expected value. The syntax of the cin operator is:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cin >> valueName; If you are requesting many values from the user, you can write a statement that would act accordingly by separating values with as many >> operators as necessary. For example, to request a first name, last name, and an age on the same line, you could use: cin >> firstName >> lastName >> Age;

The Numeric Systems


Introduction
When you decide to use the computer, if it is off, the first thing you do is to turn it on. As the computer is coming up ( it is booting), you can hear a noise (but many computers now are (very) quiet). It sounds like things are happening inside; things you usually don't care about. In essence, when that noise stops, if everything went fine, the computer loads what is called an operating system. Although the computer is up and you can see some pictures on the screen, no program other than the operating system (and some things we are not concerned about, called utilities) is available: you have to tell the computer, I want to use program A. After clicking a program of your choice, once again you would hear a noise. Depending on the called program, some applications take longer to come up than others. When you call a program, there is an initial setup that the program has to go through to be ready. Such a program uses numbers, characters, meaningful words, pictures, graphics, etc, that are part of the program. As these things are numerous, so is the size of the program, and so is the length of time needed to come up. Your job as a programmer is to create such programs and make them available to the computer, then to people who use the computer. To write your programs, you will be using alphabetic characters that are a, b, c, d, e, f, g, h, I, j, k, l, m, n, o, p, q, r, s, t, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z. You will also use numeric symbols 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. Additionally, you will use symbols that are not easily readable but are part of the common language; they are ` ~ ! @ # $ % ^ & * ( ) _ + - = : < > ; , . /. Some of these symbols are used in the C++ language while some others are not. When creating your programs, you will be combining letters and/or symbols to create English words or language instructions.
Some of the instructions you will give to the computer could consist of counting the number of oranges, converting water to soup, or making sure that a date occurs after January 15. After you have typed an instruction, the compiler would translate it to

machine language. Why not send your instructions directly to the computer? This is because the computer does not understand the language you and I speak or write. The computer represents any of your instructions as a group of numbers. Even if you ask the computer to use an orange, it would translate it into a set of numbers. As you give more instructions or create more words, the computer stores them in the computer memory using a certain amount of space for each instruction or each item you use. How much space is necessary? How does the compiler figure out that space? There are three numbering systems that will be involved in your programs, with or without your intervention. The numeric system provides the counting techniques that you use everyday. The hexadecimal system is an intermediary system that allows you to know how the computer deals with numbers. The binary system is the actual system that the computer uses to find out (almost) everything in your program.

The Binary System


When dealing with assignments, the computer considers a piece of information to be true or to be false. To evaluate such a piece, it uses two symbols: 0 and 1. When a piece of information is true, the computer gives it a value of 1; otherwise, its value is 0. Therefore, the system that the computer recognizes and uses is made of two symbols: 0 and 1. As the information in your computer is greater than a simple piece, the computer combines 0s and 1s to produce all sorts of numbers. Examples of such numbers are 1, 100, 1011, or 1101111011. Therefore, because this technique uses only two symbols, it is called the binary system. When reading a binary number such as 1101, you should not pronounce "One Thousand One Hundred And 1", because such a reading is not accurate. Instead, you should pronounce 1 as One and 0 as zero or o. 1101 should be pronounced One One Zero One, or One One o One.

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
The sequence of the symbols of the binary system depends on the number that needs to be represented. Why learn the binary system? You need to know what the binary system looks like because you will be writing instructions to the computer, and the computer does not understand English.

The Decimal System


The numeric system that we have always used uses a set of ten symbols that are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. Each of these symbols is called a digit. Using a combination of these digits, you can display numeric values of any kind, such as 240, 3826 or 234523. This system of representing numeric values is called the decimal system because it is based on 10 digits. When a number starts with 0, a calculator or a computer ignores the 0. Consequently, 0248 is the same as 248; 030426 is the same as 30426. From now on, we will represent a numeric value in the decimal system without starting with 0: this will reduce, if not eliminate, any confusion. Decimal Values: 3849, 279, 917293, 39473 Non- Decimal Values: 0237, 0276382, k2783, R3273 The decimal system is said to use a base 10. This allows you to recognize and be able to read any number. The system works in increments of 0, 10, 100, 1000, 10000, and up. In the decimal system, 0 is 0*10 0 (= 0*1, which is 0); 1 is 1*10 0 (=1*1, which is 1); 2 is 2*10 0 (=2*1, which is 2), and 9 is 9*10 0 (= 9*1, which is 9). Between 10 and 99, a number is represented by left-digit * 10 1 + right-digit * 10 0. For example, 32 = 3*10 1 + 2*10 0 = 3*10 + 2*1 = 30 + 2 = 32. In the same way, 85 = 8*10 1 + 5*10 0 = 8*10 + 5*1 = 80 + 5 = 85. Using the same logic, you can get any number in the decimal system. Examples are: 2751 = 2*10 3 + 7*10 2 + 5*10 1 + 1*10 0 = 2*1000 + 7*100 + 5*10 + 1 = 2000 + 700 + 50 + 1 = 2751 67048 = 6*10 4 + 7*10 3 + 0*10 2 + 4*10 1 + 8*10 0 = 6*10000 + 7*1000+0*100+4*10+8*1 = 67048 Another way you can represent this is by using the following table: etc Add 0 to the preceding value 1000000 100000 10000 1000 100 10 0

When these numbers get large, they become difficult to read; an example is 279174394327. To make this easier to read, you can separate each thousand fraction with a comma. Our number would become 279,174,394,327. You can do this only on paper, never in a program: the compiler would not understand the comma(s). Why use the decimal system? Because, to represent numbers, that is the only system that you and I are familiar with.

The Hexadecimal System


While the decimal system uses 10 digits (they are all numeric), the hexadecimal system uses sixteen (16) symbols to represent a number. Since the Latin language consists of only 10 digits, we cannot make up new ones. To compensate for this, the hexadecimal system uses alphabetic characters. After counting from 0 to 9, the system uses letters until it gets 16 different values. The letters used are a, b, c, d, e, and f, or their uppercase equivalents A, B, C, D, E, and F. The hexadecimal system counts as follows: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, and f; or 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. Once again, to produce a number, you use a combination of these sixteen symbols. Examples of hexadecimal numbers are 293, 0, df, a37, c23b34, or ffed54. At first glance, the decimal representation of 8024 and the hexadecimal representation of 8024 are the same. Also, when you see fed, is it a name of a federal agency or a hexadecimal number? Does CAB represent a taxi, a social organization, or a hexadecimal number? From now on, to express the difference between a decimal number and a hexadecimal one, each hexadecimal number will start with 0x or 0X. The number will be followed by a valid hexadecimal combination. The letter can be in uppercase or lowercase.

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Legal Hexadecimals: 0x273, 0xfeaa, 0Xfe3, 0x35FD, 0x32F4e Non-Hex Numbers: 0686, ffekj, 87fe6y, 312

Why learn or use the hexadecimal system? Because the computer does not understand the decimal system, which is our everyday base of counting items, and because we do not understand or are not familiar with the binary system, the hexadecimal system provides an intermediary system. Also, the hexadecimal system represents shorter words to represent the same numbers in the decimal system.

Signed and unsigned


The numbers we have used so far were counting from 0, then 1, then 2, and up to any number desired, in incrementing values. Such a number that increments from 0, 1, 2, and up is qualified as positive. By convention, you do not need to let the computer or someone else know that such a number is positive: by just displaying or saying it, the number is considered positive. This is the basis of our counting items. In real life, there are numbers counted in decrement values. Such numbers start at 1 and move down to -2, -3, -4 etc. These numbers are qualified as negative. When you write a number normally, such as 42, 502, or 1250, the number is positive. If you want to express the number as negative, you use the on the left side of the number. The symbol is called a sign. Therefore, if the number does not have the symbol, C++ (or the compiler) considers such a number as unsigned. In C++, if you declare a variable that would represent a numeric value and you do not initialize (assign a value to) such a variable, the compiler will consider that the variable can hold either a signed or an unsigned value. If you want to let the compiler know that the variable should hold only a positive value, you will declare such a variable as unsigned.

Representing Numbers
A Bit
The computer (or an Intel computer, or a computer that runs on an Intel microprocessor) uses the binary system to represent its information. A piece of information in the computer is called a datum; and the plural is data. Sometimes, the word data is used for both singular and plural. The computer represents data using only a 0 or 1 values. To make an illustration, let's consider that a computer uses a small box to represent such a value. This small box can have only one of two states. When the box is empty, we will give it a value of 0. When the box is full, we give it a value of 1. The box can have only one of these two values.

Since this box can have only one of two states, consider that you can use it to represent anything that could assume one out of two states. Examples include: True-False; Parent-Child; On-Off; Discount-NoDiscount; Male-Female; Yes-No, etc. This technique of representing values is called The Binary system. In the computer, it uses values 0 and/or 1, which themselves are called digits. The entity used to represent such a value is called a binary digit; in its abbreviated form, it is called a bit (for binary digit). The bit (binary digit) is the most fundamental representation of the computer's counting system. Although this is valid for the computer, the Intel microprocessors cannot validate a variable at this level; but eventually, you will be able to manipulate data at the bit level. Although the C++ compiler recognizes a bit, you cannot store a variable in a bit. However, eventually, you will be able to manipulate the information stored in a bit. The single bit is used only to represent a tinny piece of information. To get effective numbers, the computer combines the bits. The first combination of bits consists of grouping four consecutive bits.

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

To count the bits, we number them starting at 0, followed by 1, 2, and 3. The count starts with the most right bit.

The Four-Bit Combination

The first bit, on the right side of the nibble, is called the Low Order bit or LO bit. This is also called the least significant bit. The last bit, on the left side of the nibble, is called the High Order bit or HI bit; it is also called the most significant bit. The bit on the right side is counted as bit 0. The bit on the left side is counted as bit 3. The other bits are called by their positions: bit 1 and bit 2. Once again, each bit can have one of two states. Continuing with our illustration, when a box is empty, it receives a value of 0. Otherwise, it has a value of 1. On a group of four consecutive bits, we can have the following combinations:

This produces the following binary combinations: 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111, 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111 = 16 combinations. When using the decimal system, these combinations can be represented as 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, and 15. As you can see, a nibble is represented by a group of 4 bits. This is also a system that the computer uses to count bits internally. Sometimes, in your program or in the help files, you will encounter a number that is less than four bits, such as 10 or 01 or 101. How do you reconcile such a number to a nibble? The technique used to complete and fill out the nibble consists of displaying 0 for each non-represented bit. The binary number 10 will be the same as 0010. The number 01 is the same as 0001. The number 101 is the same as 0101. This technique is valuable and allows you to always identify a binary number as a divider of 4. When all bits of a nibble are 0, you have the lowest value you can get, which is 0000. Any of the other combinations has at least one 0 bit, except for the last one. When all bits are 1, this provides the highest value possible for a nibble. The lowest value, also considered the minimum value, can be represented in the decimal system as 0. The highest value, also considered the maximum, can be expressed in decimal value as 2 4 (2 represents the fact that there are two possible states: 0 and 1; 4 represents the fact that there are four possible combinations), which is 16. This produces 16 because 2 4 = 16. As you can see, the binary system is very difficult to read when a value combines various bit representations. To make your life a little easier, the computer recognizes the hexadecimal representation of bits. Following the box combinations above, we can represent each 4-bit of the sixteen combinations using the decimal, hexadecimal, and binary systems as follows:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Decimal 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Hexadecimal 0 1 2 3 4 5 6 7 8 9 A B C D E F Binary 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111

Table of Numeric Conversions When looking at a binary value represented by 4 bits, you can get its decimal or hexadecimal values by referring to the table above. For this reason, you may have to memorize it. A nibble, which is a group of four consecutive bits, has a minimum and maximum values on each system as follows: Decimal 0 15 Hexadecimal 0x0 0xf Binary 0000 1111

Minimum Maximum

Although the C++ compiler recognizes a group of four consecutive bits, you cannot store any variable in a nibble. You can, however, manipulate the bits of a nibble.

A Byte
Representing a Byte

A byte is a group or eight consecutive bits. The bits are counted from right to left starting at 0. The most right bit is bit 0; it is called the least significant bit. It is also referred to as the Low Order bit, the LO bit, or LOBIT. The most left bit is bit 7; it is called the most significant bit. It is also referred to as the High Order bit, the HI bit, or HIBIT. The other bits are referred to following their positions. A byte is considered as being made of two nibbles. The right nibble, made of the right 4 bits, is called the Low Order nibble or LO nibble. The left nibble, made of the left 4 bits, is called the High Order nibble or HI nibble.

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Using the binary system, you can represent the byte using a combination of 0s and 1s. When all bits have a value of 0, the byte is represented as 00000000. On the other hand, when all bits have a value of 1, the byte is represented as 11111111. When the number grows very large, it becomes difficult to read. Therefore, we will represent bits in groups of four. Instead of writing 00000000, we will write 0000 0000. This makes the number easier to read. If you have the patience to create combinations of bits using the boxes as we did for the nibble, you would find out that there are 256 possible combinations. Another way to find it out is by using the base 2 technique: 27 + 26 + 25 + 24 + 23 + 22 + 21 + 20 = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255 Therefore, the maximum decimal value you can store in a byte is 255. Remember that the byte with all bits having a value of 0 has its value set to 0. Since this byte also holds a valid value, the number of combinations = 255 + 1 = 256. When a byte is completely represented with 0s, it provides the minimum value it can hold; this is 0000 0000, which is also 0. When all bits have a value of 1, which is 1111 1111, a byte holds its maximum value that we calculated as 255 in the decimal system. As done with the nibble, we get the following table: Decimal 0 255 Hexadecimal 0x0 0xff Binary 0000 1111 1111

Minimum Maximum

The minimum storage area offered by the (Intel) computer is the byte. As you know already, a byte is a group of 8 consecutive bits. The amount of memory space offered by a byte can be used to store just a single symbol, such as those you see on your keyboard. These symbols, also called characters, have been organized by the American Standard Code for Information Exchange (ASCII) in a set list. But, ASCII uses only 128 decimal numbers (based on a 7-bit format) to represent symbols counted from 0 to 127. To compensate for the remaining 1 bit, IBM used it to organize special characters, foreign language characters, mathematical symbols, small graphics, etc. Each one of these characters has a decimal, a hexadecimal, and a binary equivalents. Each one of the characters you see on your keyboard is represented as a numeric value, but whether it appears as a number, a letter, or a symbol, each one of these is considered a character. To display any character on your screen, you can use the cout << operator and include the character between single-quotes, as follows: #include <iostream> using namespace std; int main() { cout << 'a'; return 0; }

Character Variables
A byte is used to hold a single character. A character is an individual symbol that displays on your screen. It could be: A lowercase letter: a, b, c, d, e, f, g, h, I, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, and z An uppercase letter: A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y,

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
And Z A digit: 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9; A special characters : ` ~ # $ ! @ % ^ & * ( { [ ) } ] | \ : ; + - < _ ? > , / =. To declare a variable as a character, use the C++ keyword char followed by a valid C++ name. Here is an example: char Gender; With a byte variable declared like that, you can give the variable a starting value. Giving a value to a variable is referred to as initializing it. Initializing a variable is done with the = operator. The syntax used is: VariableName = Value; Since a char variable represents one symbol, to initialize it, enclose the initial value in single quotes. Here is an example: char Answer = y; You can also initialize a variable by including its value between parentheses as follows; char Answer(y); To display the value of an initialized variable, use the cout << extractor and type the name of the variable. Here is an example: #include <iostream> using namespace std; int main() { char category = 'H'; cout << "Category: " << category; cout << endl; return 0; } If the character is of a signed category, you can declare it as a signed character. This type of variable would be an 8-bit integer whose value can range from 128 to +127. Here is an example: #include <iostream> using namespace std; int main() { signed char category = 'D'; cout << "Category: " << category << endl; return 0; } You can also declare a positive character as unsigned char. Here is an example: #include <iostream> using namespace std; int main() { char letter = 'L'; char category = 'n'; unsigned char sound('x); cout << "Pick " << Pick; cout << category; cout << "Sound " << sound; return 0; } To request a byte variable, type the name of the variable on the right side of the cin >> extractor followed by a semi-colon as follows: #include <iostream> using namespace std; int main() { char Satisfaction, answer; signed char ageCategory, size;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "From A to Z, enter a character as your level of satisfaction: "; cin >> satisfaction; cout << "Age category(t=teen/a=Adult/s=Senior): "; cin >> ageCategory; cout << "Are you drunk(y=Yes/n=No)? "; cin >> answer; cout << "Enter your size(s=Small/m=Medium/l=Large): "; cin >> size; cout cout cout cout }
To keep the integer value of a char positive, you can declare it as an unsigned char. Its value would then range from 0 to 255.

<< << << <<

"\nSatisfaction: " << Satisfaction; "\nAge category: " << AgeCategory; "\nYour answer: " << Answer; "\nYour size: " << Size;

return 0;

Escape Sequences
When you use alphabetic characters in your program, the compiler considers them as numbers but converts each to its corresponding character following the ASCII list. Counting decimal values starting at 0, the first 32 characters actually do not display anything on the screen: they are called non-printing characters. They are obtained from pressing Ctrl and an alphabetic letter or a symbol. The exception is that the 8th to 12th characters are used to control some of the characters and they are called escape sequences. To use one of these escape sequences, you include it preceded by a backslash; you can include both in single-quotes. For example, the \n is used to ask the compiler to stop the line and start the remaining program to the next line; this is referred to Carriage Return Line Feed. The \n escape sequence could be used as follows: #include <iostream> using namespace std; int main() { cout << "Sydney\nAustralia\n"; return 0; } Besides the \n escape sequence, you can also use the endl keyword to move the cursor to the next line. Here is the list of escape sequences: Escape Name Sequence \a Bell (alert) \b Backspace Horizontal \t Tab \n \v \f \r \" \' \? \\ \0 New line Vertical Tab Form feed Carriage return Double Quote Apostrophe Question mark Backslash Null ASCII Description value 007 Makes a sound from the computer 008 Takes the cursor back 009 Takes the cursor to the next tab stop Takes the cursor to the beginning of the next line 011 Performs a vertical tab 012 010 013 Causes a carriage return 034 Displays a quotation mark (") 039 Displays an apostrophe (') 063 Displays a question mark 092 Displays a backslash (\) 000 Displays a null character

A Word
Representing a Word
Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
A word is a group of 16 consecutive bits. The bits are counted from right to left starting at 0:

Considered as a group of 16 bits, the most right bit of a word, bit 0, is called the least significant bit or Low Order bit or LO bit or LOBIT. The most left bit, bit 15, is called the most significant bit or High Order bit or HI bit or HIBIT. The other bits are referred to using their positions: bit 1, bit 2, bit 3, etc. Considering that a word is made of two bytes, the group of the right 8 bits is called the least significant byte or Low Order byte or LO byte or LOBYTE. The other group is called the most significant byte or High Order byte or HI byte or HIBYTE.

The most fundamental representation of a word in binary format is 0000000000000000. To make it easier to read, you can group bits in 4, like this: 0000 0000 0000 0000. Therefore, the minimum binary value represented by a word is 0000 0000 0000 0000. The maximum binary value represented by a word is 1111 1111 1111 1111. The minimum decimal value of a word is 0. To find out the maximum decimal value of a word, you can use the base 2 formula, filling out each bit with 1: 1*215+1*2 14+1*2 13 + 1*212 + 1*211 + 1*210 + 1*29 + 1*28 + 1*27 + 1*26 + 1*25 + 1*24 + 1*23 + 1*22 + 1*21 + 1*20 = 32768 + 16384 + 8192 + 4096 + 2048 + 1024 + 512 + 256 + 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 65535 The minimum hexadecimal value you can store in a word is 0x0000000000000000. This is also represented as 0x00000000, or 0x0000, or 0x0. All these numbers produce the same value, which is 0x0. To find out the maximum hexadecimal number you can store in a word, replace every group of 4 bits with an f or F: 1111 1111 1111 1111 f f f f = 0xffff = 0xFFFF = 0Xffff = 0XFFFF

Short Integers
A word, which is a group of 16 contiguous bits or 2 bytes, is used to represent a natural number. As we have studied, the maximum numeric value that can fit in a word is 65535. Since the Byte is used only to represent a character, whenever you plan to use a number in your program, the minimum representation you should/must use is a word. An algebraic natural number is also called an integer. The smallest integer you can store in a word is declared with the short keyword followed by a name. Because a short integer is signed by default, it can store a value that ranges from 32768 to 32767. Here is an example program that uses two short integers: #include <iostream>

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
using namespace std; int main() { short number1, number2; cout << "Enter a number between -32768 and 32767: "; cin >> number1; cout << "Enter another number: "; cin >> number2; cout << "\nThe numbers you entered were\n"; cout << "\tNumber 1: " << number1 << "\n"; cout << "\tNumber 2: " << number2 << "\n"; return 0; } By default, a short integer is signed. You can also explicitly declare such a variable as a signed short. Here is an example: signed short XCoord; If the integer must be positive, you should declared as an unsigned short. The unsigned short is used to identify a 16-bit positive integer whose value would range from 0 to 65535.

Practical Learning: Using Short Integer Variables


1. Start your programming environment and create a new project named GCS1. Depending on your environment, if the file was not created already, then create a source file and save it as, or name it exercise.cpp 2. Set the file's content as follows: #include <iostream> using namespace std; int main() { unsigned unsigned unsigned unsigned

short short short short

shirts; pants; dresses; ties;

cout << " -=- Georgetown Cleaning Services -=-\n"; cout << "Enter number of shirts: "; cin >> shirts; cout << "Enter number of pants: "; cin >> pants; cout << "Enter number of dresses: "; cin >> dresses; cout << "Enter number of ties: "; cin >> ties; cout cout cout cout << << << << "\n===================================="; "\n-=- Georgetown Cleaning Services -=-"; "\n===================================="; "\nCustomer Order" << "\nItem Type Qty" << "\nShirts: " << shirts << "\nPants: " << pants << "\nDresses: " << dresses << "\nTies: " << ties << "\n\n";

return 0; } 3. Execute the application and perform the exercise. Here is an example:

-=- Georgetown Cleaning Services -=Enter Enter Enter Enter number number number number of of of of shirts: 6 pants: 2 dresses: 3 ties: 4

==================================== -=- Georgetown Cleaning Services -=====================================

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Customer Order Item Type Qty Shirts: 6 Pants: 2 Dresses: 3 Ties: 4 4. Return to your programming environment

A Double-Word
Representing a Double-Word
A double-word is a group of two consecutive Words. This means that a double-word combines 4 bytes, or 8 nibbles, or 32 bits. The bits, counted from right to left, start at 0 and end at 31.

The most right bit, bit 0, is called the Low Order bit or LO bit or LOBIT. The most left bit, bit 31, is called the High Order bit or HI bit or HIBIT. The other bits are called using their positions. The group of the first 8 bits (from bit 0 to bit 7), which is the right byte, is called the Low Order Byte, or LO Byte. It is sometimes referred to as LOBYTE. The group of the last 8 bits (from bit 24 to bit 31), which is the left byte, is called the High Order Byte, or HI Byte or HIBYTE. The other bytes are called by their positions. The group of the right 16 bits, or the right Word, is called the Low Order Word, or LO Word, or LOWORD. The group of the left 16 bits, or the left Word, is called the High Order Word, or HI Word, or HIWORD.

The minimum binary number you can represent with a double-word is 0 The minimum decimal value of a double-word is 0. To find out the maximum decimal value of a word, you can use the base 2 formula giving a 1 value to each bit: 2 n1

2 30

2 29

2 28

2 27

2 26

2 25

2 24

etc 1,073,741,824 536,870,912 268,435,456 134,217,728 67,108,864 33,554,432 16,777,216 2 23 2 22 2 21 2 20 8,388,608 4,194,304 2,097,152 1,048,576 2 15 32,768 2 14 16,384 2 13 8,192 2 12 4,096 2 19 524,288 2 11 2,048 2 18 262,144 2 10 1,024 2 17 131,072 29 512 2 16 65,536 28 256

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
27 128 26 64 25 32 24 16 23 8 22 4 21 2 20 1

1*231+1*2 30+1*2 29 + 1*228 + 1*227 + 1*226 + 1*225 + 1*224 + 1*223 + 1*222 + 1*221 + 1*220 + 1*219 + 1*218 + 1*217 + 1*216 + 1*215 + 1*214 + 1*213 + 1*212 + 1*211 + 1*210 + 1*29 + 1*28 + 1*27 + 1*26 + 1*25 + 1*24 + 1*23 + 1*22 + 1*21 + 1*20 = 2,147,483,648 + 1,073,741,824 + 536,870,912 + 268,435,456 + 134,217,728 + 67,108,864 + 33,554,432 + 16,777,216 + 8,388,608 + 4,194,304 + 2,097,152 + 1,048,576 + 524,288 + 262,144 + 131,072 + 65,536 + 32,768 + 16,384 + 8,192 + 4,096 + 2,048 + 1,024 + 512 + 256 + 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 4,286,578,708 The minimum hexadecimal value you can store in a word is 0x0. To find out the maximum hexadecimal number you can represent with a word, replace every group of 4-bits with an f or F:

1111 1111 1111 1111 1111 1111 1111 1111 f f f f f f f f = 0xffffffff = 0Xffffffff = 0XFFFFFFFF = 0xFFFFFFFF

Using Integers
A double-word is large enough to contain double the amount of data that can be stored in a word. This is equivalent to 32 bits or 4 bytes or 4294967295. Therefore, a double-word is used for large numbers that would not fit in a word. An integer is a natural number typically used to count items. For an integer variable whose value requires more memory space than a word can hold, declare it using the int keyword. The integer data type is used for a variable whose value can range from 2,147,483,648 to 2,147,484,647. Here is an example: #include <iostream> using namespace std; int main() { int coordX, coordY, coordZ; cout << "Enter the coordinates of point A\n"; cout << "Horizontal X = "; cin >> coordX; cout << "Vertical Y = "; cin >> coordY; cout << "Depth Z = "; cin >> coordZ; cout cout cout cout } When executed, the program would produce: Enter the coordinates of point AHorizontal X = -12Vertical Y = 8Depth Z = 6On a cartesian system, point A is located at X = -12 Y = 8 Z = 6Press any key to continue... The signed is used to designate an integer variable whose value could be negative or positive. You can declare such a variable using one of the following: signed distanceRange; signed int velocity; When declared with int, an integer is considered as signed. You can also explicitly declared such an integer as signed int. Here is an example: << << << << "\nOn a cartesian system, point A is located at"; "\n\tX = " << coordX; "\n\tY = " << coordY; "\n\tZ = " << coordZ;

return 0;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
signed int pagePosition; If the variable must be positive, you can declared it an unsigned int. The unsigned int is used to identify a 32-bit positive integer variable whose value would range from 0 to 2,147,484,647. Here is an example: unsigned int pageCount; An unsigned integer can also be declared simply with the unsigned keyword. Here is an example: #include <iostream> using namespace std; int main() { unsigned dayOfBirth, monthOfBirth, yearOfBirth; cout << "The following pieces of information " << "are required for each student\n"; cout << "Day of Birth: "; cin >> dayOfBirth; cout << "Month of Birth: "; cin >> monthOfBirth; cout << "Year of Birth: "; cin >> yearOfBirth; cout << "\nStudent's Date of Birth: " << dayOfBirth << "/" << monthOfBirth << "/" << yearOfBirth; return 0; }

Practical Learning: Using Integer Variables


1. To use integer variables, change the source file as follows:

#include <iostream> using namespace std; int main() { unsigned unsigned unsigned unsigned

short short short short

shirts; pants; dresses; ties;

int orderDay; int orderMonth; int orderYear; cout << " -=- Georgetown Cleaning Services -=-\n"; cout << "Enter the date this order was placed\n"; cout << "Order Day: "; cin >> orderDay; cout << "Order Month: "; cin >> orderMonth; cout << "Order Year: "; cin >> orderYear; cout << "Enter number of shirts: "; cin >> shirts; cout << "Enter number of pants: "; cin >> pants; cout << "Enter number of dresses: "; cin >> dresses; cout << "Enter number of ties: "; cin >> ties; cout cout cout cout cout "\n===================================="; "\n-=- Georgetown Cleaning Services -=-"; "\n===================================="; "\nCustomer Order"; "\nOrder Date: " << orderMonth << '/' << orderDay << '/' << orderYear; cout << "\n------------------------------------" << "\nItem Type Qty"; cout << "\n------------------------------------" << "\nShirts: " << shirts << "\nPants: " << pants << "\nDresses: " << dresses << "\nTies: " << ties << "\n\n"; return 0; } << << << << <<

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
2. Execute the application and test the exercise. Here is an example:

-=- Georgetown Cleaning Services -=Enter Order Order Order Enter Enter Enter Enter the date this order was placed Day: 18 Month: 06 Year: 2000 number of shirts: 2 number of pants: 0 number of dresses: 3 number of ties: 0

==================================== -=- Georgetown Cleaning Services -===================================== Customer Order Order Date: 6/18/2000 -----------------------------------Item Type Qty -----------------------------------Shirts: 2 Pants: 0 Dresses: 3 Ties: 0 3. Return to your programming environment

Long Integers
An integer variable whose value should be positive can also be declared with the long keyword. The long keyword designates a positive 32-bit integer whose value ranges from 0 to 4,294,967,295. Here is an example: long countryArea; To enforce the long integer being positive, you can declare its variable as an unsigned long. The following program illustrates that: #include <iostream> using namespace std; int main() { long USPopulation; unsigned long USArea; cout << "What is the area of the US? "; cin >> USArea; cout << "What is the population of the US? "; cin >> USPopulation; cout << "\nCharacteristics of the US"; cout << "\n\tArea = " << USArea << "\n\tPopulation = " << USPopulation; return 0; }

Floating-Point Numbers
Floating-Point Numbers With Single-Precision
The integers we have used so far have the main limitation of not allowing decimal values. C++ provides floating identifier values that would solve this problem. The most fundamental floating variable is declared with the float keyword. The float is a 4 Byte real number that ranges from 3.4 x 10-38 to 3.4 x 1038. To declare a floating variable, use the float keyword followed by the name of the variable. Here are examples: float side; float length; To initialize a floating variable, after declaring it, assign it a value using the Assignment operator =, like this:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
float priceSoda; priceSoda = 0.85; You can also initialize the variable using the parentheses, like this: float priceOrangeJuice(2.25); To request a floating-point variable from the user, use the cin >> operator, like this cin >> variable; Like an initialized variable, you can perform any desired operation on such a variable. Here is an example program that requests the side of a square and then calculates the perimeter and the area: #include <iostream> using namespace std; int main() { float side, perimeter, area; cout << "Enter the side of the square: "; cin >> side; perimeter = side * 4; area = side * side; cout cout cout cout } << << << << "Characteristics of the square:"; "\nSide: " << side; "\nPerimeter: " << perimeter; "\nArea: " << area;

return 0;

Floating-Point Numbers With Double-Precision


When a variable is larger than the float can handle and requires more precision, you should use the double identifier. The double-precision identifier is an 8 Byte decimal or fractional number ranging from 1.7 x 10 -308 to 1.7 x 10 308. Here is an example: #include <iostream> using namespace std; int main() { float side, perimeter, area; cout << "Enter the side of the square: "; cin >> side; perimeter = side * 4; area = side * side; cout cout cout cout } For an even larger variable, use the 10 Byte real data type identified as a long double data type that ranges from 3.4 x 10 -4932 to 1.1 x 10 4932. Here is an example that uses the long double data type: #include <iostream> using namespace std; int main() { long double radius = 15.625, Radius = 18.125; long double area, Area, TotalArea; Area = Radius * Radius * 3.14159; << << << << "Characteristics of the square:"; "\nSide: " << side; "\nPerimeter: " << perimeter; "\nArea: " << area;

return 0;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
area = radius * radius * 3.14159; TotalArea = Area - area; cout cout cout cout } << << << << "Properties of the plate"; "\nExternal Radius: " << Radius; "\nInternal Radius: " << radius; "\nArea: " << TotalArea;

return 0;

Practical Learning: Using Floating-Point Numbers


1. To use decimal variables, change the source file as follows:

#include <iostream> using namespace std; int main() { unsigned unsigned unsigned unsigned double double double double

short short short short

shirts; pants; dresses; ties; = = = = 1.25; 2.75; 3.25; 1.65;

priceShirts pricePants priceDresses priceTies

int orderDay; int orderMonth; int orderYear; cout << " -=- Georgetown Cleaning Services -=-\n"; cout << "Enter the date this order was placed\n"; cout << "Order Day: "; cin >> orderDay; cout << "Order Month: "; cin >> orderMonth; cout << "Order Year: "; cin >> orderYear; cout << "Enter number of shirts: "; cin >> shirts; cout << "Enter number of pants: "; cin >> pants; cout << "Enter number of dresses: "; cin >> dresses; cout << "Enter number of ties: "; cin >> ties; cout cout cout cout cout "\n===================================="; "\n-=- Georgetown Cleaning Services -=-"; "\n===================================="; "\nCustomer Order"; "\nOrder Date: " << orderMonth << '/' << orderDay << '/' << orderYear; cout << "\n------------------------------------" << "\nItem Type Unit Price Qty"; cout << "\n------------------------------------" << "\nShirts: " << priceShirts << " " << shirts << "\nPants: " << pricePants << " " << pants << "\nDresses: " << priceDresses << " " << dresses << "\nTies: " << priceTies << " " << ties << "\n\n"; return 0; } 2. Execute the application and perform an order. Here is an example: << << << << <<

-=- Georgetown Cleaning Services -=Enter the date this order was placed Order Day: 14 Order Month: 10 Order Year: 2002 Enter number of shirts: 5 Enter number of pants: 2 Enter number of dresses: 3 Enter number of ties: 2 ==================================== -=- Georgetown Cleaning Services -===================================== Customer Order Order Date: 10/14/2002

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
-----------------------------------Item Type Unit Price Qty -----------------------------------Shirts: 1.25 5 Pants: 2.75 2 Dresses: 3.25 3 Ties: 1.65 2 3. Return to your programming environment

Introduction to Strings
A Group of Characters
A group of characters is called an array. This is a study we will cover when learning about arrays. For now, if you want to use a group of characters of any kind, declare a variable starting with a char data type, followed by a valid name for the variable, followed by an opening square bracket [, followed by a number of characters, followed by a closing square bracket ], and ended with a semi-colon. The syntax to declare a group of characters is: char VariableName[NumberOfCharacters]; The char keyword is required to let the compiler know that you want to create a variable of type char. The created variable must have a valid name. The number of characters, called the dimension of the array, should be an estimate; for example, if you want to request employees first names, type a number that you think would represent the largest name possible. The maximum number should be 80, but the average and a good regular number should be between 12 or 20. To represent an address or a similar long group of characters, use a dimension between 32 and 50. Examples of declaring arrays of characters are: char FirstName[12]; char LastName[12]; To initialize an array of characters, do not specify the dimension and leave the square brackets empty. You can use the assignment operator and include the initialized variable in doublequotes. Another technique, is to include the value between parentheses. Here is a program with two techniques of initializing arrays of characters: #include <iostream> using namespace std; int main() { char University[] = "University of the District of Columbia"; char Faculty[]("Computer sciences"); cout cout cout cout } To request an array from the user, simply type the name of the array variable on the right side of the cin >> operator. Here is an example: #include <iostream> using namespace std; int main() { char FirstName[12]; char LastName[12]; cout << "Enter First Name: "; cin >> FirstName; cout << "Enter Last Name: "; cin >> LastName; cout << "\nFull Name: " << FirstName << " " << LastName; cout << endl; return 0; } To request a group of words using an array, use one of the following functions: cin.getline( VariableName, Dimension); << << << << "Welcome to the Student Orientation Program.\n"; "For your studies, we have selected:\n"; "Institution: " << University << "\n"; "Faculty: " << Faculty << "\n";

return 0;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cin.getline(VariableName, Dimension, Delimeter); To use the array variables, change the content of the file as follows: #include <iostream> using namespace std; int main() { char FirstName [20], LastName [20]; char Address [40]; char JobPerformed [80]; cout << "Welcome to College Park Auto-Parts\n"; cout << "Enter the following information about the customer's.\n"; cout << "First Name: "; cin >> ws; cin.getline(FirstName, 20); cout << "Last Name: "; cin >> ws; cin.getline(LastName, 20); cout << "Address: "; cin >> ws; cin.getline(Address, 40); cout << "Describe the job performed on the customer's car in 100 words or less:\n"; cin >> ws; cin.getline(JobPerformed, 80); cout cout cout cout cout } << << << << << "\nCPAP Invoice # 1202"; "\nCustomer Name: " << FirstName << " " << LastName; "\nAddress: " << Address; "\nJob Performed: " << JobPerformed; "\n\n";

return 0;

Practical Learning: Using Strings


The following exercise was tested only in Microsoft Windows. The cin >> ws operation may not work on other operating systems but you would have to test it for yourself. Thanks. 1. To use string variables, change the source file as follows:

#include <iostream> using namespace std; int main() { char customerName[60], customerPhone[20]; unsigned short shirts; unsigned short pants; unsigned short dresses; unsigned short ties; double double double double priceShirts pricePants priceDresses priceTies = = = = 1.25; 2.75; 3.25; 1.65;

int orderDay; int orderMonth; int orderYear; cout << " -=- Georgetown Cleaning Services -=-\n"; cout << "Enter Customer Name: "; cin >> ws; cin.getline(customerName, 60); cout << "Enter Customer Phone: "; cin.getline(customerPhone, 20); cout << "Enter the date this order was placed\n"; cout << "Order Day: "; cin >> orderDay; cout << "Order Month: "; cin >> orderMonth; cout << "Order Year: "; cin >> orderYear; cout << "Enter number of shirts: "; cin >> shirts; cout << "Enter number of pants: "; cin >> pants; cout << "Enter number of dresses: "; cin >> dresses; cout << "Enter number of ties: ";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cin >> ties; cout cout cout cout cout cout cout "\n===================================="; "\n-=- Georgetown Cleaning Services -=-"; "\n===================================="; "\nCustomer Order"; "\nCustomer Name: " << customerName; "\nCustomer Phone: " << customerPhone; "\nOrder Date: " << orderMonth << '/' << orderDay << '/' << orderYear; cout << "\n------------------------------------" << "\nItem Type Unit Price Qty"; cout << "\n------------------------------------" << "\nShirts: " << priceShirts << " " << shirts << "\nPants: " << pricePants << " " << pants << "\nDresses: " << priceDresses << " " << dresses << "\nTies: " << priceTies << " " << ties << "\n\n"; return 0; } 2. Execute the application and perform an order. Here is an example: << << << << << << <<

Enter Order Order Order Enter Enter Enter Enter

the date this order was placed Day: 02 Month: 11 Year: 2001 number of shirts: 6 number of pants: 4 number of dresses: 2 number of ties: 0

==================================== -=- Georgetown Cleaning Services -===================================== Customer Order Customer Name: Jeannot Arnolds Customer Phone: (301) 938-2240 Order Date: 11/2/2001 -----------------------------------Item Type Unit Price Qty -----------------------------------Shirts: 1.25 6 Pants: 2.75 4 Dresses: 3.25 2 Ties: 1.65 0 3. Return to your programming environment

Strings
A string is a character, a group of characters, or an empty space that you want the compiler to treat as is. Besides using an array of characters, a special library called the Standard Template Library provides an alternative. You can declare a string using the string keyword. To use a string in your program, first include the string library using the using namespace keywords followed by std;. In your program, declare a variable starting with the word string followed by a valid name for the variable. Here are examples: string Continent; string Company; When requesting its value from the user, by default, the string identifier is used to get only a one-word variable. Here is an example program that requests a first and last names: #include <iostream> #include <string> using namespace std; int main() { string FirstName, LastName; cout << "Enter first name: "; cin >> FirstName; cout << "Enter last name: "; cin >> LastName; cout << "\n\nFull Name: " << FirstName << " " << LastName << "\n\n"; return 0;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} You can initialize a string variable of any length. One technique is to use the assignment operator and include the string in double-quotes. Here is an example: string UN = "United Nations"; cout << "The " << UN << " is an organization headed by a Secretary General"; Another technique involves using parentheses following the name of the string variable, and including the string in double-quotes. Here is an example: string BookTitle("Drugs, Sociology, and Human Behavior."); cout << "For our class next week, please read \"" << BookTitle;cout << "\""; If you want to request the value of the variable from the user, you should use the getline function. To use the getline function, follow this formula: getline(cin, StringName); Inside of the parentheses, the word cin informs the compiler that the request will come from an external source, mainly the user typing from the keyboard. The StringName is the name you declared the variable with. The getline() function expects that the user will press Enter to end the sentence; the end line character is \n. Here is an example program that requests strings of any length from the user: #include <iostream> #include <string> using namespace std; int main() { string MusicAlbum; string TrackTitle; cout << "Welcome to Radio Request where the listeners select their songs:\n"; cout << "Type the album name: "; getline(cin, MusicAlbum); cout << "Type the song title: "; getline(cin, TrackTitle); cout << "\nNow for your pleasure, we will play: " << TrackTitle << "\nfrom the " << MusicAlbum << " wonderful album.\n\n"; return 0; } If you want the user to end the sentence with another character such as * or !, use the following function getline(cin, StringName, Delimiter); The following example uses the = symbol as the end character of the sentence: string Address; cout << "Enter your address. To end, type = "; getline(cin, Address, '='); cout << "\nSo, you live at: " << Address; Here is an example: #include <iostream> #include <string> using namespace std; int main() { string FirstName, LastName; cout << "Welcome to College Park Auto-Parts\n"; cout << "Enter the following information about the customer's.\n"; cout << "First Name: "; cin >> FirstName; cout << "Last Name: "; cin >> LastName; cout << "\n\nCPAP Invoice # 1202"; cout << "\nCustomer Name: " << FirstName << " " << LastName << "\n\n"; return 0; } When requesting a string made of various words, such as an address, you can use the

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
getlin() function as follows: #include <iostream> #include <string> using namespace std; int main() { string FirstName, LastName; string Address; string JobPerformed; cout << "Welcome to College Park Auto-Parts\n"; cout << "Enter the following information about the customer's.\n"; cout << "First Name: "; cin >> FirstName; cout << "Last Name: "; cin >> LastName; cout << "Address: "; getline(cin, Address); cout << "Describe the job performed on the customer's car:\n"; getline(cin, JobPerformed); cout cout cout cout } << << << << "\n\nCPAP Invoice # 1202"; "\nCustomer Name: " << FirstName << " " << LastName; "\nAddress: " << Address; "\nJob Performed: " << JobPerformed << "\n\n";

return 0;

Previous

Copyright 1998-2006 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

C++ Support for Code Writing


Value Casting

Introduction
We have been introduced to declaring variables using specific data types. After declaring a value and initializing it, you may want the value to change type without redefining it. This is required in some cases where you already have a value, probably produced by one variable, while another variable declared with a different data type. This means that you would need to convert a value from one type into another type. For example, you may have declared a variable using a double data type but you need the value of that variable to be used as an int. Transferring a value from one type to another is referred to as casting. There are two broad types of casting available in C++: C's old school of casting and the C++ standards.

C How To Cast a Value


C, the parent of C++ supports value casting by specifying the type of value you want an existing one to have. To do this, you use the following formula:
(DataType)Expression

Based on this formula, in the parentheses, enter the type of data you want the existing or resulting value to have. The DataType factor can be any of the data types we saw above. The Expression factor can be a constant value. Here is an example:
#include <iostream> using namespace std; int main() { cout << "Number: " << (int)3.14159 << "\n"; } return 0;

Notice that the value to convert is a floating-point number. If the conversion is successful, the new value would be conform to the type in parentheses. For example, the above code would produce:
Number: 3

Here is another version of the above program:


#include <iostream> using namespace std; int main() { int number; number = (int)3.14159; cout << "Number: " << number << "\n"; } return 0;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
The Expression factor can also be the result of a calculation. In this case, you should include the whole expression is its own parentheses. The Expression factor of our formula can also be the name of a variable that holds a value. Here is an example:
#include <iostream> using namespace std; int main() { double price = 258.85; int number; cout << "Price? $" << price << "\n"; number = (int)price; cout << "Number: " << number << "\n"; } return 0;

This would produce:


Price? $258.85 Number: 258

C++ Casting
C++ provides its own support of value casting using variable keywords so you can specify the type of conversion you want. One of the keywords used is static_cast and the formula is:
static_cast<DataType>(Expression)

In this formula, the static_cast keyword, the <, the >, and the parentheses are required. The DataType factor should be an existing data type such as those we have reviewed in this lesson. The Expression factor can be a constant value. Here is an example that converts a floating-point number to an integer:
#include <iostream> using namespace std;

int main() { cout << "Number: " << static_cast<int>(3.14159) << "\n";

return 0; }

You can also assign the resulting value to a variable before using it:
#include <iostream> using namespace std;

int main() { int number = static_cast<int>(3.14159);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "Number: " << number << "\n";

return 0; }

The value to convert can also be the result of a calculation. The value can also be originating from an existing variable whose value you want to convert to a new type. Here is an example:
#include <iostream> using namespace std;

int main() { double PI = 3.14159; int number;

number = static_cast<int>(PI);

cout << "PI = " << PI << endl; cout << "Number = " << number << "\n";

return 0; }

This would produce:


PI = 3.14159 Number = 3

Variable Scope

Introduction
So far, to declare a variable, we proceeded inside of the main() function. Such a variable could be used only inside of the square brackets of main(). In some cases, you may want to declare a variable that can be accessed from one section of the code. The section of code in which a variable can be accessed is referred to as its scope.

Local Variables
If you declare a variable inside of a function such as main(), that function can be accessed only from that function. Consider the following example:
#include <iostream> using namespace std;

int main()

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ double number = 3.14159; cout << "Number = " << number << "\n";

return 0; }

Such a variable is referred to as local because it is declared in a function. In reality, a local scope is defined by a beginning opening curly bracket "{" and a closing curly bracket "}". Everything between these brackets belongs to a local scope. Once you have declared such a variable, you cannot declare another variable in the same scope and that bears the same name. Consider the following example:
#include <iostream> using namespace std;

int main() { double number = 3.14159; cout << "Number = " << number << "\n";

double number = 2.98; cout << "Number = " << number << "\n";

return 0; }

This would produce a "redefinition" error and the program would not compile, even if the second declaration uses a different data type. As one type of solution to this kind of problem, C++ allows you to create a "physical" scope. To do this, you can use curly brackets to delimit the scope of a particular variable. Here is an example:
#include <iostream> using namespace std;

int main() { { double number = 3.14159; cout << "Number = " << number << "\n"; }

double number = 2.98; cout << "Number = " << number << "\n";

return 0; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
This would produce:
Number = 3.14159 Number = 2.98

In the code, notice that we delimit only the first declaration. Indeed, you can delimit each scope if you want:
#include <iostream> using namespace std;

int main() { { double number = 3.14159; cout << "Number = " << number << "\n"; }

{ double number = 2.98; cout << "Number = " << number << "\n"; }

return 0; }

Global Variables
C++ allows you to declare a variable outside of any function. Such as a variable is referred to as a global variable (). To declare a global variable, proceed as you normally would. Here is an example:
#include <iostream> using namespace std;

C++ Note
Some languages such as Pascal or Visual Basic support global variables. Some other languages such as Java and C# don't support them

double number;

int main() {

return 0; }

After declaring the variable, you can initialize it immediately:


#include <iostream>

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
using namespace std;

double number = 3.14159;

int main() { cout << "Number = " << number << "\n";

return 0; }

You can also initialize it inside of the function that would use it. After declaring and initializing the variable, you can access its value and use it. For example, you can display its value to the user. Here is an example:
#include <iostream> using namespace std;

double number;

int main() { number = 3.14159;

cout << "Number = " << number << "\n";

return 0; }

In C++ (some other languages don't have this situation), the compiler always proceed in a topdown approach. After declaring a variable, only the sections under it can access it. This means that you cannot access a variable above its declaration. Consider the following program where only the area of the declaration has changed:
#include <iostream> using namespace std;

int main() { number = 3.14159;

cout << "Number = " << number << "\n";

return 0; }

double number;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
This program would not compile. The reason is that, when accessing it inside of main(), as far as main() is concerned, the variable has never been declared and C++ doesn't allow the use of a variable before it has been declared. Therefore, you must always declare a variable before accessing it.

Namespaces

Introduction
A namespace is a section of code, delimited and referred to using a specific name. A namespace is created to set apart a portion of code with the goal to reduce, otherwise eliminate, confusion. This is done by giving a common name to that portion of code so that, when referring to it, only entities that are part of that section would be recognized. A namespace is not a variable. It is not a function. It is not a class. It is only a technique of naming a section of code and referring to that section of code with a name.

Creating a namespace
The syntax of creating a namespace is:
namespace Name { Body }

The creation of a namespace starts with the (required) namespace keyword followed by a name that would identify the section of code. The name follows the rules we have been applying to C++ names except that, throughout this site, the name of a namespace will start in uppercase. A namespace has a body: this is where the entities that are part of the namespace would be declared or defined. The body of the namespace starts with an opening curly bracket { and ends with a closing curly bracket }. Here is an example of a simple namespace:
namespace Mine { int a; }

The entities included in the body of a namespace are referred to as its members.

Accessing a namespace: The Scope Access Operator


To access a member of a namespace, there are various techniques you can use. The scope access operator :: is used to access the members of a namespace. To do this, type the name of the namespace, followed by the scope access operator ::, followed by the member you are want to access. Only the members of a particular namespace are available when using its name. For example, to access the member a of the Mine namespace above, you can write:
Mine::a;

Once you have access to a namespace member, you can initialize it or display its value using cout. Here is an example:
#include <iostream> using namespace std;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
namespace Mine { int a; }

int main() { Mine::a = 140;

cout << "Value of a = " << Mine::a << endl; return 0; }

This would produce:


Value of a = 140

When creating a namespace, you can add as many members as you see fit. When necessary, you can use the scope access operator "::" to call anyone of them as needed. Here is an example:
#include <iostream> using namespace std;

namespace InterestAndDiscount { double principal; double rate; int periods; }

int main() { InterestAndDiscount::principal = 3250; InterestAndDiscount::rate = 0.1225; // =12.25% InterestAndDiscount::periods = 2;

cout << "Loan Processing"; cout << "\nPrincipal: $" << InterestAndDiscount::principal; cout << "\nRate: cout << "\nTime: " << InterestAndDiscount::rate*100 << "%"; " << InterestAndDiscount::periods << " years" << endl;

return 0; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
You can also request the values of the members of a namespace from the user. Remember to use the scope access operator "::" whenever you need to access the member of a namespace. Here is an example:
#include <iostream> using namespace std;

namespace InterestAndDiscount { double principal; double rate; int periods; }

int main() { cout << "Interest and Discount\n"; cout << "Principal: $"; cin >> InterestAndDiscount::principal; cout << "Rate (example 8.75): "; cin >> InterestAndDiscount::rate; cout << "Number of Years: "; cin >> InterestAndDiscount::periods;

cout << "\nLoan Processing"; cout << "\nPrincipal: $" << InterestAndDiscount::principal; cout << "\nRate: cout << "\nPeriods: " << InterestAndDiscount::rate << "%"; " << InterestAndDiscount::periods << " years" << endl;

return 0; }

Here is an example of running the program:


Interest and Discount Principal: $12500 Rate (example 8.75): 7.25 Number of Years: 10

Interest Calculation Principal: $12500.00 Rate: 7.25% Periods: 10 years

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
The member variable of a namespace can also be mixed with a variable that is locally declared in a function. All you have to do is make sure that you qualify the member of the namespace so the compiler would be able to locate it. Here is an example:
#include <iostream> using namespace std;

namespace InterestAndDiscount { double principal; double rate; int periods; }

int main() { double interest; double maturityValue;

cout << "Interest and Discount\n"; cout << "Principal: $"; cin >> InterestAndDiscount::principal; cout << "Rate (example 8.75): "; cin >> InterestAndDiscount::rate; cout << "Number of Years: "; cin >> InterestAndDiscount::periods;

interest = InterestAndDiscount::principal * (InterestAndDiscount::rate/100) * InterestAndDiscount::periods; maturityValue = InterestAndDiscount::principal + interest;

cout << "\nLoan Processing"; cout << "\nPrincipal: $" << InterestAndDiscount::principal; cout << "\nRate: cout << "\nPeriods: " << InterestAndDiscount::rate << "%"; " << InterestAndDiscount::periods << " years";

cout << "\nInterest: $" << interest; cout << "\nMaturity Value: $" << maturityValue << "\n\n";

return 0; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

The using Keyword


The scope access operator ::provides a safe mechanism to access the members of a namespace. If the namespace is very long and the application needs constant access, this might be a little cumbersome. Another technique used to access the members of a namespace involves using two keywords: using and namespace. To call a namespace, on the section of the program where you need to access the members, type:
using namespace NamespaceName;

Both the using and the namespace keywords are required by the compiler. The NamespaceName represents the name of the namespace whose member(s) you want to access. Using this technique, the above program can be written:
#include <iostream> using namespace std;

namespace InterestAndDiscount { double principal; double rate; int periods; }

int main() { using namespace InterestAndDiscount; double interest; double maturityValue;

cout << "Interest and Discount\n"; cout << "Principal: $"; cin >> principal; cout << "Rate (example 8.75): "; cin >> rate; cout << "Number of Years: "; cin >> periods;

interest = principal * (rate/100) * periods; maturityValue = principal + interest;

cout << "\nLoan Processing"; cout << "\nPrincipal: $" << principal; cout << "\nRate: cout << "\nPeriods: " << rate << "%"; " << periods << " years";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\nInterest: $" << interest; cout << "\nMaturity Value: $" << maturityValue << "\n\n";

return 0; }

Here is an example of a result:


Interest and Discount Principal: $2500 Rate (example 8.75): 12.15 Number of Years: 4

Loan Processing Principal: $2500 Rate: 12.15% Periods: 4 years Interest: $1215 Maturity Value: $3715

In a variable intensive program (we are still inside of one function only) where a local variable holds the same name as the member of a namespace that is being accessed with the using namespace routine, you will be sensitive to the calling of the same name variable. When manipulating such a name of a variable that is present locally in the function as well as in the namespace that is being accessed, the compiler will require more precision from you. You will need to specify what name is being called.

Combination of Namespaces

Introduction
Various namespaces can be part of the same file and the same application. You can create each namespace and specify its own members in its delimiting curly brackets. With various namespaces on the same file or application, you can have the same variables in different namespaces. Here is an example of two namespaces:
namespace InterestAndDiscount { double principal; double rate; int periods; double interest; double discount; double maturityValue; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
namespace BuyAndSell { double originalPrice; double taxRate; double taxAmount; double discount; double discountAmount; double netPrice; }

To access the member of a namespace, use the scope access operator appended to its name and call the desired member. Here is an example:
#include <iostream> using namespace std;

namespace InterestAndDiscount { double principal; double rate; int periods; double interest; double discount; double maturityValue; }

namespace BuyAndSell { double originalPrice; double taxRate; double taxAmount; double discount; double discountAmount; double netPrice; }

int main() { InterestAndDiscount::principal = 12500; // $ InterestAndDiscount::rate = 8.25; // % InterestAndDiscount::periods = 5; // Years InterestAndDiscount::discount = InterestAndDiscount::rate / 100;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
InterestAndDiscount::interest = InterestAndDiscount::principal * InterestAndDiscount::discount * InterestAndDiscount::periods; InterestAndDiscount::maturityValue = InterestAndDiscount::principal + InterestAndDiscount::interest;

cout << "Interest Calculation"; cout << "\nPrincipal: $" << InterestAndDiscount::principal << "\nRate: " << InterestAndDiscount::rate << "%" << "\nDiscount: " << InterestAndDiscount::discount << "\nPeriods: " << InterestAndDiscount::periods << " years" << "\nInterest: $" << InterestAndDiscount::interest << "\nMaturity Value: $" << InterestAndDiscount::maturityValue;

BuyAndSell::originalPrice = 250; // $ BuyAndSell::taxRate = 16.00; // % BuyAndSell::discount = 20.00; // %

BuyAndSell::taxAmount = BuyAndSell::originalPrice * BuyAndSell::taxRate / 100; BuyAndSell::discountAmount = BuyAndSell::originalPrice * BuyAndSell::discount / 100; BuyAndSell::netPrice = BuyAndSell::originalPrice + BuyAndSell::taxAmount BuyAndSell::discountAmount;

cout << "\n\nBuy and Sell - Receipt"; cout << "\nOriginal Price: $" << BuyAndSell::originalPrice << "\nDiscount: $" << BuyAndSell::discountAmount << "\nTax Rate: " << BuyAndSell::taxRate << "\nTax Amount: $" << BuyAndSell::taxAmount << "\nNet Price: $" << BuyAndSell::netPrice << "\n\n";

return 0; }

Using the scope access operator like that, you can perform any operation on any member of one namespace applied to a member of another namespace. We saw earlier that the using namespace routine allows accessing the members of a namespace. After typing it, if the name of a variable appears under a using namespace, the compiler would need to reconcile or identify it; if the name of such a variable is not recognized as part of the namespace that is being accessed, the program would not compile. For example, here is an example that uses two using namespace routines:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#include <iostream> using namespace std;

namespace InterestAndDiscount { double principal; double rate; int periods;

double interest; double discount; double maturityValue; }

namespace BuyAndSell { double originalPrice; double taxRate; double taxAmount; double discount; double discountAmount; double netPrice; }

int main() { using namespace InterestAndDiscount; principal = 12500; // $ rate = 8.25; // % periods = 5; // Years

discount = rate / 100; interest = principal * discount * periods; maturityValue = principal + interest;

cout << "Interest Calculation"; cout << "\nPrincipal: $" << principal << "\nRate: " << rate << "%"

<< "\nDiscount: " << discount << "\nPeriods: " << periods << " years"

<< "\nInterest: $" << interest

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
<< "\nMaturity Value: $" << maturityValue;

using namespace BuyAndSell; originalPrice = 250; // $ taxRate = 16.00; // % discount = 20.00; // %

taxAmount = originalPrice * taxRate / 100; discountAmount = originalPrice * discount / 100; netPrice = originalPrice + taxAmount - discountAmount;

cout << "\n\nBuy and Sell - Receipt"; cout << "\nOriginal Price: $" << originalPrice << "\nDiscount: $" << discountAmount << "\nTax Rate: " << taxRate << "\nTax Amount: $" << taxAmount << "\nNet Price: $" << netPrice << "\n\n";

return 0; }

The above program would not compile because the compiler does not understand what discount is being referred to in the second discount call: is it InterestAndDiscount::discount or BuyAndSell::discount? If you want to use different namespaces with the using namespace routine, each namespace will have to control its scope. One solution would be to create a physical scope for each namespace. Here is an example:
#include <iostream> using namespace std;

namespace InterestAndDiscount { double principal; double rate; int periods;

double interest; double discount; double maturityValue; }

namespace BuyAndSell {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
double originalPrice; double taxRate; double taxAmount; double discount; double discountAmount; double netPrice; }

int main() { { using namespace InterestAndDiscount; principal = 12500; // $ rate = 8.25; // % periods = 5; // Years

discount = rate / 100; interest = principal * discount * periods; maturityValue = principal + interest;

cout << "Interest Calculation"; cout << "\nPrincipal: $" << principal << "\nRate: " << rate << "%"

<< "\nDiscount: " << discount << "\nPeriods: " << periods << " years"

<< "\nInterest: $" << interest << "\nMaturity Value: $" << maturityValue; }

using namespace BuyAndSell; originalPrice = 250; // $ taxRate = 16.00; // % discount = 20.00; // %

taxAmount = originalPrice * taxRate / 100; discountAmount = originalPrice * discount / 100; netPrice = originalPrice + taxAmount - discountAmount;

cout << "\n\nBuy and Sell - Receipt";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\nOriginal Price: $" << originalPrice << "\nDiscount: $" << discountAmount << "\nTax Rate: " << taxRate << "\nTax Amount: $" << taxAmount << "\nNet Price: $" << netPrice << "\n\n";

return 0; }

Before creating a physical scope, we saw that the compiler is able to point out what problem occurred at compilation time. Fortunately, the compiler is able to explicitly designate what problem it encountered. In this case there is a conflict in name resolution: two namespaces have a member of the same name. The solution, which is commonly used, is to qualify the variable that is causing the conflict. You may want to qualify only the second discount call because the compiler will associate the first discount call with the first using namespace. The safest way is to qualify both calls to the discount variable, as follows:
#include <iostream> using namespace std;

namespace InterestAndDiscount { ... }

namespace BuyAndSell { ... }

int main() { using namespace InterestAndDiscount; principal = 12500; // $ rate = 8.25; // % periods = 5; // Years

InterestAndDiscount::discount = Rate / 100; interest = principal * InterestAndDiscount::discount * periods; maturityValue = principal + interest;

cout << "Interest Calculation"; cout << "\nPrincipal: $" << Principal

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
<< "\nRate: " << Rate << "%" << "\nDiscount: " << InterestAndDiscount::discount << "\nPeriods: " << periods << " years" << "\nInterest: $" << interest << "\nMaturity Value: $" << maturityValue;

using namespace BuyAndSell; originalPrice = 250; // $ taxRate = 16.00; // % BuyAndSell::discount = 20.00; // %

taxAmount = originalPrice * taxRate / 100; discountAmount = originalPrice * BuyAndSell::discount / 100; netPrice = originalPrice + taxAmount - discountAmount;

cout << "\n\nBuy and Sell - Receipt"; cout << "\nOriginal Price: $" << originalPrice << "\nDiscount: $" << discountAmount << "\nTax Rate: " << taxRate << "\nTax Amount: $" << taxAmount << "\nNet Price: $" << netPrice << "\n\n";

return 0; }

Nesting Namespaces
Nesting a namespace is the ability to include a namespace inside (as part of the body) of another namespace. To do this, create the intended namespace as a member of the parent namespace. The nested namespace should have its own name and its own body. Here is an example:
namespace BuyAndSell { double originalPrice; double taxRate; double taxAmount; double discount; double discountAmount; double netPrice; { long itemNumber; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
}

To access a member of a nested namespace, first call its parent, type the :: operator, type the name of the nested namespace, followed by the :: operator, then type the name of the variable you are trying to access. Here is an example:
#include <iostream> using namespace std;

namespace BuyAndSell { double originalPrice; double taxRate; double taxAmount; double discount; double discountAmount; double netPrice; namespace ItemID { long itemNumber; } }

int main() { BuyAndSell::originalPrice = 780.50; BuyAndSell::taxRate = 7.55; BuyAndSell::discount = 25; // % BuyAndSell::ItemID::itemNumber = 641238;

BuyAndSell::taxAmount = BuyAndSell::originalPrice * BuyAndSell::taxRate / 100; BuyAndSell::discountAmount = BuyAndSell::originalPrice * BuyAndSell::discount / 100; BuyAndSell::netPrice = BuyAndSell::originalPrice + BuyAndSell::taxAmount BuyAndSell::discountAmount;

cout << "Buy and Sell - Receipt"; cout << "\nItem Nunmber: " << BuyAndSell::ItemID::itemNumber; cout << "\nOriginal Price: $" << BuyAndSell::originalPrice; cout << "\nDiscount: $" << BuyAndSell::discountAmount;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\nTax Rate: " << BuyAndSell::taxRate; cout << "\nTax Amount $" << BuyAndSell::taxAmount; cout << "\nNet Price: $" << BuyAndSell::netPrice << "\n\n";

return 0; }

Following the same logic, you can have as many namespaces and as many nested namespaces in your application as you desire. If you nest a namespace, you can use as many "::" operators to qualify each member of the nested namespace as you want. Here is an example:
#include <iostream> using namespace std;

namespace BuyAndSell { double originalPrice; double taxRate; double taxAmount; double discount; double discountAmount; double netPrice; namespace ItemID { long itemNumber; namespace DateSold { int month; int Day; int Year; } } }

int main() { ...

BuyAndSell::ItemID::DateSold::month = 10; BuyAndSell::ItemID::DateSold::day = 18; BuyAndSell::ItemID::DateSold::year = 2002;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
...

return 0; }

You can also use the using namespace routine by calling each namespace using its complete name:
#include <iostream> using namespace std;

namespace BuyAndSell { double originalPrice; double taxRate; double taxAmount; double discount; double discountAmount; double netPrice; namespace ItemID { long itemNumber;

namespace DateSold { int month; int day; int year; } } }

int main() { using namespace BuyAndSell; using namespace BuyAndSell::ItemID; using namespace BuyAndSell::ItemID::DateSold;

originalPrice = 780.50; taxRate = 7.55; discount = 25; // % itemNumber = 641238;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
taxAmount = originalPrice * taxRate / 100; discountAmount = originalPrice * discount / 100; netPrice = originalPrice + taxAmount - discountAmount;

month = 10; day = 18; year = 2002;

cout << "Buy and Sell - Receipt"; cout << "\nReceipt Date: " << month << "/" << day << "/" << year; cout << "\nItem Nunmber: " << itemNumber; cout << "\nDiscount Category: " << qualifyForDiscount; cout << "\nOriginal Price: $" << originalPrice; cout << "\nDiscount: $" << discountAmount; cout << "\nTax Rate: " << taxRate; cout << "\nTax Amount $" << taxAmount; cout << "\nNet Price: $" << netPrice << "\n\n";

return 0; }

Otherwise, you can create a using namespace for each namespace and make sure that each one of them controls its scope. As long as you are using the scope access operator to identify the variable that is being accessed inside of a using namespace, you can call the member of any namespace in any scope, provided you qualify it.

The std Namespace


To avoid name conflicts of the various items used in its own implementation, the C++ Standard provides a namespace called std. The std namespace includes a series of libraries that you will routinely and regularly use in your programs. The following libraries are part of the std namespace: algorithm bitset complex deque exception fstream functional iomanip ios iosfwd iostream istream iterator limits list locale map memory new numeric ostream queue set sstream stack stdexcept streambuf string typeinfo utility valarray vector

The following additional libraries can be used to include C header files into a C++ program: cassert cctype cerrno cfloat cios646 climits clocale cmath csetjmp csignal cstdarg cstddef cstdio cstdlib cstring ctime cwchar cwctype

Therefore, whenever you need to use a library that is part of the std namespace, instead of typing a library with its file extension, as in iostream.h, simply type the name of the library as in iostream. Then, on the second line, type using namespace std;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
As an example, instead of typing
#include <iostream.h>

You can type:


#include <iostream> using namespace std;

Because this second technique is conform with the C++ Standard, we will use it whenever we need one of its libraries.

Previous

Copyright 1998-2006 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Operators and Operands


Unary Operators
Introduction
An operation is an action performed on one or more values either to modify the value held one or both of the variables or to produce a new value by combining variables. Therefore, operation is performed using at least one symbol and one value. The symbol used in operation is called an operator. A variable or a value involved in an operation is called operand. A unary operator is an operator that performs its operation on only one operand. An operator is referred to as binary if it operates on two operands. by an an an

Unary Operators: The Positive Operator +


Algebra uses a type of ruler to classify numbers. This ruler has a middle position of zero. The numbers on the left side of the 0 are referred to as negative while the numbers on the right side of the rulers are considered positive: - - -6 -6 -5 -5 -4 -4 -3 -3 -2 -2 -1 0 -1 1 2 3 4 5 6 + A value on the right side of 0 is considered positive. To express that a number is positive, you can write a + sign on its left. Examples are +4, +228, +90335. In this case the + symbol is called a unary operator because it acts on only one operand. The positive unary operator, when used, must be positioned on the left side of its operand, never on the right side. As a mathematical convention, when a value is positive, you do not need to express it with the + operator. Just writing the number without any symbol signifies that the number is positive. Therefore, the numbers +4, +228, and +90335 can be, and are better, expressed as 4, 228, 90335. Because the value does not display a sign, it is referred as unsigned as we learned in the previous lesson. To express a variable as positive or unsigned, you can just type it. here is an example: #include <iostream> using namespace std; 1 2 3 4 5 6 +

int main() { int number = +802;

cout << "The value of the number is: " << number << "\n";

return 0; }

Unary Operators: The Negative Operator As you can see on the above ruler, in order to express any number on the left side of 0, it must be appended with a sign, namely the - symbol. Examples are -12, -448, -32706. A value accompanied by - is referred to as negative.

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
The - sign must be typed on the left side of the number it is used to negate. Remember that if a number does not have a sign, it is considered positive. Therefore, whenever a number is negative, it MUST have a - sign. In the same way, if you want to change a value from positive to negative, you can just add a - sign to its left. Here is an example that uses two variables. One has a positive value while the other has a negative value: #include <iostream> using namespace std;

int main() { int number1 = 802; int number2 = -62;

cout << "The value of the first number is: " << number1 << "\n"; cout << "The value of the second number is: " << number2 << "\n";

return 0; }

Unary Operators: Increment and Decrement ++ and -The increment operator is used to increase the value of a number or variable by 1. The increment operator is performed with the ++ operator. Because it involves a few more other issues, we will study it later on. The decrement operator is used to decrease the value of a number or variable by 1. The decrement operator is performed with the -- operator. Because it involves a few more other issues, we will study it later on.

Unary Operators: The Address Of Operator &


In the previous lesson, we learned that, when declaring a variable, the compiler reserves an amount of space in memory for that variable. C++ provides an operator that can tell you where (the space for) a variable is located. This is done using the "address of" operator represented by the ampersand &. To get the address of a variable, use the ampersand operator on its left. The address is a hexadecimal number. Here is an example: #include <iostream> using namespace std;

int main() { int number = 46;

cout << "\n&Number = " << &number;

return 0; } This would produce: &Number = 0012FED4

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Unary Operators: The sizeof Operator


We have already seen that when declaring a variable, the compiler reserves a portion of space in the computer memory to hold that variable. We also illustrated how much space some data types need to store their variable. C++ provides the unary sizeof operator that allows you to find out how much space a data type or a certain variable in your program is using. There are four methods you can use with the sizeof operator: using the variable or the data type. The general syntaxes of the sizeof operator are: sizeof VariableName; sizeof DataType; sizeof(VariableName); sizeof(DataType); Any of these four formulas is admissible. But it is good to refrain from using the data type except in rare cases that you can justify. The reason you should apply the sizeof operator on the variable is because, if you change the variable (the word variable means it can change throughout the program), that is, if you perform any operation on it, the sizeof operator will acknowledge that and render the right result. Some and most of the time, if you apply the sizeof operator on the data type, you might end up with a bug; if you are lucky, the program would simply not compile. Here is an example: #include <iostream> using namespace std;

int main() { double period = 155.50; int sizeOf = sizeof Period;

cout << "The size of Period is " << sizeOf << " bytes\n\n";

return 0; } Here is an example with various uses of the sizeof operator // Use of the sizeof operator to find out how much // space a variable or an identifier are using #include <iostream> using namespace std;

int main() { char iChar; unsigned char uChar; signed char sChar; int iInt; short int sInt; unsigned int uInt; unsigned short int uShortInt; long int LInt; unsigned long int uLongInt; float iFloat;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
double iDouble; long double lDouble;

cout << "The sizeof operator used on a variable\n\n"; cout << "Identifier\t Memory Size\n" << "\t\t in Bytes\n"; cout << "----------------------------------"; cout << "\nchar\t\t\t" << sizeof(char); cout << "\nunsigned char\t\t" << sizeof(unsigned char); cout << "\nsigned char\t\t" << sizeof(signed char); cout << "\nint\t\t\t" << sizeof(int); cout << "\nshort int\t\t" << sizeof(short int); cout << "\nunsigned int\t\t" << sizeof(unsigned int); cout << "\nunsigned short int\t" << sizeof(unsigned short int); cout << "\nlong int\t\t" << sizeof(long int); cout << "\nunsigned long int\t" << sizeof(unsigned long int); cout << "\nfloat\t\t\t" << sizeof(float); cout << "\ndouble\t\t\t" << sizeof(double); cout << "\nlong double\t\t" << sizeof(long double);

cout << "\n\n";

return 0; } This would produce: The sizeof operator used on a variable

Identifier

Memory Size in Bytes

---------------------------------char unsigned char signed char int short int unsigned int unsigned short int long int unsigned long int float double long double 8 8 4 4 2 4 4 2 1 1 4 1

While the previous example uses the name of data types, the following sizeof operators are used on the name of variables // Use of the sizeof operator to find out how much // space a variable or an identifier are using

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#include <iostream> using namespace std;

int main() { char iChar; unsigned char uChar; signed char sChar; int iInt; short int sInt; unsigned int uInt; unsigned short int uShortInt; long int LInt; unsigned long int uLongInt; float iFloat; double iDouble; long double lDouble;

cout << "The sizeof operator used on an identifier\n\n"; cout << "Identifier\t Memory Size\n" << "\t\t in Bytes\n"; cout << "------------------------------"; cout << "\nchar\t\t\t" << sizeof(iChar); cout << "\nunsigned char\t\t" << sizeof(uChar); cout << "\nsigned char\t\t" << sizeof(sChar); cout << "\nint\t\t\t" << sizeof(iInt); cout << "\nshort int\t\t" << sizeof(sInt); cout << "\nunsigned int\t\t" << sizeof(uInt); cout << "\nunsigned short int\t" << sizeof(uShortInt); cout << "\nlong int\t\t" << sizeof(LInt); cout << "\nunsigned long int\t" << sizeof(uLongInt); cout << "\nfloat\t\t\t" << sizeof(iFloat); cout << "\ndouble\t\t\t" << sizeof(iDouble); cout << "\nlong double\t\t" << sizeof(lDouble);

cout << "\n\n";

return 0; }

Algebraic Operators
Introduction
In algebra, operations are performed on numeric values. Algebraic operators are represented with the following symbols:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Practical Learning: Introducing Operators


1. Start your programming environment and create a new project named GCS2. Depending on your environment, if the file was not created already, then create a source file and save it as, or name it, exercise.cpp 2. Set the file's content as follows: #include <iostream> using namespace std;

int main() { char customerName[60], customerPhone[20];

unsigned short shirts; unsigned short pants; unsigned short dresses; unsigned short ties;

double priceShirts double pricePants

= 1.25; = 2.75;

double priceDresses = 3.25; double priceTies = 1.65;

int orderDay; int orderMonth; int orderYear;

cout << " -=- Georgetown Cleaning Services -=-\n"; cout << "Enter Customer Name: cin >> ws; cin.getline(customerName, 60); cout << "Enter Customer Phone: "; cin.getline(customerPhone, 20); cout << "Enter the date this order was placed\n"; cout << "Order Day: cin >> orderDay; cout << "Order Month: "; cin >> orderMonth; cout << "Order Year: "; cin >> orderYear; cout << "Enter number of shirts: "; cin >> shirts; cout << "Enter number of pants: "; cin >> pants; cout << "Enter number of dresses: "; "; ";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cin >> dresses; cout << "Enter number of ties: "; cin >> ties;

cout << "\n===================================="; cout << "\n-=- Georgetown Cleaning Services -=-"; cout << "\n===================================="; cout << "\nCustomer Order"; cout << "\nCustomer Name: " << customerName;

cout << "\nCustomer Phone: " << customerPhone; cout << "\nOrder Date: " << orderMonth << '/' << orderDay << '/' << orderYear; cout << "\n------------------------------------" << "\nItem Type Unit Price Qty";

cout << "\n------------------------------------" << "\nShirts: << "\nPants: << "\nDresses: << "\nTies: << "\n\n"; " << priceShirts << " " << pricePants << " " << priceDresses << " " << priceTies << " " << shirts " << pants " << dresses " << ties

return 0; } 3. Execute the application and perform the exercise 4. Return to your programming environment

The Addition
The addition is an operation used to add one number to another. For example, if you have one pen and somebody gives you another pen, then you have two pens. If you keep receiving pens, you will soon have more than you had originally. In this manner, as you add pens, the number grows. The addition gives you to ability to add things of the same nature one to another, as many as necessary, until all items have been added. Sometimes, the items are added one group to another. The concept is still the same, except that this last example is faster. For example, if you have a group of eleven students and you add 5 students to the group, you can apply the same rule by adding one student at a time. But to perform this operation faster, you should work to add groups of items to one another. The addition is performed in mathematics using the + sign. The same sign is used in C++. The + sign is located on the left side of the Backspace key. You get it by pressing Shift and =. To get the addition of two values, you add the first one to the other. After the addition of two values has been performed, you get a new value. This means if you add Value1 to Value2, you would write Value1 + Value2. The result is another value we could call Value3. You can also add more than two values, like a + b + c. The order you use to add two or more values doesn't matter. This means Value1 + Value2 is the same as Value2 + Value1. In the same way a + b + c is the same as a + c + b the same as b + a + c and the same as c + b + a. In C++, you can add values you know already, or you can use values the program gets from the user. The simplest way to add values in C++ is by performing a simple sum. Here is an example: // Program used to get the sum of two values

#include <iostream>

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
using namespace std;

iint main() { // Get the sum of two values cout << "244 + 835 = " << 244 + 835;

cout << "\n\n";

return 0; } Here is the result: 244 + 835 = 1079 You can also add some values already declared and initialized in your program. Here is an example: // Program used to get the sum of two initialized values #include <iostream> using namespace std;

int main() { int a = 244; int b = 835;

// Get the sum of a and b cout << a << " + " << b << " = " << a + b; cout << "\n\n";

return 0; } You can also get the values from the user as illustrated in the following program: // Program used to get the sum of two initialized values #include <iostream> using namespace std;

int main() { int a, b, c;

// Get the sum of a, b, and c. cout << "\nType the first value: "; cin >> a; cout << "The second value: "; cin >> b; cout << "The last value: "; cin >> c;

cout << a << " + " << b << " + " << c << " = " << a + b + c << "\n\n";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return 0; }

Practical Learning: Using the Addition


1. To perform an addition, change the file as follows: #include <iostream> using namespace std;

int main() { char customerName[60], customerPhone[20];

unsigned short shirts; unsigned short pants; unsigned short dresses; unsigned short ties; unsigned short totalItems;

double priceShirts double pricePants

= 1.25; = 2.75;

double priceDresses = 3.25; double priceTies = 1.65;

int orderDay; int orderMonth; int orderYear;

cout << " -=- Georgetown Cleaning Services -=-\n"; cout << "Enter Customer Name: cin >> ws; cin.getline(customerName, 60); cout << "Enter Customer Phone: "; cin.getline(customerPhone, 20); cout << "Enter the date this order was placed\n"; cout << "Order Day: cin >> orderDay; cout << "Order Month: "; cin >> orderMonth; cout << "Order Year: "; cin >> orderYear; cout << "Enter number of shirts: "; cin >> shirts; cout << "Enter number of pants: "; cin >> pants; cout << "Enter number of dresses: "; cin >> dresses; cout << "Enter number of ties: "; "; ";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cin >> ties;

totalItems = shirts + pants + dresses + ties;

cout << "\n===================================="; cout << "\n-=- Georgetown Cleaning Services -=-"; cout << "\n===================================="; cout << "\nCustomer Order"; cout << "\nCustomer Name: " << customerName;

cout << "\nCustomer Phone: " << customerPhone; cout << "\nOrder Date: " << orderMonth << '/' << orderDay << '/' << orderYear; cout << "\n------------------------------------" << "\nItem Type Unit Price Qty";

cout << "\n------------------------------------" << "\nShirts: << "\nPants: << "\nDresses: << "\nTies: " << priceShirts << " " << pricePants << " " << priceDresses << " " << priceTies << " " << shirts " << pants " << dresses " << ties;

cout << "\n------------------------------------" << "\nTotal Number of Items: " << totalItems << "\n\n";

return 0; } 2. Execute the application and process an order. Here is an example: Order Month: 12 Order Year: 2002 Enter number of shirts: 12 Enter number of pants: 8 Enter number of dresses: 4 Enter number of ties: 6

==================================== -=- Georgetown Cleaning Services -===================================== Customer Order Customer Name: Alain Kounkou

Customer Phone: (240) 843-8220 Order Date: 12/12/2002 -----------------------------------Item Type Unit Price Qty

-----------------------------------Shirts: Pants: Dresses: Ties: 1.25 2.75 3.25 1.65 4 6 12 8

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
-----------------------------------Total Number of Items: 30 3. Return to your programming environment

The Multiplication
The multiplication allows adding one value to itself a certain number of times, set by a second value. As an example, instead of adding a value to itself in this manner: a + a + a + a, since the variable a is repeated over and over again, you could simply find out how many times a is added to itself, then multiply a by that number which, is this case, is 4. This would mean adding a to itself 4 times, and you would get the same result. The multiplication is performed with the * sign which is typed with Shift + 8. Just like the addition, the multiplication is associative: a * b * c = c * b * a. When it comes to programming syntax, the rules we learned with the addition operation also apply to the multiplication. Here is an example: // Multiplication of multiple values #include <instream> using namespace std;

int main() { float a, b;

// Multiple of a and b. cout << "\nType two values: "; cin >> a >> b; cout << a << " * " << b << " = " << a * b; cout << "\n\n";

return 0; }

Practical Learning: Using the Multiplication


1. To perform a multiplication, change the file as follows: #include <iostream> using namespace std;

int main() { char customerName[60], customerPhone[20];

unsigned short shirts; unsigned short pants; unsigned short dresses; unsigned short ties; unsigned short totalItems;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
double priceShirts double pricePants = 1.25; = 2.75;

double priceDresses = 3.25; double priceTies = 1.65;

double totalCostShirts, totalCostPants, totalCostDresses, totalCostTies; double totalCostCleaning;

int orderDay; int orderMonth; int orderYear;

cout << " -=- Georgetown Cleaning Services -=-\n"; cout << "Enter Customer Name: cin >> ws; cin.getline(customerName, 60); cout << "Enter Customer Phone: "; cin.getline(customerPhone, 20); cout << "Enter the date this order was placed\n"; cout << "Order Day: cin >> orderDay; cout << "Order Month: "; cin >> orderMonth; cout << "Order Year: "; cin >> orderYear; cout << "Enter number of shirts: "; cin >> shirts; cout << "Enter number of pants: "; cin >> pants; cout << "Enter number of dresses: "; cin >> dresses; cout << "Enter number of ties: "; cin >> ties; "; ";

totalItems = shirts + pants + dresses + ties;

totalCostShirts totalCostPants totalCostDresses totalCostTies

= shirts = pants

* priceShirts; * pricePants;

= dresses * priceDresses; = ties * priceTies;

totalCostCleaning = totalCostShirts + totalCostPants + totalCostDresses + totalCostTies;

cout << "\n===================================="; cout << "\n-=- Georgetown Cleaning Services -=-"; cout << "\n====================================";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\nCustomer Order"; cout << "\nCustomer Name: " << customerName;

cout << "\nCustomer Phone: " << customerPhone; cout << "\nOrder Date: " << orderMonth << '/' << orderDay << '/' << orderYear; cout << "\n------------------------------------" << "\nItem Type Unit Price Qty Sub-Total";

cout << "\n------------------------------------" << "\nShirts: " << totalCostShirts << "\nPants: << totalCostPants << "\nDresses: " << totalCostDresses << "\nTies: totalCostTies; cout << "\n------------------------------------" << "\nTotal Number of Items: " << totalItems " << priceShirts << " " << pricePants << " " << priceDresses << " " << priceTies << " " << shirts << " " << pants << " " << dresses << " " << ties << " " << "

<< "\nTotal Cleaning of Items: " << totalCostCleaning << "\n";

return 0; } 2. Execute the application and process an order. Here is an example: -=- Georgetown Cleaning Services -=Enter Customer Name: Patrice Keller

Enter Customer Phone: (703) 722-8814 Enter the date this order was placed Order Day: 10

Order Month: 12 Order Year: 2002 Enter number of shirts: 8 Enter number of pants: 8 Enter number of dresses: 5 Enter number of ties: 6

==================================== -=- Georgetown Cleaning Services -===================================== Customer Order Customer Name: Patrice Keller

Customer Phone: (703) 722-8814 Order Date: 12/10/2002 -----------------------------------Item Type Unit Price Qty Sub-Total

-----------------------------------Shirts: Pants: Dresses: Ties: 1.25 2.75 3.25 1.65 5 6 8 8 10 22 16.25 9.9

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
-----------------------------------Total Number of Items: 27

Total Cleaning of Items: 58.15 3. Return to your programming environment

The Subtraction
The subtraction operation is used to take out or subtract a value from another value. It is essentially the opposite of the addition. The subtraction in C++ is performed with the - sign, which is between the 0 and the = keys. Here is an example: // Subtraction of two values #include <iostream> using namespace std;

int main() { // Values used in this program int value1, value2, value3;

// Get the values from the user cout << "Type the first number: "; cin >> value1; cout << "Type another number: "; cin >> value2;

// Subtract the first value from the second value3 = value1 - value2;

cout << value1 << " - " << value2 << " = " << value3 << "\n\n";

return 0; }
The following program shows the non-associativity of the subtraction operation:

// Non-associativity of the subtraction operation #include <iostream> using namespace std;

int main() { // Addition associativity cout << "128 + 42 + 5 = " << 128 + 42 + 5; cout << "\n5 + 42 + 128 = " << 5 + 42 + 128;

cout << "\n";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
// Subtraction non-associativity cout << "\n128 - 42 - 5 = " << 128 - 42 - 5; cout << "\n5 - 42 - 128 = " << 5 - 42 - 128;

cout << "\n\n";

return 0; }
This would produce:

128 + 42 + 5 = 175 5 + 42 + 128 = 175

128 - 42 - 5 = 81 5 - 42 - 128 = -165 Notice that both operations of the addition convey the same result. In the subtraction section, the numbers follow the same order but a different operation; and the last two operations render different results.

Practical Learning: Using the Subtraction


1. To apply a subtraction, change the file as follows: #include <iostream> using namespace std;

int main() { char customerName[60], customerPhone[20];

unsigned short shirts; unsigned short pants; unsigned short dresses; unsigned short ties; unsigned short totalItems;

double priceShirts double pricePants

= 1.25; = 2.75;

double priceDresses = 3.25; double priceTies = 1.65;

double totalCostShirts, totalCostPants, totalCostDresses, totalCostTies; double totalCostCleaning; double amountTended, difference;

int orderDay; int orderMonth; int orderYear;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

cout << " -=- Georgetown Cleaning Services -=-\n"; cout << "Enter Customer Name: cin >> ws; cin.getline(customerName, 60); cout << "Enter Customer Phone: "; cin.getline(customerPhone, 20); cout << "Enter the date this order was placed\n"; cout << "Order Day: cin >> orderDay; cout << "Order Month: "; cin >> orderMonth; cout << "Order Year: "; cin >> orderYear; cout << "Enter number of shirts: "; cin >> shirts; cout << "Enter number of pants: "; cin >> pants; cout << "Enter number of dresses: "; cin >> dresses; cout << "Enter number of ties: "; cin >> ties; "; ";

totalItems = shirts + pants + dresses + ties;

totalCostShirts totalCostPants totalCostDresses totalCostTies

= shirts = pants

* priceShirts; * pricePants;

= dresses * priceDresses; = ties * priceTies;

totalCostCleaning = totalCostShirts + totalCostPants + totalCostDresses + totalCostTies;

cout << "The total order is: " << totalCostCleaning << "\n"; cout << "Amount Tended: "; cin >> amountTended; difference = amountTended - totalCostCleaning;

cout << "\n===================================="; cout << "\n-=- Georgetown Cleaning Services -=-"; cout << "\n===================================="; cout << "\nCustomer Order"; cout << "\nCustomer Name: " << customerName;

cout << "\nCustomer Phone: " << customerPhone; cout << "\nOrder Date: " << orderMonth << '/' << orderDay << '/' << orderYear; cout << "\n------------------------------------" << "\nItem Type Unit Price Qty Sub-Total";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\n------------------------------------" << "\nShirts: totalCostShirts << "\nPants: totalCostPants << "\nDresses: totalCostDresses << "\nTies: totalCostTies; " << priceShirts << " " << pricePants << " " << priceDresses << " " << priceTies << " " << shirts << " " << pants << " " << dresses << " " << ties << " " << " << " << " <<

cout << "\n------------------------------------" << "\nTotal Number of Items: " << totalItems

<< "\nTotal Cleaning of Items: " << totalCostCleaning << "\nAmount Tended: << "\nDifference: " << amountTended " << difference << "\n";

return 0; } 2. Execute the application and process an order. Here is an example: -=- Georgetown Cleaning Services -=Enter Customer Name: Raymond Lamont

Enter Customer Phone: (202) 888-0022 Enter the date this order was placed Order Day: 20

Order Month: 02 Order Year: 2002 Enter number of shirts: 5 Enter number of pants: 2 Enter number of dresses: 0 Enter number of ties: 4 The total order is: 18.35 Amount Tended: 20

==================================== -=- Georgetown Cleaning Services -===================================== Customer Order Customer Name: Raymond Lamont

Customer Phone: (202) 888-0022 Order Date: 2/20/2002 -----------------------------------Item Type Unit Price Qty Sub-Total

-----------------------------------Shirts: Pants: Dresses: Ties: 1.25 2.75 3.25 1.65 5 2 0 4 6.25 5.5 0 6.6

-----------------------------------Total Number of Items: 11

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Total Cleaning of Items: 18.35 Amount Tended: Difference: 20 1.65

3. Return to your programming environment

The Division
Dividing an item means cutting it in pieces or fractions of a set value. For example, when you cut an apple in the middle, you are dividing it in 2 pieces. If you cut each one of the resulting pieces, you will get 4 pieces or fractions. This is considered that you have divided the apple in 4 parts. Therefore, the division is used to get the fraction of one number in terms of another. The division is performed with the forward slash /. When performing the division, be aware of its many rules. Never divide by zero (0). Make sure that you know the relationship(s) between the numbers involved in the operation. Here is an example: // Program used to get half of a number. #include <iostream> using namespace std;

int main() { float a;

// Get a number from the user. cout << "\nType a number: "; cin >> a; cout << " Half of " << a << " is " << a / 2 << "\n\n";

return 0; }

Practical Learning: Using the Division


1. To divide a value, change the file as follows: #include <iostream> using namespace std;

int main() { char customerName[60], customerPhone[20];

unsigned short shirts; unsigned short pants; unsigned short dresses; unsigned short ties; unsigned short totalItems;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
double priceShirts double pricePants = 1.25; = 2.75;

double priceDresses = 3.25; double priceTies double taxRate = 1.65; = 5.75; // 5.75%

double totalCostShirts, totalCostPants, totalCostDresses, totalCostTies; double totalCostCleaning; double amountTended, difference; double taxAmount, netPrice;

int orderDay; int orderMonth; int orderYear;

cout << " -=- Georgetown Cleaning Services -=-\n"; cout << "Enter Customer Name: cin >> ws; cin.getline(customerName, 60); cout << "Enter Customer Phone: "; cin.getline(customerPhone, 20); cout << "Enter the date this order was placed\n"; cout << "Order Day: cin >> orderDay; cout << "Order Month: "; cin >> orderMonth; cout << "Order Year: "; cin >> orderYear; cout << "Enter number of shirts: "; cin >> shirts; cout << "Enter number of pants: "; cin >> pants; cout << "Enter number of dresses: "; cin >> dresses; cout << "Enter number of ties: "; cin >> ties; "; ";

totalItems = shirts + pants + dresses + ties;

totalCostShirts totalCostPants totalCostDresses totalCostTies

= shirts = pants

* priceShirts; * pricePants;

= dresses * priceDresses; = ties * priceTies;

totalCostCleaning = totalCostShirts + totalCostPants + totalCostDresses + totalCostTies;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
taxAmount netPrice = totalCostCleaning * taxRate / 100; = totalCostCleaning + taxAmount;

cout << "The total order is: " << netPrice << "\n"; cout << "Amount Tended: "; cin >> amountTended;

difference = amountTended - netPrice;

cout << "\n===================================="; cout << "\n-=- Georgetown Cleaning Services -=-"; cout << "\n===================================="; cout << "\nCustomer Order"; cout << "\nCustomer Name: " << customerName;

cout << "\nCustomer Phone: " << customerPhone; cout << "\nOrder Date: " << orderMonth << '/' << orderDay << '/' << orderYear; cout << "\n------------------------------------" << "\nItem Type Unit Price Qty Sub-Total";

cout << "\n------------------------------------" << "\nShirts: " << totalCostShirts << "\nPants: " << totalCostPants << "\nDresses: << dresses << " << "\nTies: totalCostTies; " << priceShirts << " " << pricePants << " " << priceDresses << " " << totalCostDresses " << priceTies << " " << ties << " " << " << shirts << " " << pants << " "

cout << "\n------------------------------------" << "\nTotal Number of Items: " << totalItems

<< "\nTotal Cleaning of Items: " << totalCostCleaning << "\nTax Rate: << "\nTax Amount: << "\nNet Price: << "\nAmount Tended: << "\nDifference: " << taxRate << "%" " << taxAmount " << netPrice " << amountTended " << difference << "\n";

return 0; } 2. Execute the application and perform an order. Here is an example: -=- Georgetown Cleaning Services -=Enter Customer Name: Jeanne Lemarre

Enter Customer Phone: (410) 022-4209 Enter the date this order was placed Order Day: 04

Order Month: 08 Order Year: 2000 Enter number of shirts: 12

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Enter number of pants: 8 Enter number of dresses: 5 Enter number of ties: 3 The total order is: 61.5465 Amount Tended: 100

==================================== -=- Georgetown Cleaning Services -===================================== Customer Order Customer Name: Jeanne Lemarre

Customer Phone: (410) 022-4209 Order Date: 8/4/2000 -----------------------------------Item Type Unit Price Qty Sub-Total

-----------------------------------Shirts: Pants: Dresses: Ties: 1.25 2.75 3.25 1.65 5 3 12 8 15 22 16.25 4.95

-----------------------------------Total Number of Items: 28

Total Cleaning of Items: 58.2 Tax Rate: Tax Amount: Net Price: Amount Tended: Difference: 100 38.4535 5.75% 3.3465 61.5465

3. Return to your programming environment

The Remainder
The division program above will give you a result of a number with decimal values if you type an odd number (like 147), which is fine in some circumstances. Sometimes you will want to get the value remaining after a division renders a natural result. Imagine you have 26 kids at a football (soccer) stadium and they are about to start. You know that you need 11 kids for each team to start. If the game starts with the right amount of players, how many will seat and wait? The remainder operation is performed with the percent sign (%) which is gotten from pressing Shift + 5. Here is an example: // Program used to perform the remainder operation. #include <iostream> using namespace std;

int main() { int players = 26;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
int yourPlayers;

// When the game starts, how many players will wait?. cout << "\nOut of " << players << " players, " << 26 % 11 << " players will have to wait when the " << " football match starts.\n\n";

// Get the new number of players cout << "How many players do you have today? "; cin >> yourPlayers;

cout << "\nOut of " << yourPlayers << " players, " << yourPlayers % 11 << " players will not have a team " << " in the beginning.\n\n";

return 0; }

C++ Operators
As a language, C++ is equipped with non-algebraic operators intended to perform specific operations. We will review some of these operators now; some others need intermediary concepts that we haven't studied and cannot study at this time.

Parentheses
Like most computer languages, C++ uses parentheses to isolate a group of items that must be considered as belonging to one entity. For example, as we will learn soon, parentheses allow a function to delimit the list of its arguments. Parentheses can also be used to isolate an operation or an expression with regard to another operation or expression. For example, when studying the algebraic operations, we saw that the subtraction is not associative and can lead to unpredictable results. In the same way, if your operation involves various operators such as addition(s) and subtraction(s), you can use parentheses to tell the compiler how to proceed with the operations, that is, what operation should (must) be performed first. Consider the following algebraic operation: 154 - 12 + 8 The question here is to know whether you want to subtract the addition of 12 and 8 from 154 or you want to add the difference between 154 and 12 to 8. Using parentheses, you can communique your intentions to the compiler. This is illustrated in the following program: // Using parentheses #include <iostream> using namespace std;

int main() { cout << "(154 - 12) + 8 = " << (154 - 12) + 8 << "\n"; cout << "154 - (12 + 8) = " << 154 - (12 + 8) << "\n";

return 0; }
This would produce:

154 - 12) + 8 = 150

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
154 - (12 + 8) = 134 As you can see, using the parentheses controls how the whole operation would proceed This difference can be even more accentuated if your operation includes 3 or more operators and 4 or more operands.

Square Brackets
Square brackets are mostly used to control the dimension or index of an array. We will learn how to use them when we study arrays.

Curly Brackets
Curly brackets are probably the most used and the most tolerant operators of C++. Fundamentaly, curly brackets are used to create or isolate sections of code. As such they are required to delimit the bodies of functions, classes, structures, exceptions, and namespaces. They are also optionally used in conditional statements. Square brackets are also used to create variable scope. We will view all these uses of square brackets in this book.

Incrementing a Number
We are used to counting numbers such as 1, 2, 3, 4, etc. In reality, when counting such numbers, we are simply adding 1 to a number in order to get the next number in the range. C++ provides a technique of transparently counting such numbers. The simplest technique of incrementing a value consists of adding 1 to it. After adding 1, the value or the variable is (permanently) modified and the variable would hold the new value. This is illustrated in the following example: #include <iostream> using namespace std;

int main() { int value = 12;

cout << "Value = " << value << endl;

value = value + 1; cout << "Value = " << value << endl;

return 0; } This would produce: Value = 12 Value = 13 C++ provides a special operator that takes care of this operation. The operator is called the increment operator and is represented by ++. Instead of writing Value = Value + 1, you can write Value++ and you would get the same result. The above program can be re-written as follows: #include <iostream> using namespace std;

int main()

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ int value = 12;

cout << "Value = " << value << endl; Value++; cout << "Value = " << value << endl;

return 0; } The ++ is called a unary operator because it operates on only one variable. It is used to modify the value of the variable by adding 1 to it. Every time the Value++ is executed, the compiler takes the previous value of the variable, adds 1 to it, and the variable holds the incremented value: #include <iostream> using namespace std;

int main() { int value = 12;

cout << "Value = " << value << endl; value++; cout << "Value = " << value << endl;

value++; cout << "Value = " << value << endl;

value++; cout << "Value = " << value << endl;

return 0; }
This would produce:

Value = 12 Value = 13 Value = 14 Value = 15

Pre and Post-Increment


When using the ++ operator, the position of the operator with regard to the variable it is modifying can be significant. To increment the value of the variable before re-using it, you should position the operator on the left of the variable: #include <iostream> using namespace std;

int main() {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
int value = 12;

cout << "Value = " << value << endl; cout << "Value = " << ++value << endl; cout << "Value = " << value << endl;

return 0; }
This would produce:

Value = 12 Value = 13 Value = 13 When writing ++Value, the value of the variable is incremented before being called. On the other hand, if you want to first use a variable, then increment it, in other words, if you want to increment the variable after calling it, position the ++ operator on the right side of the variable: #include <iostream> using namespace std;

int main() { int value = 12;

cout << "Value = " << value << endl; cout << "Value = " << value++ << endl; cout << "Value = " << value << endl;

return 0; } This would produce: Value = 12 Value = 12 Value = 13

Decrementing Pre and Post-Decrementing


When counting numbers backward, such as 8, 7, 6, 5, etc, we are in fact subtracting 1 from a value in order to get the lesser value. This operation is referred to as decrementing a variable. This operation works as if a variable called Value has its value diminished by 1, as in Value = Value 1: #include <iostream> using namespace std;

int main() { int value = 8;

cout << "Value = " << value << endl; value = value - 1;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "Value = " << value << endl;

return 0; }
This would produce:

Value = 8 Value = 7 As done to increment, C++ provides a quicker way of subtracting 1 from a variable. This is done using the decrement operation, that is --. To use the decrement operator, type on the left or the right side of the variable when this operation is desired. Using the decrement operator, the above program could be written: #include <iostream> using namespace std;

int main() { int value = 8;

cout << "Value = " << value << endl; value--; cout << "Value = " << value << endl;

return 0; } Once again, the position of the operator can be important. If you want to decrement the variable before calling it, position the operator on the left side of the operand. This is illustrated in the following program: #include <iostream> using namespace std;

int main() { int value = 8;

cout << "Value = " << value << endl; cout << "Value = " << --value << endl; cout << "Value = " << value << endl;

return 0; }
This would produce:

Value = 8 Value = 7 Value = 7 If you plan to decrement a variable only after it has been accessed, position the operator on the right side of the variable. Here is an example: #include <iostream>

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
using namespace std;

int main() { int value = 8;

cout << "Value = " << value << endl; cout << "Value = " << value-- << endl; cout << "Value = " << value << endl; }
This would produce:

Value = 8 Value = 8 Value = 7

Techniques of Incrementing and Decrementing a Variable


It is not unusual to add or subtract a constant value to or from a variable. All you have to do is to declare another variable that would hold the new value. Here is an example: #include <iostream> using namespace std;

int main() { double value = 12.75; double newValue;

cout << "Value = " << value << endl; newValue = value + 2.42; cout << "Value = " << newValue << endl;

return 0; } This would produce: Value = 12.75 Value = 15.17 The above technique requires that you use an extra variable in your application. The advantage is that each value can hold its own value although the value of the second variable depends on whatever would happen to the original or source variable. Sometimes in your program you will not need to keep the original value of the source variable. You might want to simply permanently modify the value that a variable is holding. In this case you can perform the addition operation directly on the variable by adding the desired value to the variable. This operation modifies whatever value a variable is holding and does not need an additional variable. To add a value to a variable and change the value that the variable is holding, use the assignment = and the addition + operators to produce a new operator as += Here is an example: #include <iostream> using namespace std;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

int main() { double value = 12.75;

cout << "Value = " << value << endl; value += 4.42; cout << "Value = " << value << endl;

return 0; } This would produce: Value = 12.75 Value = 17.17 To diminish the value of a variable, instead of the addition operation, use the subtraction and apply the same technique. In the above program, the variable can have its value decremented by applying the assignment and the subtraction operations on the variable. This is done with the -= operator. Here is an example: #include <iostream> using namespace std;

int main() { double value = 12.75;

cout << "Value = " << value << endl; value -= 4.42; cout << "Value = " << value << endl;

return 0; }
This would produce:

Value = 12.75 Value = 8.33

Operator Precedence and Direction


When combining operations in C++, there are two aspects involved: an operator's precedence and its direction. If you ask a program to add two numbers, for example 240 + 65, the program will execute the operation by adding 240 to 65; in other words, it would read 240, then +, then 65, and evaluate the result. This is considered as operating from left to right: 240 -> + -> 65. On the other hand, if you ask the program to find the size of a variable, you would write sizeof(FirstName). In this case, the program would first consider the FirstName variable, then it would evaluate the size of that variable; in other words, it first finds out what the variable it is operating on, in this case FirstName. Once it knows the variable that is involved, it would execute the operation. This is considered that the operation is executed from right to left. This process is referred to as the direction of the operation.

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
As you will regularly combine operators on your various calculations, each operation is known for how much it "weighs" as compared to other operators. This is known as its precedence. This means that when a certain operator is combined with another, such as a + b * c, or x / y - z, some operators would execute before others, almost regardless of how you write the operation. That's why an operator could be categorized by its level of precedence.

Previous

Copyright 2002-2005 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
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()

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ 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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
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 students first name would be a word representing a students 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 members applications at a sports club. You can define a function that would request the first and last names; other functions that need a members 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; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
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 students 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.

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
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 functions 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 students first name could be declared as: string FirstName(); Here are examples of declaring functions; some take arguments, some dont: 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 functions 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)

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ double Mon, Tue, Wed, Thu, Fri, TotalHours; cout cout cout cout cout cout << << << << << << endl << FullName << "'s Weekly Hours\n"; "Monday: "; cin >> Mon; "Tuesday: "; cin >> Tue; "Wednesday: "; cin >> Wed; "Thursday: "; cin >> Thu; "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 items purchase price based on the items 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 items 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


Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
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 arguments value and gives it to the calling function. Although the calling function receives the arguments 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 cout cout cout cout << << << << << "\nIn the main() function,"; "\n\tWeekly Hours = " << hours; "\n\tSalary = $" << rate; "\n\tWeekly Salary: $" << hours * rate; "\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;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
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 cout cout cout } 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 cout cout cout } << << << << "\n\nIn the "\n\tWeekly "\n\tSalary "\n\tWeekly Earnings() function,"; Hours = " << thisWeek; = " << salary; Salary= " << thisWeek * Salary; << << << << "\n\nIn the "\n\tWeekly "\n\tSalary "\n\tWeekly Earnings() function,"; Hours = " << thisWeek; = " << salary; 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";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
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.

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

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:

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;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
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; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Exploring Functions
Functions and their Arguments
Constant Arguments
When a function receives an argument, it performs one of two actions with regards to the value of the argument; it might modify the value itself or only use the argument to modify another argument or another of its own variables. If you know that 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. 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() function cannot 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): #include <iostream> using namespace std; float Perimeter(float l, float w) { double p; p = 2 * (l + w); return p; } 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) << "\n\n"; return 0; } This would produce: Rectangle dimensions. Enter the length: 35.55 Enter the width: 28.75 The perimeter of the rectangle is: 2044.12 As you can see, the Perimeter() function does not change the values of the length or the width. To reinforce the purpose of the assignment, you should make this clear to the compiler. 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 just one or more arguments constants, and there is no order on which arguments can be made constant.

Practical Learning: Using Constant Arguments


1. Create a new project in a directory of folder called Constant Arguments 2. If necessary, create a source file. Save the source file as Main.cpp 3. To apply the "constantness" of arguments passed to functions, change the file as follows: #include <iostream> using namespace std;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
// 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 << "Triangle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(base, height, 1) << "mm\n"; return 0; } 4. Test the program: Rectangle Moment of inertia with regard to the X axis: I = 7671.78mm Semi-Circle Moment of inertia with regard to the X axis: I = 9344.28mm Triangle Moment of inertia with regard to the X axis: I = 1917.95mm 5. To use a mix of functions, change the program as follows: #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 double double double

length, height, radius; GetBase(); GetHeight(); GetRadius();

cout << "Enter the dimensions of the rectangle\n"; length = GetBase(); height = GetHeight(); cout << "Rectangle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(Length, Height) << "mm\n\n"; cout << "Enter the radius of the semi-circle\n"; radius = GetRadius();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
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"; length = GetBase(); height = GetHeight(); cout << "\nTriangle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(Length, Height, 1) << "mm\n"; return 0; } double GetBase() { double b; cout << "Enter Base: "; cin >> b; return b; } double GetHeight() { double h; cout << "Enter Height: "; cin >> h; return h; } double GetRadius() { double r; cout << "Enter Radius: "; cin >> r; return r; } 6. Test the program. Here is an example: Enter the dimensions of the rectangle Enter Base: 18.25 Enter Height: 14.15 Rectangle Moment of inertia with regard to the X axis: I = 17235mm Enter the radius of the semi-circle Enter Radius: 15.55 Semi-Circle Moment of inertia with regard to the X axis: I = 22960.5mm Enter the dimensions of the triangle Enter Base: 16.35 Enter Height: 12.75 Triangle Moment of inertia with regard to the X axis: I = 2824.02mm 7. After examining the program, return to your programming environment

An Argument as a Constant Reference


If you pass an argument as reference, the compiler would access the argument from its location. The called function can modify the value of the argument. The advantage is that 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 in the passed). 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;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
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 tiscount = 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; }

Practical Learning: Passing Arguments by Constant References


1. To illustrate the passing of arguments by reference and by constant references, change the program as follows: #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, const int&) {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return b * h * h * h / 12; } int main() { double length, height, radius; void GetBaseAndHeight(double&, double&); void GetRadius(double&); cout << "Enter the dimensions of the rectangle\n"; GetBaseAndHeight(length, height); cout << "Rectangle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(length, height) << "mm\n\n"; cout << "Enter the radius of the semi-circle\n"; GetRadius(radius); 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"; GetBaseAndHeight(length, height); cout << "\nTriangle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(length, height, 1) << "mm\n"; cout << "\n\n"; return 0; } // Passing arguments by reference void GetBaseAndHeight(double& B, double& H) { cout << "Enter Base: "; cin >> B; cout << "Enter Height: "; cin >> H; } void GetRadius(double& R) { cout << "Enter Radius: "; cin >> R; } 2. Test the program. Here is an example: Enter the dimensions of the rectangle Enter Base: 18.85 Enter Height: 15.55 Rectangle Moment of inertia with regard to the X axis: I = 23625.5mm Enter the radius of the semi-circle Enter Radius: 14.25 Semi-Circle Moment of inertia with regard to the X axis: I = 16192.7mm Enter the dimensions of the triangle Enter Base: 8.95 Enter Height: 11.25 Triangle Moment of inertia with regard to the X axis: I = 1061.94mm 3. After testing the program, return to your programming environment 4. To further mix the passing of arguments, change the program as follows: #include <iostream> using namespace std; // Rectangle // This function receives one argument by reference and two arguments // by constant references void MomentOfInertia(double& moment, const double& b, const double& h) { moment = b * h * h * h / 3; } // Semi-Circle // This function receives one argument by reference and one by // constant reference void MomentOfInertia(double& moment, const double& R) { const double PI = 3.14159; moment = R * R * R * R * PI/ 8;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} // Triangle // This function receives one argument by reference, two arguments by // constant references and one argument by value void MomentOfInertia(double& moment, const double& b, const double& h, const int&) { moment = b * h * h * h / 12; } int main() { double length, height, radius, mRectangle, mSemiCircle, mTriangle; void GetBaseAndHeight(double&, double&); void GetRadius(double&); cout << "Enter the dimensions of the rectangle\n"; GetBaseAndHeight(length, height); MomentOfInertia(mRectangle, length, height); cout << "Rectangle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << mRectangle << "mm\n\n"; cout << "Enter the radius of the semi-circle\n"; GetRadius(radius); MomentOfInertia(mSemiCircle, radius); cout << "Semi-Circle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << mSemiCircle << "mm\n\n"; cout << "Enter the dimensions of the triangle\n"; GetBaseAndHeight(length, height); MomentOfInertia(mRectangle, length, height, 1); cout << "\nTriangle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << mRectangle << "mm\n"; cout << "\n\n"; return 0; } // Passing arguments by reference void GetBaseAndHeight(double& b, double& h) { cout << "Enter Base: "; cin >> b; cout << "Enter Height: "; cin >> h; } void GetRadius(double& R) { cout << "Enter Radius: "; cin >> R; } 5. Test the program. Here is an example: Enter the dimensions of the rectangle Enter Base: 12.85 Enter Height: 8.85 Rectangle Moment of inertia with regard to the X axis: I = 2969.01mm Enter the radius of the semi-circle Enter Radius: 5.55 Semi-Circle Moment of inertia with regard to the X axis: I = 372.59mm Enter the dimensions of the triangle Enter Base: 10.75 Enter Height: 6.75 Triangle Moment of inertia with regard to the X axis: I = 275.511mm 6. Return to your programming environment

Functions and Namespaces


Functions Local Definition
Like a variable, a function can be part of a namespace. To declare a function in a namespace, provide its return type, followed by a name, followed by the argument(s), if any, inside of

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
parentheses. Here is an example: namespace InterestAndDiscount { double Principal; double Rate; int Time; double CalculateDiscount(); double CalculateInterest(); double CalculateMaturity(); } A member function of a namespace can be accessed 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> using namespace std; namespace InterestAndDiscount { double Principal; double Rate; int Time; double GetInterestRate() { return Rate / 100; } double CalculateInterest() { return Principal * GetInterestRate() * Time; } double CalculateMaturity() { return Principal + CalculateInterest(); } } int main() { using namespace InterestAndDiscount; Principal = 12500; // $ Rate = 12.25; // % Time = 4; // Years cout << "Interest Calculation"; cout << "\nPrincipal: $" << Principal << "\nRate: " << Rate << "%" << "\nTime: " << Time << " years" << "\nInterest: $" << CalculateInterest() << "\nMaturity: $" << CalculateMaturity() << "\n\n"; return 0; } This would produce: Interest Calculation Principal: $12500 Rate: 12.25% Time: 4 years Interest: $6125 Maturity: $18625 If a nested namespace has its own functions, you can also implement them in the body of the nested namespace. Here is an example: namespace InterestAndDiscount { double Principal; double Rate; int Time; double GetInterestRate() { return Rate / 100; } double CalculateInterest() {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return Principal * GetInterestRate() * Time; } double CalculateMaturity() { return Principal + CalculateInterest(); } namespace Discounter { double Maturity; double DiscountRate; double TermOfDiscount; double Discount() { return Maturity * DiscountRate * TermOfDiscount; } } } After locally implementing the member functions of a nested namespace, you can access its members and display their value in the main() function as done above.

Functions Global Definitions


To implement a member function outside the body of a namespace, provide the return type, followed by the name of the namespace, followed by the scope access operator ::. Here is an example: namespace InterestAndDiscount { double Principal; double Rate; int Time; double GetInterestRate(); double CalculateInterest(); double CalculateMaturity(); } InterestAndDiscount::GetInterestRate() { return Rate / 100; } InterestAndDiscount::CalculateInterest() { return Principal * GetInterestRate() * Time; } InterestAndDiscount::CalculateMaturity() { return Principal + CalculateInterest(); } 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: namespace InterestAndDiscount { double Principal; double Rate; int Time; double GetInterestRate(); double CalculateInterest(); double CalculateMaturity() namespace Discounter { double Maturity; double DiscountRate; double TermOfDiscount; double Discount(); } } . . . InterestAndDiscount::Discounter::Discount() { return Maturity * DiscountRate * TermOfDiscount; }

Namespaces and External Functions


Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
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> using namespace std; namespace InterestAndDiscount { . . . } . . . int main() { using namespace InterestAndDiscount; double GetThePrincipal(); cout << "Loan Processing\n"; cout << "Enter the following values\n"; Principal = GetThePrincipal(); cout << "Rate (between 0 and 100): "; cin >> Rate; cout << "Time (number of years): "; cin >> Time; cout cout cout cout cout cout } double GetThePrincipal() { double P; cout << "Principal: $"; cin >> P; return P; } The member variable of a namespace can also be passed as argument to a function. When passing the argument, if the using namespace routine has been entered, you can pass the argument like any other. Otherwise, you should qualify the namespace member with the :: operator. In the following example, one member of a namespace is passed by its name only because of the previous using namespace. The other members are passed by being qualified, which is for demonstration purposes only: #include <iostream> using namespace std; namespace InterestAndDiscount { . . . } . . . int main() { using namespace InterestAndDiscount; void GetThePrincipal(double& p); void RateAndTime(double &r, double &t); cout << "Loan Processing"; cout << "\nEnter the following values\n"; GetThePrincipal(Principal); RateAndTime(InterestAndDiscount::Rate, InterestAndDiscount::Time); cout cout cout cout cout cout cout cout cout << << << << << << << << << setiosflags(ios::fixed) << setprecision(2); "\nInterest on a loan"; "\nPrincipal: $" << Principal; "\nRate: " << Rate << "%"; setiosflags(ios::fixed) << setprecision(0); "\nTime: " << Time << " years"; setiosflags(ios::fixed) << setprecision(2); "\nInterest: $" << CalcInterest(); "\nMaturity Value: $" << CalcMaturityValue(); << << << << << << "\nInterest on a loan"; "\nPrincipal: $" << Principal; "\nRate: " << Rate << "%"; "\nTime: " << Time << " years"; "\nInterest: $" << CalcInterest(); "\nMaturity Value: $" << CalcMaturityValue();

return 0;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return 0; } void GetThePrincipal(double& P) { cout << "Principal: $"; cin >> P; while( P < 0 ) { cout << "Enter a positive number: $"; cin >> P; } } void RateAndTime(double &rate, double &time) { do { cout << "Rate (between 0 and 100): "; cin >> rate; } while(rate < 0 || rate > 100); do { cout << "Time (Nbr of Years): "; cin >> time; } while(time <= 0 || time >= 30); }

C++ Built-in Functions


Introduction
Although as a smart programmer you can create any function to perform a desired job, the C++ language provides a series of functions already made so you can just add them to your program without caring how they work, all you need to know is what these functions do. The functions that are part of the C++ language are highly valuable, were tested sufficiently, and are completely reliable. The C++ built-in functions are made for various assignments ranging from algebra, geometry, trigonometry, and finance, etc. Besides the functions that are part of the C++ Standard, each compiler ships with its own set of functions that may not be available on other compilers. Borland C++ Builder provides an extremely rich library of functions.

Asserting a Value or an Expression


Most of the values you use in your program will need to fit in an interval of your choice. For example, when requesting the age of a person, you would need such a value to be positive. After all, you do not expect a person to be 26 years old. C++ provides a function that can be used to check that a value or expression responds to a criteria of your choice. This function is called assert() and is defined in the cassert library of the std namespace. Its syntax is: void assert(int Expression); The assert() function considers an expression as its argument and tests it. This function is used in the same context as the conditional statements we will study in the next lesson of this book. If the Expression is true, assert() acknowledges that and lets the compiler continue with the next operation. If the Expression is false, assert() displays a (nasty) message. Although we have not yet learned conditional statements, the following is an example that requests the age of a student and checks that the supplied age is valid only if the student is older than 8: #include <iostream> #include <cassert> using namespace std; int main() { float StudentAge; cout << "Type Student's Age: "; cin >> StudentAge; assert(StudentAge > 8); cout << "Student Age: " << StudentAge << "\n\n"; return 0; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Mathematic Functions
The C++ language also provides a series of functions to perform various mathematically related operations. The functions are defined in various libraries and this can depend on the compiler you are using. The functions defined in the cmath library are: acos asin atan atan2 ceil cos cosh exp fabs floor fmod frexp ldexp log log10 modf pow sin sinh sqrt tan tanh

Additional functions are defined in the cstdlib library and they are: abs div labs ldiv srand rand

Previous

Copyright 1998-2006 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

C++ Projects and Linkage


C++ and Files
Introduction
A computer application is primarily a series of files put together to compose a single entity. With previous generations of programming, you had to create text files, save them with a .c, a .cc, or a .cpp extension, link them and compile them. Many modern programming environments allow you to create the files and hand them to the compiler that would link them as a project, and then create an executable. In reality, the process has not changed, it has only been made easier and faster. Still, because the programming environments are developed by different companies, each presents its own way of creating the necessary files, compiling them, and creating an executable. When writing a program, the main reason for using functions is to isolate assignments. This allows you to effectively troubleshoot problems when they arise (because they will arise, not if but when). For example, if you are asked to write a program that would process orders at a department store, you can write one long main() function that would process all requests and orders. When the store is having a sale and you need to apply a discount to the program, you would spend time looking for the sections that use the discount and calculate the price. If you use functions to isolate assignments, you can easily find out which particular function deals with discount; all you would have to do is change the discount value without having to read the whole program.

Practical Learning: Creating a File


1. Start a new project in your programming environment and name it MomentOfInertia1 2. If necessary, create a new source file. Save the current source file as Exercise.cpp

Header Files
When using functions in a program, we found out that the order of declaring functions was important. For example, you cannot call a function that has not been declared yet. For this reason, whenever you need to call a function, you should find out where it was created or whether it has been declared already. If the program is using many functions, it would become cumbersome to start looking for functions. At the same time, on a large program, it is usual for many functions to use the same kind of variable. Although you can locally declare the same variable needed by a function, if these functions of the same program would need to exchange values among them, you should declare some variables globally, usually on top of the file, then make such a variable available to any function that needs it. To make these functions and variables easily manageable, you can create one file where you would list the functions and variables used in a program. Such a file is called a header file and it has the h extension.

File Preprocessors
As you are creating header files, if you work with a large team, you should avoid including in your program a file that has already been included. C++ allows you to avoid this by asking the compiler to check whether a header or a section of code has already been included in your program. This checking is performed using objects called preprocessors. When using preprocessors to check whether a section of code or a file has already been included in your program, you start the file or the section with
#ifndef WhatToCheck

The preprocessors must start with the # symbol as we have been using on the #include preprocessor so far. The ifndef preprocessor, word for word, means If Not Defined. It refers to the word on its right side to check if that word has already been included. Because the #ifndef is used to check If WhatToCheck has not been defined yet, it can also be written as
#if !define WhatToCheck

Both would mean the same. In reality, what you would be asking this preprocessor to do is to check if the WhatToCheck word has not already been included. If it has not, then you would ask the compiler to define this section of code with the WhatToCheck word. To do this, you would

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
decide that the section of code you want to delimit will be referred to with the WhatToCheck word. Therefore, the #ifndef preprocessor is followed by a
#define WhatToCheck

This means that if WhatToCheck has not been included yet, then it would be defined starting with the #define. The section must end with the #endif preprocessor. This time, you do not need to specify what needs to be ended; the compiler will figure that out.

Source Files
After creating the header file, you can create another file to define the functions. The file used to implement the functions of the header file is called the Source File and it has a cpp extension. In order to use the code that is written in the header file, you must specify its file using the #include preprocessor and including the name of the file in double-quotes. The process of creating header and source files depends on your programming environment.

Practical Learning: Creating a Header File: KDevelop


1. To create a header file, on the main menu, click File -> New 2. On the New File dialog box, in the General tab, click C/C++ Header (*.h,*.hxx) and, in the Filename edit box, type Inertia

3. Make sure that the Add To Project check box is checked and click OK

Practical Learning: Creating a Header File: Borland C++BuilderX


1. On the main menu, click File -> New File... 2. In the Create New File dialog box, set the Name to Inertia 3. In the Type combo box, select h

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

4. Click OK

Practical Learning: Creating a Header File: Borland C++ Builder 6


1. To create a header file, from the main menu of Borland C++ Builder, click File -> New -> Other 2. From the New Items dialog box, click Header File

3. Click OK By default, the first header file of C++ Builder is named File1.h and the subsequent names are incremental. If you want to change the name of the file, you must save it and give it the desired name 4. Save the file as Inertia.h

Practical Learning: Creating a Header File: Microsoft Visual C++


1. To create a header file in Microsoft Visual C++ 5 and 6, on the main menu, click File -> New 2. From the Files property page of the New dialog box, click C/C++ Header FileType a name in the File Name edit box as Inertia 3. Click OK

Practical Learning: Creating a Header File: Dev-C++


1. To create a header file in Dev-C++, on the main menu, click File -> New Source File 2. On the main menu, click File -> Save Unit 3. In the Save File dialog box, change the File As Type combo box to Header File (.h) and type the desired name of the file in the File Name text box as Inertia

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
4. Click Save

Practical Learning: Creating a Header File: Microsoft Visual C++ .Net


1. To create a header file in Microsoft Visual C++ .Net, on the main menu, click Project -> Add New Item 2. In the Add New Item dialog box, make sure the Visual C++ node is selected in the Categories tree view. In the Templates, click Header File 3. In the Name text box, type Inertia 4. Click Open In all cases, replace the contents of the file with the following:
#ifndef _INERTIA_H_ #define _INERTIA_H_

double MomentOfInertia(const double b, const double h); double MomentOfInertia(const double R); double MomentOfInertia(const double b, const double h, const int); double GetBase(); double GetHeight(); double GetRadius();

#endif // INERTIA_H_

Source Files
A source file is used to actually define the behavior of an object. This is also referred to as implementing the object. The creation of a source file also depends on the programming environment.

Practical Learning: Creating a Source File: Borland C++ BuilderX


1. On the main menu, click File -> New File... 2. In the Create New File dialog box, set the Name to Inertia 3. In the Type combo box, select cpp

4. Click OK

Practical Learning: Creating a Source File: KDevelop


1. To create a source file, on the main menu, click File -> New

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
2. In the New File dialog box, click C/C++ File (*.cpp,*.c,*.cc,*.C ) 3. In the Filename edit box, type Inertia 4. Make sure that the the Add To Project check box is selected and click OK

Practical Learning: Creating a Source File: Borland C++ Builder


1. To create a source file, from the main menu of Borland C++ Builder, click File -> New -> Other 2. From the New Items dialog box, click Cpp File 3. Click OK 4. Save the file as as Inertia.cpp

Practical Learning: Creating a Source File: Microsoft Visual C++


1. To create a source file in Microsoft Visual C++ 5 and 6, on the main menu, click File -> New 2. From the Files property page of the New dialog box, click C++ Source File 3. Type a name in the File Name edit box 4. Click OK

Practical Learning: Creating a Source File: Dev-C++


1. To create a header file in Dev-C++, on the main menu, click File -> New Source File 2. On the main menu, click File -> Save Unit 3. In the Save File dialog box, make sure the File As Type combo box displays C++ Source File (.cpp). Type the desired name of the file in the File Name text box as Inertia.cpp (either make sure that the dialog box does not add the .h extension or append the .cpp extension): 4. Click Save

Practical Learning: Creating a Source File: Microsoft Visual C++ .Net


1. To create a source file in Microsoft Visual C++ .Net, on the main menu, click Project -> Add New Item 2. In the Add New Item dialog box, make sure the Visual C++ node is selected in the Categories tree view. In the Templates, click C++ File (.cpp) (it should be selected by default 3. In the Name text box, type Inertia as the name of the file and click Open In all cases, replace the contents of the file with the following:
#include <iostream> using namespace std;

#include "Inertia.h"

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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

// 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, const int) { return b * h * h * h / 12; }

double GetBase() { double b;

cout << "Base: "; cin >> b;

return b; }

double GetHeight() { double h;

cout << "Height: "; cin >> h;

return h; }

double GetRadius() { double r;

cout << "Radius: "; cin >> r;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return r; }

1. To prepare the application for a test, in the Main.cpp file, type the following:
#include <iostream> #include <string> using namespace std;

#include "Inertia.h"

void Announce(const string Figure) { cout << "Enter the dimensions of the " << Figure << "\n"; }

int main() { double Length, Height, Radius;

Announce("rectangle"); Length = GetBase(); Height = GetHeight(); cout << "Rectangle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(Length, Height) << "mm\n\n";

Announce("semi-circle"); Radius = GetRadius(); cout << "Semi-Circle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(Radius) << "mm\n\n";

Announce("triangle"); Length = GetBase(); Height = GetHeight();

cout << "\nTriangle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(Length, Height, 1) << "mm\n";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return 0; }

2. Save the project and test it. Here is an example

Variable External Linkage


We saw that you could use different files in the same program. In our header files, we declared only functions. In many cases, you can also declare one or more variables in a (header) file and want to access such a variable in another file. After declaring a variable in one file, you can access it in any other file. This process is referred to as external linkage. To perform external linkage with a variable, in most cases, there is not much to do: you simply declare and optionally initialize a variable in one file, #include that file in another file, and use the variable as you see fit. Consider the following example: Header File: Exercise.h
#ifndef Exercise_H #define Exercise_H

int numberOfPagesInTheBook = 842;

#endif // Exercise_H

Source File: Exercise.cpp


#ifdef __BORLANDC__ #pragma argsused #endif #include <iostream> #include "Exercise.h" using namespace std; int main( int argc, char * argv[] ) { cout << "This book contains " << numberOfPagesInTheBook << " pages"; } return 0;

This would produce:


This book contains 842 pages

Imagine that, before accessing such a variable, you declare another variable of the same data type and the same name. Consider the following example: Header File: Exercise.h
#ifndef Exercise_H #define Exercise_H int numberOfPagesInTheBook = 842; #endif // Exercise_H

Source File: Exercise.cpp


#ifdef __BORLANDC__ #pragma argsused #endif #include <iostream> #include "Exercise.h" using namespace std; int main( int argc, char * argv[] ) { int numberOfPagesInTheBook; cout << "This book contains " << numberOfPagesInTheBook << " pages"; return 0;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Since a file included, in this case Exercise.h, has a variable with the same name as a locally declared variable, when you try accessing it locally, the compiler would consider the local variable and would ignore the external variable. The above code would produce:
This book contains 8856072 pages

(This result is from Borland C++BuilderX) To indicate that the newly declared variable is simply a reference to the external variable, when re-declaring it, start the declaration with the extern keyword:
#ifdef __BORLANDC__ #pragma argsused #endif #include <iostream> #include "Exercise.h" using namespace std; int main( int argc, char * argv[] ) { extern int numberOfPagesInTheBook; cout << "This book contains " << numberOfPagesInTheBook << " pages"; } return 0;

This time, it is the external variable that will be accessed.

References
Referenced Variables
A reference is a variable name that is a duplicate of an existing variable. It provides a technique of creating more than one name to designate the same variable. To declare a reference variable, you use the reference operator expressed with the ampersand. The syntax of creating or declaring a reference is:
DataType &RefernceName = VariableName;

To declare a reference, type the variables name preceded by the same type as the variable it is referring to. Between the data type and the reference name, type the ampersand operator &. To specify what variable the reference is addressed to, use the assignment operator = followed by the name of the variable. The referred to variable must exist already. You cannot declare a reference as:
int &mine;

The compiler must know what variable you are referring to. Here is an example:
#include <iostream> using namespace std; int main() { int number = 228; int &nbr = number; } return 0;

The ampersand operator between the data type and the variable name can assume one of three positions as follows:
int& nbr; int & nbr; int &nbr;

As long as the & symbol is between a valid data type and a variable name, the compiler knows that the variable name (in this case Nbr) is a reference.

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Once a reference has been initialized, it holds the same value as the variable it is referring to. You can then display the value of the variable using either of both:
#include <iostream> using namespace std; int main() { int number = 228; int & nbr = number; cout << "Number = " << number << "\n"; cout << "Its reference = " << nbr << "\n\n"; } return 0;

If you change the value of the variable, the compiler updates the value of the reference so that both variables would hold the same value. In the same way, you can modify the value of the reference, which would update the value of the referred to variable. To access the reference, do not use the ampersand operator; just the name of the reference is sufficient to the compiler. This is illustrated in the following:
#include <iostream> using namespace std; int main() { int number = 228; // Regular variable int& nbr = number; // Reference cout << "Number = " << number << "\n"; cout << "Its reference = " << nbr << "\n"; // Changing the value of the original variable number = 4250; cout << "\nNumber = " << number; cout << "\nIts reference = " << nbr << "\n"; // Modifying the value of the reference Nbr = 38570; cout << "\nNumber = " << number; cout << "\nIts reference = " << nbr << "\n\n"; } return 0;

In the same way, you can use either a reference or the variable it is referring to, to request the variables value from the user. Here is an example:
#include <iostream> using namespace std; int main() { double price; double& refPrice = price; cout << "What's the price? $"; cin >> price; cout << "Price = $" << price << "\n"; cout << "Same as: $" << refPrice << "\n\n"; cout << "What's the price? $"; cin >> refPrice; cout << "Price = $" << price << "\n"; cout << "Same as: $" << refPrice << "\n"; } return 0;

If you change the value of the variable, the compiler updates the value of the reference so that both variables would hold the same value. In the same way, you can modify the value of the reference, which would update the value of the referred to variable. To access the reference, do not use the ampersand operator; just the name of the reference is sufficient to the compiler. This is illustrated in the following:
#include <iostream> using namespace std;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
main() { int Number = 228; // Regular variable int& Nbr = Number; // Reference cout << "Number = " << Number << "\n"; cout << "Its reference = " << Nbr << "\n"; // Changing the value of the original variable Number = 4250; cout << "\nNumber = " << Number; cout << "\nIts reference = " << Nbr << "\n"; // Modifying the value of the reference Nbr = 38570; cout << "\nNumber = " << Number; cout << "\nIts reference = " << Nbr << "\n\n";

In the way, you can use either a reference or the variable it is referring to, to request the variables value from the user. Here is an example:
#include <iostream> using namespace std; main() { double Price; double& RefPrice = Price; cout << "What's the price? $"; cin >> Price; cout << "Price = $" << Price << "\n"; cout << "Same as: $" << RefPrice << "\n\n"; cout << "What's the price? $"; cin >> RefPrice; cout << "Price = $" << Price << "\n"; cout << "Same as: $" << RefPrice << "\n";

Referenced Functions
A function can be made to return a reference to a value. When defining such a function, make sure you type the reference operator to its left. After processing the function in its body, you must make sure you return a value that is a reference of the same type of the function. Here is an example:
#ifdef __BORLANDC__ #pragma argsused #endif #include <iostream> using namespace std; int &GetNumberOfPages() { int pp = 842; int &pages = pp; } return pages;

int main( int argc, char * argv[] ) { cout << "This book contains " << GetNumberOfPages() << " pages"; return 0; }

If the function is not modifying any value it may have received, you can declare it as a constant:
#ifdef __BORLANDC__ #pragma argsused

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#endif #include <iostream> using namespace std; const int &GetNumberOfPages() { int pp = 842; int &pages = pp; } return pages;

int main( int argc, char * argv[] ) { cout << "This book contains " << GetNumberOfPages() << " pages"; } return 0;

Static Variables and Functions


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 cout cout cout << << << << "y "a "b "b = " << y << endl; = " << a << endl; = " << b << endl; / a = " << b / a << "\n\n";

int main() { Starter(2); Starter(2); Starter(2); Starter(2); } return 0;

When executed, this program would produce:


y a b b y a b b y a b b y a b b =2 = 56.25 = 177.25 / a = 3.15111 =2 = 56.25 = 177.25 / a = 3.15111 =2 = 56.25 = 177.25 / a = 3.15111 =2 = 56.25 = 177.25 / a = 3.15111

The Starter() function receives one argument passed when it is called. The called function also

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
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 body 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 static keyword on the left of the variables 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; }

When you declare a variable as static, it is initialized with a 0 value. Otherwise, you can initialize it with a value of your choice 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 cout cout cout << << << << "y "a "b "b = " << y << endl; = " << a << endl; = " << b << endl; / a = " << b / a << "\n\n";

This time, when executing the program, it would produce:


y a b b y a b b y a b b y a b b =2 = 56.25 = 177.25 / a = 3.15111 =2 = 28.125 = 179.25 / a = 6.37333 =2 = 14.0625 = 181.25 / a = 12.8889 =2 = 7.03125 = 183.25 / a = 26.0622

Notice that, this time, each local variable keeps its newly changed value when the function exits. Since a functions 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;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
b = b + 2; cout cout cout cout << << << << "y "a "b "b = " << y << endl; = " << a << endl; = " << b << endl; / 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 a b b y a b b y a b b y a b b =2 = 56.25 = 177.25 / a = 3.15111 =5 = 11.25 = 179.25 / a = 15.9333 = 14 = 0.803571 = 181.25 / a = 225.556 = 25 = 0.0321429 = 183.25 / a = 5701.11

Static Functions
Like a variable, a function also can be declared and/or defined as static. Here is an example:
#ifdef __BORLANDC__ #pragma argsused #endif #include <iostream> // #include "Exercise.h" using namespace std; static int GetNumberOfPages() { int pages = 842; } return pages;

int main( int argc, char * argv[] ) { cout << "This book contains " << GetNumberOfPages() << " pages"; } return 0;

Previous

Copyright 1998-2005 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Logical Comparisons
Logical Operators
Introduction
A program is a series of instructions that ask the computer (actually the compiler) to check some situations and to act accordingly. To check such situations, the computer spends a great deal of its time performing comparisons between values. A comparison is a Boolean operation that produces a true or a false result, depending on the values on which the comparison is performed. A comparison is performed between two values of the same type; for example, you can compare two numbers, two characters, or the names of two cities. On the other hand, a comparison between two disparate values doesn't bear any meaning. For example, it is difficult to compare a telephone number and somebody's age, or a music category and the distance between two points. Like the binary arithmetic operations, the comparison operations are performed on two values. Unlike arithmetic operations where results are varied, a comparison produces only one of two results. The result can be a logical true or false. When a comparison is true, it has an integral value of 1 or positive; that is, a value greater than 0. If the comparison is not true, it is considered false and carries an integral value of 0. The C++ language is equipped with various operators used to perform any type of comparison between similar values. The values could be numeric, strings, or objects (operations on objects are customized in a process referred to as Operator Overloading).

The Equality Operator ==


To compare two variables for equality, C++ uses the == operator. Its syntax is: Value1 == Value2 The equality operation is used to find out whether two variables (or one variable and a constant) hold the same value. From our syntax, the compiler would compare the value of Value1 with that of Value2. If Value1 and Value2 hold the same value, the comparison produces a true result. If they are different, the comparison renders false or 0.

Most of the comparisons performed in C++ will be applied to conditional statements; but because a comparison operation produces an integral result, the result of the comparison can be displayed on the monitor screen using a cout extractor. Here is an example:

#include <iostream> using namespace std;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
int main() { int Value = 15; cout << "Comparison of Value == 32 produces " << (Value == 32) << "\n\n"; return 0; } The result of a comparison can also be assigned to a variable. As done with the cout extractor, to store the result of a comparison, you should include the comparison operation between parentheses. Here is an example:

#include <iostream> using namespace std; int main() { int Value1 = 15; int Value2 = (Value1 == 24); cout << "Value 1 = " << Value1 << "\n"; cout << "Value 2 = " << Value2 << "\n"; cout << "Comparison of Value1 == 15 produces " << (Value1 == 15) << "\n\n"; return 0; } This would produce: Value 1 = 15 Value 2 = 0 Comparison of Value1 == 15 produces 1

Very important The equality operator and the assignment operator are different. When writing StudentAge = 12, this means the constant value 12 is assigned to the variable StudentAge. The variable StudentAge can change anytime and can be assigned another value. The constant 12 can never change and is always 12. The variable StudentAge is usually on the left side of the assignment operator. A constant, such as 12, is always on the right side and can never be on the left side of the assignment operator. This means you can write StudentAge = 12 but never 12 = StudentAge because when writing StudentAge = 12, you are modifying the variable StudentAge from any previous value to 12. Attempting to write 12 = StudentAge means you want to modify the constant integer 12 and give it a new value which is StudentAge: you would receive an error.NumberOfStudents1 == NumberOfStudents2 means both variables exactly mean the same thing. Whether using the first or the second, the compiler considers each as meaning the other.

The Logical Not Operator !


When a variable is declared and receives a value (this could be done through initialization or a change of value) in a program, it becomes alive. It can then participate in any necessary operation. The compiler keeps track of every variable that exists in the program being processed. When a variable is not being used or is not available for processing (in visual programming, it would be considered as disabled) to make a variable (temporarily) unusable, you can nullify its value. C++ considers that a variable whose value is null is stern. To render a variable unavailable during the evolution of a program, apply the logical not operator which is !. Its syntax is: !Value There are two main ways you can use the logical not operator. As we will learn when studying conditional statements, the most classic way of using the logical not operator is to check the state of a variable. To nullify a variable, you can write the exclamation point to its left. When used like that, you can display its value using the cout extractor. You can even assign it to another variable. Here

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
is an example:

#include <iostream> using namespace std; int main() { int Value1 = 250; int Value2 = 32; int Value3 = !Value1; // Display the value of a variable cout << "Value1 = " << Value1 << "\n"; // Logical Not a variable and display its value cout << "!Value2 = " << !Value2 << "\n"; // Display the value of a variable that was logically "notted" cout << "Value3 = " << Value3 << "\n"; return 0; } When a variable holds a value, it is "alive". To make it not available, you can "not" it. When a variable has been "notted", its logical value has changed. If the logical value was true, which is 1, it would be changed to false, which is 0. Therefore, you can inverse the logical value of a variable by "notting" or not "notting" it. This is illustrated in the following example:

#include <iostream> using namespace std; int main() { int Value1 = 482; int Value2 = !Value1; cout << " Value1 = " << Value1 << "\n"; cout << " Value2 = " << Value2 << "\n"; cout << "!Value2 = " << !Value2 << "\n\n"; return 0; }

The Inequality Operator !=


As opposed to Equality, C++ provides another operator used to compare two values for inequality. This operation uses a combination of equality and logical not operators. It combines the logical not ! and a simplified == to produce !=. Its syntax is: Value1 != Value2 The != is a binary operator (like all logical operator except the logical not, which is a unary operator) that is used to compare two values. The values can come from two variables as in Variable1 != Variable2. Upon comparing the values, if both variables hold different values, the comparison produces a true or positive value. Otherwise, the comparison renders false or a null value.

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Here is an example:

#include <iostream> using namespace std; int main() { int Value1 = 212; int Value2 = -46; int Value3 = (Value1 != Value2); cout << "Value1 = " << Value1 << "\n"; cout << "Value2 = " << Value2 << "\n"; cout << "Value3 = " << Value3 << "\n\n"; return 0; } The inequality is obviously the opposite of the equality.

The Comparison for a Lower Value <


To find out whether one value is lower than another, use the < operator. Its syntax is: Value1 < Value2 The value held by Value1 is compared to that of Value2. As it would be done with other operations, the comparison can be made between two variables, as in Variable1 < Variable2. If the value held by Variable1 is lower than that of Variable2, the comparison produces a true or positive result.

Here is an example:

#include <iostream> using namespace std; int main() { int Value1 = 15; int Value2 = (Value1 < 24); cout << "Value 1 = " << Value1 << "\n"; cout << "Value 2 = " << Value2 << "\n\n"; return 0; }

Combining Equality and Lower Value <=


The previous two operations can be combined to compare two values. This allows you to know if two values are the same or if the first is less than the second. The operator used is <= and its syntax is:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Value1 <= Value2 The <= operation performs a comparison as any of the last two. If both Value1 and Value2 hold the same value, the result is true or positive. If the left operand, in this case Value1, holds a value lower than the second operand, in this case Value2, the result is still true.

Here is an example:

#include <iostream> using namespace std; int main() { int Value1 = 15; int Value2 = (Value1 <= 24); cout << "Value 1 = " << Value1 << "\n"; cout << "Value 2 = " << Value2 << "\n\n"; return 0; }

The Comparison for a Greater Value >


When two values of the same type are distinct, one of them is usually higher than the other. C++ provides a logical operator that allows you to find out if one of two values is greater than the other. The operator used for this operation uses the > symbol. Its syntax is: Value1 > Value2 Both operands, in this case Value1 and Value2, can be variables or the left operand can be a variable while the right operand is a constant. If the value on the left of the > operator is greater than the value on the right side or a constant, the comparison produces a true or positive value . Otherwise, the comparison renders false or null.

The Greater Than or Equal Operator >=


The greater than and the equality operators can be combined to produce an operator as follows: >=. This is the "greater than or equal to" operator. Its syntax is: Value1 >= Value2 A comparison is performed on both operands: Value1 and Value2. If the value of Value1 and

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
that of Value2 are the same, the comparison produces a true or positive value. If the value of the left operand is greater than that of the right operand, the comparison produces true or positive also. If the value of the left operand is strictly less than the value of the right operand, the comparison produces a false or null result.

Here is a summary table of the logical operators we have studied: Operator == != < <= > >= Meaning Equality to Not equal to Less than Less than or equal to Greater than Greater than or equal to Example a == b 12 != 7 25 < 84 Cab <= Tab 248 > 55 Val1 >= Val2 Opposite != == >= > <= <

Accessories for Logical Conditions


Boolean Variables
The Boolean data type is used to declare a variable whose value would be set as true (1) or false (0). To declare such a value, you use the bool keyword. The variable can then be initialized with a starting value. The Boolean constant is used to check that the state of a variable (or a function) is true or false. You can declare such a variable as: bool GotThePassingGrade = true; Later in the program, for a student who got a failing grade, you can assign the other value, like this GotThePassingGrade = false; Here is an example: #include <iostream> using namespace std; int main() { bool MachineIsWorking = true; cout << "Since this machine is working, its value is " << MachineIsWorking << endl; MachineIsWorking = false; cout << "The machine has stopped operating. " << "Now its value is " << MachineIsWorking << endl; return 0; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Enumerations
An enumeration provides a technique of setting a list of integers where each item of the list is ranked and has a specific name. For example, instead of numbers that represent players of a football (soccer) game such as 1, 2, 3, 4, 5, you can use names instead. This would produce GoalKeeper, RightDefender, LeftDefender, Stopper, Libero. The syntax of creating an enumeration is enum Series_Name {Item1, Item2, Item_n}; In our example, the list of players by their name or position would be enum Players { GoalKeeper, RightDefender, LeftDefender, Stopper, Libero }; Each name in this list represents a constant number. Since the enumeration list is created in the beginning of the program, or at least before using any of the values in the list, each item in the list is assigned a constant number. The items are counted starting at 0, then 1, etc. By default, the first item in the list is assigned the number 0, the second is 1, etc. Just like in a game, you do not have to follow a strict set of numbers. Just like a goalkeeper could have number 2 and a midfielder number 22, you can assign the numbers you want to each item, or you can ask the list to start at a specific number. In our list above, the goalkeeper would have No. 0. To make the list start at a specific number, assign the starting value to the first item in the list. Here is an example: enum Players { GoalKeeper = 12, RightDefender, LeftDefender, Stopper, Libero }; This time, the goalkeeper would be No. 12, the RightDefender would be No. 13, etc. You still can assign any value of your choice to any item in the list, or you can set different ranges of values to various items. You can create a list like this: enum Days { Mon, Tue, Wed, Thu, Fri, Sat, Sun = 0 }; Since Sun is No. 0, Sat would be No. 1, Fri would be 2 and so on. On the other hand, you can set values to your liking. Here is an example: enum Colors { Black = 2, Green = 4, Red = 3, Blue = 5, Gray, White = 0 }; In this case, the Gray color would be 6 because it follows Blue = 5. Once the list has been created, the name you give to the list, such as Players, becomes an identifier of its own, and its can be used to declare a variable. Therefore, a variable of the enumerated type would be declared as: Series_Name Variable; You can declare more than one variable of such a type. An example of the type of our list of players would be: Players Defense, Midfield, Attack; Players HandBall, BasketBall, VolleyBall; Instead of declaring variables after the list has been created, you can declare the variables of that type on the right side of the list but before the closing semi-colon. Here is an example of a color enumeration and variables declared of that type: enum Flags {Yellow, Red, Blue, Black, Green, White} Title, Heading1, BottomLine; #include <iostream> using namespace std; main() { enum PizzaSize {psSmall, psMedium, psLarge, psJumbo}; cout cout cout cout } To assign your own values to the list, you could change the enumeration as follows: << << << << "The "The "The "The small pizza has a value of " << psSmall << endl; medium pizza has a value of " << psMedium << endl; large pizza has a value of " << psLarge << endl; jumbo pizza has a value of " << psJumbo << endl;

PizzaSize {psSmall = 4, psMedium = 10, psLarge = 16, psJumbo = 24};

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
enum To get the starting as you want, change the enumeration as follows: #include <iostream> using namespace std; main() { enum PizzaSize {psSmall = 4, psMedium, psLarge, psJumbo}; cout cout cout cout }
This would produce:

<< << << <<

"The "The "The "The

small pizza has a value of " << psSmall << endl; medium pizza has a value of " << psMedium << endl; large pizza has a value of " << psLarge << endl; jumbo pizza has a value of " << psJumbo << endl;

The The The The

small pizza has a value of 4 medium pizza has a value of 5 large pizza has a value of 6 jumbo pizza has a value of 7

Press any key to continue... To assign values at random, you could change the list of pizzas as follows: enum PizzaSize {psSmall = 2, psMedium, psLarge = 14, psJumbo = -5}; This would produce: The The The The small pizza has a value of 2 medium pizza has a value of 3 large pizza has a value of 14 jumbo pizza has a value of -5

Press any key to continue...

Previous

Copyright 2002-2009FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Conditional Statements
Conditions
Overview of Conditions
When programming, you will ask the computer to check various kinds of situations and to act accordingly. The computer performs various comparisons of various kinds of statements. These statements come either from you or from the computer itself, while it is processing internal assignments. Lets imagine you are writing an employment application and one question would be, "Do you consider yourself a hot-tempered individual?" The source file of such a program would look like this: #include <iostream> using namespace std; int main() { char Answer; cout << "Do you consider yourself a hot-tempered individual? "; cin >> Answer; return 0; } Some of the answers a user would type are y, yes, Y, Yes, YES, n, N, no, No, NO, I dont know, Sometimes, Why are you asking?, and What do you mean? The variety of these different answers means that you should pay attention to how you structure your programs, you should be clear to the users.

A better version of the line that asks the question would be: cout << "Do you consider yourself a hot-tempered individual? (y=Yes/n=No)"; This time, although the user can still type anything, at least you have specified the expected answers.

Introduction to Conditional Statements


There are three entities that participate on a traffic light: the lights, the human beings who interact with the light, and the law. The road provides a platform on which these components come together. The Traffic Light Everything taken into consideration, a traffic light is made of three light colors: Green Yellow/Orange Red. When the light is green, the road is clear for moving in. The red light signals to stop and wait. A yellow light means, Be careful, it is not safe to proceed right now. Maybe you should wait. When it is

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

not blinking, the yellow light usually serves as a transition period from green to red. There is no transition from red to green. The Drivers There are two main categories of people who deal with the traffic light: the drivers and the walkers. To make our discussion a little simpler, we will consider only the driver. When the light is green, a driver can drive through. When the light is red, the driver is required to stop and wait. The Law Rules and regulations dictate that when a driver does not obey the law by stopping to a red light, he is considered to have broken the law and there is a consequence. The most independent of the three entities is the traffic light. It does not think, therefore it does not make mistakes. It is programmed with a timer or counter that directs it when to act, that is, when to change lights. The second entity, the driver, is a human being who can think and make decisions based on circumstances that are beyond human understanding. A driver can decide to stop at a green light or drive through a red light A driver who proceeds through a red light can get a ticket depending on one of two circumstances: either a police officer caught him hand-in-the-basket or a special camera took a picture. Worse, if an accident happens, this becomes another story. The traffic light is sometimes equipped with a timer or counter. We will call it Timer T. It is equipped with three lights: Green, Yellow, and Red. Lets suppose that the light stays green for 45 seconds, then its turns and stays yellow for 5 seconds, and finally it turns and stays red for 1 minute = 60 seconds. At one moment in the day, the timer is set at the beginning or is reset and the light is green: T = 0. Since the timer is working fine, it starts counting the seconds 1, 2, 3, 4, 45. The light will stay green from T = 0 to T = 45. When the timer reaches 45, the timer is reset to 0 and starts counting from 0 until it reaches 5; meanwhile, Color = Yellow.

if a Condition is True
In C++, comparisons are made from a statement. Examples of statements are: "You are 12 years old" "It is raining outside" You live in Sydney" When a driver comes to a traffic light, the first thing he does is to examine the light's color. There are two values the driver would put together: The current light of the traffic and the desired light of the traffic. Upon coming to the traffic light, the driver would have to compare the traffic light variable with a color he desires the traffic light to have, namely the green light (because if the light is green, then the driver can drive through). The comparison is performed by the driver making a statement such as "The light is green". After making a statement, the driver evaluates it and compares it to what must be true. When a driver comes to a traffic light, he would likely expect the light to be green. Therefore, if the light is green (because that is what he is expecting), the result of his examination would receive the Boolean value of TRUE. This produces the following table: Color Statement The light is green Boolean Value true

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

One of the comparisons the computer performs is to find out if a statement is true (in reality, programmers (like you) write these statements and the computer only follows your logic). If a statement is true, the computer acts on a subsequent instruction. The comparison using the if statement is used to check whether a condition is true or false. The syntax to use it is: if(Condition) Statement; If the Condition is true, then the compiler would execute the Statement. The compiler ignores anything else:

If the statement to execute is (very) short, you can write it on the same line with the condition that is being checked. Consider a program that is asking a user to answer Yes or No to a question such as "Are you ready to provide your credit card number?". A source file of such a program could look like this: #include <iostream> using namespace std; int main() { char Answer; // Request the availability of a credit card from the user cout << "Are you ready to provide your credit card number(1=Yes/0=No)? "; cin >> Answer; // Since the user is ready, let's process the credit card transaction if(Answer == '1') cout << "\nNow we will get your credit card information.\n"; cout << "\n"; return 0; } You can write the if condition and the statement on different lines; this makes your program easier to read. The above code could be written as follows: #include <iostream> using namespace std; int main() { char Answer; // Request the availability of a credit card from the user cout << "Are you ready to provide your credit card number(1=Yes/0=No)? "; cin >> Answer; // Since the user is ready, let's process the credit card transaction if(Answer == '1') cout << "\nNow we will get your credit card information.\n"; cout << "\n"; return 0; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
You can also write the statement on its own line if the statement is too long to fit on the same line with the condition. Although the (simple) if statement is used to check one condition, it can lead to executing multiple dependent statements. If that is the case, enclose the group of statements between an opening curly bracket { and a closing curly bracket }. Here is an example: #include <iostream> using namespace std; int main() { char Answer; char CreditCardNumber[40]; // Request the availability of a credit card from the user cout << "Are you ready to provide your credit card number(1=Yes/0=No)? "; cin >> Answer; // Since the user is ready, let's process the credit card transaction if(Answer == '1') { cout << "\nNow we will continue processing the transaction."; cout << "\nPlease enter your credit card number without spaces: "; cin >> CreditCardNumber; } cout << "\n"; return 0; } If you omit the brackets, only the statement that immediately follows the condition would be executed. When studying logical operators, we found out that if a comparison produces a true result, it in fact produces a non zero integral result. When a comparison leads to false, its result is equivalent to 0. You can use this property of logical operations and omit the comparison if or when you expect the result of the comparison to be true, that is, to bear a valid value. This is illustrated in the following program: #include <iostream> using namespace std; int main() { int Number; cout << "Enter a non zero number: "; cin >> Number; if(Number) cout << "\nYou entered " << Number << endl; cout << endl; return 0; }

Using the Logical Not


When a driver comes to a light that he expects to be green, we saw that he would use a statement such as, "The light is green". If in fact the light is green, we saw that the statement would lead to a true result. If the light is not green, the "The light is green" statement produces a false result. This is shown in the following table: Color Statement The light is green The light is green Boolean Value true false

As you may realize already, in Boolean algebra, the result of performing a comparison depends on how the Condition is formulated. If the driver is approaching a light that he is expecting to display any color other than green, he would start from a statement such as "The light is not green". If the light IS NOT green, the expression "The light is not green" is true (very important). This is illustrated in the following table:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Color Statement The light is green The light is not green Boolean Value true true

The "The light is not green" statement is expressed in Boolean algebra as Not the light is green. Instead of writing Not the light is green", in C++, using the logical Not operator , you would formulate the statement as, !"The light is green". Therefore, if P means The light is green, you can express the negativity of P as !P. The Boolean table produced is: Color Statement The light is green The light is not green Boolean Value true false Symbol P !P

When a statement is true, its Boolean value is equivalent to a non-zero integer such as 1. Otherwise, if a statement produces a false result, it is given a 0 value. Therefore, our table would be: Color Statement The light is green The light is not green Boolean Value true false Integer Value 1 0

Otherwise: ifelse
The if condition is used to check one possibility and ignore anything else. Usually, other conditions should be considered. In this case, you can use more than one if statement. For example, on a program that asks a user to answer Yes or No, although the positive answer is the most expected, it is important to offer an alternate statement in case the user provides another answer. Here is an example:

#include <iostream> using namespace std; int main() { char Answer; cout << "Do you consider yourself a hot-tempered individual(y=Yes/n=No)? "; cin >> Answer; if( Answer == 'y' ) // First Condition { cout << "\nThis job involves a high level of self-control."; cout << "\nWe will get back to you.\n"; } if( Answer == 'n' ) // Second Condition cout << "\nYou are hired!\n"; return 0; } The problem with the above program is that the second if is not an alternative to the first, it is just another condition that the program has to check and execute after executing the first. On that program, if the user provides y as the answer to the question, the compiler would execute the content of its statement and the compiler would execute the second if condition. You can also ask the compiler to check a condition; if that condition is true, the compiler will execute the intended statement. Otherwise, the compiler would execute alternate statement.

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
This is performed using the syntax: if(Condition) Statement1; else Statement2;

The above program would better be written as: #include <iostream> using namespace std; int main() { char Answer; cout << "Do you consider yourself a hot-tempered individual(y=Yes/n=No)? "; cin >> Answer; if( Answer == 'y' ) // One answer { cout << "\nThis job involves a high level of self-control."; cout << "\nWe will get back to you.\n"; } else // Any other answer cout << "\nYou are hired!\n"; return 0; }

The Ternary Operator (?:)


The conditional operator behaves like a simple ifelse statement. Its syntax is: Condition ? Statement1 : Statement2; The compiler would first test the Condition. If the Condition is true, then it would execute Statement1, otherwise it would execute Statement2. When you request two numbers from the user and would like to compare them, the following program would do find out which one of both numbers is higher. The comparison is performed using the conditional operator: #include <iostream> using namespace std; int main() { signed Num1, Num2, Max; cout << "Enter two numbers: "; cin >> Num1 >> Num2; Max = (Num1 < Num2) ? Num2 : Num1; cout << "\nThe maximum of " << Num1 << " and " << Num2 << " is " << Max; return 0; }

Conditional Statements: ifelse if and ifelse ifelse


The previous conditional formula is used to execute one of two alternatives. Sometimes, your

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
program will need to check many more than that. The syntax for such a situation is: if(Condition1) Statement1; else if(Condition2) Statement2; An alternative syntax would add the last else as follows: if(Condition1) Statement1; else if(Condition2) Statement2; else Statement-n; if(Condition1) Statement1; else if(Condition2) Statement2; else if(Condition3) Statement3; else Statement-n;

The compiler will check the first condition. If Condition1 is true, it will execute Statement1. If Condition1 is false, then the compiler will check the second condition. If Condition2 is true, it will execute Statement2. When the compiler finds a Condition-n to be true, it will execute its corresponding statement. It that Condition-n is false, the compiler will check the subsequent condition. This means you can include as many conditions as you see fit using the else if statement. If after examining all the known possible conditions you still think that there might be an unexpected condition, you can use the optional single else. A program we previously wrote was considering that any answer other than y was negative. It would be more professional to consider a negative answer because the program anticipated one. Therefore, here is a better version of the program:

#include <iostream> using namespace std; int main() { char Answer; cout << "Do you consider yourself a hot-tempered individual(y=Yes/n=No)? "; cin >> Answer; if( Answer == 'y' ) // Unique Condition { cout << "\nThis job involves a high level of self-control."; cout << "\nWe will get back to you.\n"; } else if( Answer == 'n' ) // Alternative cout << "\nYou are hired!\n"; else cout << "\nThat's not a valid answer!\n"; return 0; }

The switch Statement


When defining an expression whose result would lead to a specific program execution, the switch statement considers that result and executes a statement based on the possible outcome of that expression, this possible outcome is called a case. The different outcomes are listed in the body of the switch statement and each case has its own execution, if necessary. The body of a switch statement is delimited from an opening to a closing curly brackets: { to }. The syntax of the switch statement is: switch(Expression) { case Choice1: Statement1; case Choice2: Statement2; case Choice-n: Statement-n; } The expression to examine is an integer. Since an enumeration (enum) and the character

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
(char) data types are just other forms of integers, they can be used too. Here is an example of using the switch statement:

#include <iostream> using namespace std; int main() { int Number; cout << "Type a number between 1 and 3: "; cin >> Number; switch (Number) { case 1: cout << "\nYou typed 1."; case 2: cout << "\nYou typed 2."; case 3: cout << "\nYou typed 3."; } return 0; } The program above would request a number from the user. If the user types 1, it would execute the first, the second, and the third cases. If she types 2, the program would execute the second and third cases. If she supplies 3, only the third case would be considered. If the user types any other number, no case would execute. When establishing the possible outcomes that the switch statement should consider, at times there will be other possibilities other than those listed and you will be likely to consider them. This special case is handled by the default keyword. The default case would be considered if none of the listed cases matches the supplied answer. The syntax of the switch statement that considers the default case would be:

switch(Expression) { case Choice1: Statement1; case Choice2: Statement2; case Choice-n: Statement-n; default: Other-Possibility; }
Therefore another version of the program above would be

#include <iostream> using namespace std; int main() { int Number; cout << "Type a number between 1 and 3: "; cin >> Number; switch (Number) { case 1: cout << case 2: cout << case 3: cout << default: cout << } return 0; }

"\nYou typed 1."; "\nYou typed 2."; "\nYou typed 3."; endl << Number << " is out of the requested range.";

Counting and Looping


Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
The C++ language provides a set of control statements that allows you to conditionally control data input and output. These controls are referred to as loops.

The while Statement


The while statement examines or evaluates a condition. The syntax of the while statement is: while(Condition) Statement;

To execute this expression, the compiler first examines the Condition. If the Condition is true, then it executes the Statement. After executing the Statement, the Condition is checked again. AS LONG AS the Condition is true, it will keep executing the Statement. When or once the Condition becomes false, it exits the loop. Here is an example:

int Number; while( Number <= 12 ) { cout << "Number " << Number << endl; Number++; } To effectively execute a while condition, you should make sure you provide a mechanism for the compiler to use a get a reference value for the condition, variable, or expression being checked. This is sometimes in the form of a variable being initialized although it could be some other expression. Such a while condition could be illustrated as follows:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

An example would be:

#include <iostream> using namespace std; int main() { int Number;// = 0; while( Number <= 12 ) { cout << "Number " << Number << endl; Number++; } return 0; }

The do...while Statement


The dowhile statement uses the following syntax: do Statement while (Condition);

The dowhile condition executes a Statement first. After the first execution of the Statement, it examines the Condition. If the Condition is true, then it executes the Statement again. It will keep executing the Statement AS LONG AS the Condition is true. Once the Condition becomes false, the looping (the execution of the Statement) would stop. If the Statement is a short one, such as made of one line, simply write it after the do keyword. Like the if and the while statements, the Condition being checked must be included between parentheses. The whole dowhile statement must end with a semicolon.

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Another version of the counting program seen previously would be:

#include <iostream> using namespace std; int main() { int Number = 0; do cout << "Number " << Number++ << endl; while( Number <= 12 ); return 0; } If the Statement is long and should span more than one line, start it with an opening curly braket and end it with a closing curly bracket. The dowhile statement can be used to insist on getting a specific value from the user. For example, since our ergonomic program would like the user to sit down for the subsequent exercise, you can modify your program to continue only once she is sitting down. Here is an example on how you would accomplish that:

#include <iostream> using namespace std; int main() { char SittingDown; cout << "For the next exercise, you need to be sitting down\n"; do { cout << "Are you sitting down now(y/n)? "; cin >> SittingDown; } while( !(SittingDown == 'y') ); cout << "\nWonderful!!!"; return 0; }

The for Statement


The for statement is typically used to count a number of items. At its regular structure, it is divided in three parts. The first section specifies the starting point for the count. The second section sets the counting limit. The last section determines the counting frequency. The syntax of the for statement is: for( Start; End; Frequency) Statement; The Start expression is a variable assigned the starting value. This could be Count = 0; The End expression sets the criteria for ending the counting. An example would be Count < 24; this means the counting would continue as long as the Count variable is less than 24. When the count is about to rich 24, because in this case 24 is excluded, the counting would stop. To include the counting limit, use the <= or >= comparison operators depending on how you are counting. The Frequency expression would let the compiler know how many numbers to add or subtract before continuing with the loop. This expression could be an increment operation such as ++Count. Here is an example that applies the for statement:

#include <iostream> using namespace std; int main() { for(int Count = 0; Count <= 12; Count++) cout << "Number " << Count << endl; return 0; } The C++ compiler recognizes that a variable declared as the counter of a for loop is available

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
only in that for loop. This means the scope of the counting variable is confined only to the for loop. This allows different for loops to use the same counter variable. Here is an example:

#include <iostream> using namespace std; int main() { for(int Count = 0; Count <= 12; Count++) cout << "Number " << Count << endl; cout << endl; for(int Count = 10; Count >= 2; Count--) cout << "Number " << Count << endl; return 0; } Some compilers do not allow the same counter variable in more than one for loop. The counter variables scope spans beyond the for loop. With such a compiler, you must use a different counter variable for each for loop. An alternative to using the same counter variable in different for loops is to declare the counter variable outside of the first for loop and call the variable in the needed for loops. Here is an example:

#include <iostream> using namespace std; int main() { int Count; for(Count = 0; Count <= 12; Count++) cout << "Number " << Count << endl; cout << endl; for(Count = 10; Count >= 2; Count--) cout << "Number " << Count << endl; return 0; }

Previous

Copyright 2002-2009 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Constructing Expressions
Accessories for Conditional Statements

Introduction
There are techniques you can use to combine conditional statements when one of them cannot fully implement the desired behavior. We will continue with our traffic light analogy.

Nesting Conditions
A condition can be created inside of another to write a more effective statement. This is referred to as nesting conditions. Almost any condition can be part of another and multiple conditions can be included inside of others. As we have learned, different conditional statements are applied in specific circumstances. In some situations, they are interchangeable or one can be applied just like another, which becomes a matter of choice. Statements can be combined to render a better result with each playing an appropriate role. To continue with our ergonomic program, imagine that you would really like the user to sit down and your program would continue only once she answers that she is sitting down, you can use the dowhile statement to wait for the user to sit down; but as the dowhile is checking the condition, you can insert an if statement to enforce your request. Here is an example of how you can do it:
#include <iostream> using namespace std; int main() { char SittingDown; do { cout << "Are you sitting down now(y/n)? "; cin >> SittingDown; if( SittingDown != 'y' ) cout << "\nCould you please sit down for the next exercise?\n";

} while( !(SittingDown == 'y') ); cout << "\nWonderful!!!\n"; return 0;

Here is an example of running the program:


Are you sitting down now(y/n)? n Could you please sit down for the next exercise? Are you sitting down now(y/n)? n Could you please sit down for the next exercise?

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Are you sitting down now(y/n)? y Wonderful!!! Press any key to continue...

One of the reasons you would need to nest conditions is because one would lead to another. Sometimes, before checking one condition, another primary condition would have to be met. The ergonomic program we have been simulating so far is asking the user whether she is sitting down. Once the user is sitting down, you would write an exercise she would perform. Depending on her strength, at a certain time, one user will be tired and want to stop while for the same amount of previous exercises, another user would like to continue. Before continuing with a subsequent exercise, you may want to check whether the user would like to continue. Of course, this would be easily done with:
#include <iostream> using namespace std; int main() { char SittingDown; do { cout << "Are you sitting down now(y/n)? "; cin >> SittingDown;

if( SittingDown != 'y' ) cout << "Could you please sit down for the next exercise?"; cout << "\n\n"; }while( SittingDown != 'y' ); cout << "Wonderful. Now we will continue today's exercise..."; cout << "\n...\nEnd of exercise"; char WantToContinue; cout << "Do you want to continue(y=Yes/n=No)? "; cin >> WantToContinue; } return 0;

If the user answers No, you can stop the program. If she answers Yes, you would need to continue the program with another exercise. Because the user answered Yes, the subsequent exercise would be included in the previous condition because it does not apply for a user who wants to stop. In this case, one if could be inserted inside of another. Here is an example:
#include <iostream> using namespace std; int main() { char SittingDown; do { cout << "Are you sitting down now(y/n)? "; cin >> SittingDown;

if( SittingDown != 'y' ) cout << "Could you please sit down for the next exercise?"; cout << "\n\n"; }while( SittingDown != 'y' ); cout << "Wonderful. Now we will continue today's exercise...\n"; cout << "\n...\n\nEnd of exercise\n"; char WantToContinue; cout << "\nDo you want to continue(1=Yes/0=No)? ";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cin >> WantToContinue; if(WantToContinue == '1') { char LayOnBack; cout << "Good. For the next exercise, you should lay on your back"; cout << "\nAre you laying on your back(1=Yes/0=No)? "; cin >> LayOnBack; if(LayOnBack == '1') cout << "\nGreat.\nNow we will start the next exercise."; else cout << "\nWell, it looks like you are getting tired..."; cout << "\nWe had enough today";

} else

cout << "\nWe will stop the session now\nThanks.\n"; return 0;

In the same way, you can nest statements as you see fit. The goal is to provide an efficient and friendly application. You can insert and nest statements that provide valuable feedback to the user while minimizing boredom. The above version of the program can be improved as followed:
#include <iostream> using namespace std; int main() { char SittingDown; do { cout << "Are you sitting down now(y/n)? "; cin >> SittingDown;

if( SittingDown != 'y' ) cout << "Could you please sit down for the next exercise?"; cout << "\n\n"; }while( SittingDown != 'y' ); cout << "Wonderful. Now we will continue today's exercise...\n"; cout << "\n...\n\nEnd of exercise\n"; char WantToContinue; cout << "\nDo you want to continue(1=Yes/0=No)? "; cin >> WantToContinue; if(WantToContinue == '1') { char LayOnBack; cout << "Good. For the next exercise, you should lay on your back"; cout << "\nAre you laying on your back(1=Yes/0=No)? "; cin >> LayOnBack; if(LayOnBack == '0') { char Ready; do { cout << "Please lay on your back"; cout << "\nAre you ready(1=Yes/0=No)? "; cin >> Ready; }while(Ready == '0');

} else

} else if(LayOnBack == '1') cout << "\nGreat.\nNow we will start the next exercise."; else cout << "\nWell, it looks like you are getting tired..."; cout << "\nWe had enough today";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} cout << "\nWe will stop the session now\nThanks.\n"; return 0;

Conditional Statements Accessories

break
The break statement is used to stop a loop for any reason or condition the programmer sees considers fit. The break statement can be used in a while condition to stop an ongoing action. The syntax of the break statement is simply: break; Although made of only one word, the break statement is a complete statement; therefore, it can (and should always) stay on its own line (this makes the program easy to read). The break statement applies to the most previous conditional statement to it; provided that previous statement is applicable. The following program would display the letter d continuously unless something or somebody stops it. A break statement is inserted to stop this ever looping process:
#include <iostream> using namespace std; int main() { char Letter = 'd'; while( Letter <= 'n' ) { cout << "Letter " << Letter << endl; break; } } return 0;

The break statement can also be used in a dowhile or a for loop the same way. The break statement is typically used to handle the cases in a switch statement. We saw earlier that all cases in a switch would execute starting where a valid statement is found. Consider the program we used earlier to request a number from 1 to 3, a better version that involves a break in each case would allow the switch to stop once the right case is found. Here is a new version of that program:
#include <iostream> using namespace std; int main() { int Number; cout << "Type a number between 1 and 3: "; cin >> Number; switch (Number) { case 1: cout << "\nYou typed 1."; break; case 2: cout << "\nYou typed 2."; break;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
case 3: cout << "\nYou typed 3."; break; default: cout << endl << Number << " is out of the requested range."; } } return 0;

Even when using the break statement, the switch allows many case to execute as one. To do this, as we saw when not using the break, type two cases together. This technique is useful when validating letters because the letters could be in uppercase or lowercase. This illustrated in the following program:
#include <iostream> using namespace std; int main() { char Letter; cout << "Type a letter: "; cin >> Letter; switch( Letter ) { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U': cout << "The letter you typed, " << Letter << ", is a vowel\n"; break; case 'b':case 'c':case 'd':case 'f':case 'g':case 'h':case 'j': case 'k':case 'l':case 'm':case 'n':case 'p':case 'q':case 'r': case 's':case 't':case 'v':case 'w':case 'x':case 'y':case 'z': cout << Letter << " is a lowercase consonant\n"; break; case 'B':case 'C':case 'D':case 'F':case 'G':case 'H':case 'J': case 'K':case 'L':case 'M':case 'N':case 'P':case 'Q':case 'R': case 'S':case 'T':case 'V':case 'W':case 'X':case 'Y':case 'Z': cout << Letter << " is a consonant in uppercase\n"; break; default: cout << "The symbol " << Letter << " is not an alphabetical letter\n"; } } return 0;

The switch statement is also used with an enumerator that controls cases. This is also a good place to use the break statement to decide which case applies. An advantage of using an enumerator is its ability to be more explicit than a regular integer. To use an enumerator, define it and list each one of its members for the case that applies. Remember that, by default, the members of an enumerator are counted with the first member having a value of 0, the second is 1, etc. Here is an example of a switch statement that uses an enumerator.
#include <iostream> using namespace std; enum TEmploymentStatus { esFullTime, esPartTime, esContractor, esNS }; int main()

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ int EmplStatus; cout << "Employee's Contract Status: "; cout << "\n0 - Full Time | 1 - Part Time" << "\n2 - Contractor | 3 - Other" << "\nStatus: "; cin >> EmplStatus; cout << endl; switch( EmplStatus ) { case esFullTime: cout << "Employment Status: Full Time\n"; cout << "Employee's Benefits: Medical Insurance\n" << " Sick Leave\n" << " Maternal Leave\n" << " Vacation Time\n" << " 401K\n"; break; case esPartTime: cout << "Employment Status: Part Time\n"; cout << "Employee's Benefits: Sick Leave\n" << " Maternal Leave\n"; break; case esContractor: cout << "Employment Status: Contractor\n"; cout << "Employee's Benefits: None\n"; break; case esNS: cout << "Employment Status: Other\n"; cout << "Status Not Specified\n"; break; default: cout << "Unknown Status\n"; } } return 0;

continue
The continue statement uses the following syntax: continue; When processing a loop, if the statement finds a false value, you can use the continue statement inside of a while, dowhile or a for conditional statements to ignore the subsequent statement or to jump from a false Boolean value to the subsequent valid value, unlike the break statement that would exit the loop. Like the break statement, the continue keyword applies to the most previous conditional statement and should stay on its own line. The following programs asks the user to type 4 positive numbers and calculates the sum of the numbers by considering only the positive ones. If the user types a negative number, the program manages to ignore the numbers that do not fit in the specified category:
#include <iostream> using namespace std; int main() { // Declare necessary variables int posNumber, Sum = 0; // Request 4 positive numbers from the user cout << "Type 4 positive numbers.\n"; // Make sure the user types 4 positive numbers for( int Count = 1; Count <= 4; Count++ ) {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "Number: "; cin >> posNumber; // If the number typed is not positive, ignore it if( posNumber < 0 ) continue; // Add each number to the sum Sum += posNumber;

// Display the sum cout << "\nSum of the numbers you entered = " << Sum << "\n\n"; } return 0;

goto
The goto statement allows a program execution to jump to another section of the function in which it is being used. In order to use the goto statement, insert a name on a particular section of your function so you can refer to that name. The name, also called a label, is made of one word and follows the rules we have learned about C++ names (the name can be anything), then followed by a colon. The following program uses a for loop to count from 0 to 12, but when it encounters 5, it jumps to a designated section of the program:
#include <iostream> using namespace std; int main() { for(int Count = 0; Count <= 12; ++Count) { cout << "Count " << Count << endl; if( Count == 5 ) goto MamaMia;

MamaMia: cout << "Stopped at 5"; } return 0;

Logical Operations on Statements


The conditional Statements we have used so far were applied to single situations. You can combine statements using techniques of logical thinking to create more complex and complete expressions. One way to do this is by making sure that two conditions are met for the whole expression to be true. On the other hand, one or the other of two conditions can produce a true condition, as long as one of them is true. This is done with logical conjunction or disjunction.

Using the Logical Not


When a driver comes to a light that he expects to be green, we saw that he would use a statement such as, "The light is green". If in fact the light is green, we saw that the statement would lead to a true result. If the light is not green, the "The light is green" statement produces a false result. This is shown in the following table:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Color Statement The light is green The light is green Boolean Value true false

As you may realize already, in Boolean algebra, the result of performing a comparison depends on how the Condition is formulated. If the driver is approaching a light that he is expecting to display any color other than green, he would start from a statement such as "The light is not green". If the light IS NOT green, the expression "The light is not green" is true (very important). This is illustrated in the following table:

Color

Statement The light is green The light is not green

Boolean Value true true

The "The light is not green" statement is expressed in green. Instead of writing Not the light is green", you would formulate the statement as, !"The light is light is green, you can express the negativity of P as Color Statement The light is green The light is not green

Boolean algebra as Not the light is in C++, using the logical Not operator , green". Therefore, if P means The !P. The Boolean table produced is: Boolean Value true false Symbol P !P

When a statement is true, its Boolean value is equivalent to a non-zero integer such as 1. Otherwise, if a statement produces a false result, it is given a 0 value. Therefore, our table would be: Color Statement The light is green The light is not green Boolean Value true false Integer Value 1 0

Even though a program usually asks a straightforward question, the compiler would only consider the expression that needs to be evaluated; that is, the expression included between the parentheses of the if Condition. Suppose you are writing an ergonomic program that would guide the user on when and how to exercise. One of the questions your program would ask might be: "Are you sitting down?" There are three classic variances to this issue: the user might be sitting down, standing up, or laying down. Your program might look like this:
#include <iostream> using namespace std; int main() { int Position; cout << "Specify your position:\n" << "1 - Sitting Down\n" << "2 - Standing Up\n" << "3 - Laying Down\n";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cin >> Position; if( Position == 1 ) cout << "\nNow, position your back as vertically as you can.\n"; } return 0;

That program allows the user to give one of three answers; and you might do something depending on the users answer. Now, suppose you only want to know whether the user is sitting down; in fact, the program might expect the user to be sitting down for the subsequent assignment. Such a program could be:
#include <iostream> using namespace std; int main() { int SittingDown; cout << "Are you sitting down (1=Yes/0=No)? "; cin >> SittingDown; if( SittingDown == 1 ) cout << "\nGood, now we will continue our next assignment.\n"; } return 0;

If the user is standing up, you would like her to sit down. If she is laying down, you still would like her to sit down. Based on this requirement, you might want to check whether the user is sitting down and you would not be interested in another position. The question could then be, Aren't you sitting down?. In Boolean algebra, the question would be asked as, " Are you NOT sitting down?". A better C++ question would be, Not Are you sitting down? . In other words, the statement (in this case the question) would be the negation of the regular question. If P represents the Are you sitting down? question, the negativity of P is expressed as !P. The new version of our program would be more concerned with the position the user has. Since the user is expected to type 1 for Yes, the program would display a concern for any other answer; in short, it would check the negativity of the Condition:
#include <iostream> using namespace std; int main() { int SittingDown; cout << "Are you sitting down (1=Yes/0=No)? "; cin >> SittingDown; if( !(SittingDown == 1) ) cout << "\nCould you please sit down for the next exercise?\n"; cout << "\nWonderful!!!\n\n"; return 0;

Logical Conjunction: AND


The law of the traffic light states that if a driver drives through a red light, he or she has broken the law. Three things happen here: 1. The traffic light is red 2. The driver is driving 3. The law is broken Lets segment these expressions and give each a name. The first statement will be called L. Therefore,

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
L <=> The traffic light is red The second statement will be called D. This means D <=> The driver is driving through the light The last statement will be called B, which means B <=> The law is broken Whenever the traffic light is red, the The traffic light is red statement is true. Whenever a driver is driving, the The driver is driving statement is true, which means D is true. Whenever the law is broken, the The law is broken statement is true. When a statement is true, it receives a Boolean value of true: L true D true B true

These three statements are completely independent when each is stated in its own sentence. The third bears any consideration only when the first two are combined. Therefore, the third statement is a consequence or a result. The fact that a driver is driving and/or a light is red or displays any color, does not make a law broken. The law is broken only when or IF a driver drives through a red light. This means L and D have to be combined to produce B. A combination of the first two statements means you need Statement1 AND Statement2. Combining Statement1 AND Statement2 means L AND D that produces "The traffic light is red AND The driver is driving through the light" In C++, the AND keyword is called an operator because it applies for one or more variable. The AND operator is specifically called a binary operator because it is used on two variables. The AND operator is used to concatenate or add two statements or expressions. It is represented by &&. Therefore, a concatenation of L and D would be written as L && D. Logically, what does the combination mean? When the traffic light is red, L is true. If a driver is driving through the light, D is true. If the driver is driving through the light that is red, this means L && D. Then the law is broken: L true D true L && D true B TRUE

When the traffic light is not red, regardless of the lights color, L is false. If a driver drives through it, no law is broken. Remember, not only should you drive through a green light, but also you are allowed to drive through a yellow light. Therefore, B is false: L false D true L && D false B FALSE

If the traffic light is red, L is true. If no driver drives through it, D is false, and no law is broken. When no law is broken, B, which is the result of L && D, is false: L true D false L && D false B FALSE

If the light is not red, L is false. If no driver drives through it, D is false. Consequently, no law is broken. B, which is the result of L && D, is still false: L false D false L && D false B FALSE

From our tables, the law is broken only when the light is red AND a driver drives through it. This produces: L true false true false D true true false false L && D true false false false B TRUE FALSE FALSE FALSE

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
The logical conjunction operator && is used to check that the combination of two statements results in a true condition. This is used when one condition cannot satisfy the intended result. Consider a pizza application whose valid sizes are 1 for small, 2 for medium, 3 for large, and 4 for jumbo. When a clerk uses this application, you would usually want to make sure that only a valid size is selected to process an order. After the clerk has selected a size, you can use a logical conjunction to validate the range of the items size. Such a program could be written (or started) as follows:
#include <iostream> using namespace std; int main() { int PizzaSize; cout << "Select your pizza size"; cout << "\n1=Small | 2=Medium"; cout << "\n3=Large | 4=Jumbo"; cout << "\nYour Choice: "; cin >> PizzaSize; if(PizzaSize >= 0 && PizzaSize <= 4) cout << "Good Choice. Now we will proceed with the toppings\n"; else cout << "Invalid Choice\n"; } return 0;

When a program asks a question to the user who must answer by typing a letter, there is a chance that the user would type the answer in uppercase or lowercase. Since we know that C++ is case-sensitive, you can use a combined conditional statement to find out what answer or letter the user would have typed. We saw that the truthfulness of a statement depends on how the statement is structured. In some and various cases, instead of checking that a statement is true, you can validate only negative values. This can be done on single or combined statements. For example, if a program is asking a question that requires a Yes or No answer, you can make sure the program gets a valid answer before continuing. Once again, you can use a logical conjunction to test the valild answers. Here is an example:
#include <iostream> using namespace std; int main() { char SittingDown; do { cout << "Are you sitting down now(y/n)? "; cin >> SittingDown;

if( SittingDown != 'y' && SittingDown != 'Y' ) cout << "Could you please sit down for the next exercise?"; cout << "\n"; } while( SittingDown != 'y' && SittingDown != 'Y' ); cout << "Wonderful!!!"; } return 0;

Logical Disjunction: OR
Lets assume that a driver has broken the law by driving through a red traffic light but there was no accident (to make our discussion simpler). There are two ways he can get a ticket: a police officer saw him, a special camera took a picture. This time again, we have

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
three statements to make: S <=> A police officer saw the driver H <=> A camera took a picture of the action T <=> The driver got a ticket If a police officer saw the driver breaking the law, the A police officer saw the driver statement is true. Consequently, S is true. If a (specially installed) camera took the picture (of the scene), the A camera took the picture of the action statement is true. This means H is true. If the driver gets a ticket, the The driver gets a ticket statement is true, which means T is true. S true H true T true

Once again, the third statement has no bearing unless you consider the first two. Last time, we saw that if the first two statements were combined, only then the result would produce the third statement. Lets consider in which case the driver would get a ticket. If a police officer saw the driver, would he get a ticket? Yes, because on many traffic lights there is no camera but a police officer has authority to hand an infraction. This means if S is true, then T also is true. This produces: S true H Don't Care T true

Imagine a traffic light is equipped with a camera. If the driver breaks the law, the camera would take a picture, which means the driver would get a ticket. Therefore, if a camera takes a picture (H is true), the driver gets a ticket (T is true): S Don't Care H true T true

What if a police officer catches the action and a camera takes a picture. This means the driver will still get a ticket, even if one of both the police officer and the camera does not act but the other does. If both the police officer and the camera catch the action and act accordingly, the driver would get only one ticket (even if the driver receives two tickets, only one would be considered). Therefore, whether the first statement OR the second statement is true, the resulting third statement T is still true: S true H true T true

The only time the driver would not get a ticket is when no police officer catches him and no camera takes a picture. In other words, only when both of the first two statements are false can the third statement be false. Since T is the result of S and H combined, we have seen that T is true whenever either S is true OR H is true. The OR logical disjunction is expressed in C++ with the || operator. Here is the resulting table: S true false true false H true true false false S || H true true true false T TRUE TRUE TRUE FALSE

Consider a program that asks a question and expects a yes or no answer in the form of y or n. Besides y for yes, you can also allow the user to type Y as a valid yes. To do this, you would let the compiler check that either y or Y was typed. In the same way, either n or N would be valid negations. Any of the other characters would fall outside the valid characters. Our hottempered program can be restructured as follows:
#include <iostream> using namespace std;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
int main() { char Answer; cout << "Do you consider yourself a hot-tempered individual(y=Yes/n=No)? "; cin >> Answer; if( Answer == 'y' || Answer == 'Y' ) // Unique Condition { cout << "\nThis job involves a high level of self-control."; cout << "\nWe will get back to you.\n"; } else if( Answer == 'n' || Answer == 'N' ) // Alternative cout << "\nYou are hired!\n"; else cout << "\nThat was not a valid answer!\n"; } return 0;

Conditional Statements and functions

Using Conditions in Functions

The use of functions in a program allows you to isolate assignments and confine them to appropriate entities. While the functions take care of specific requests, you should provide them with conditional statements to validate what these functions are supposed to do. There are no set rules to the techniques involved; everything depends on the tasks at hand. Once again, you will have to choose the right tools for the right job. To make effective use of functions, you should be very familiar with different data types because you will need to return the right value. The ergonomic program we have been writing so far needs to check different things including answers from the user in order to proceed. These various assignments can be given to functions that would simply hand the results to the main() function that can, in turn, send these results to other functions for further processing. Here is an example:
#include <iostream> using namespace std; #define Or || #define And && char GetPosition() { char Position; do { cout << "Are you sitting down now(y/n)? "; cin >> Position;

if( Position != 'y' And Position != 'Y' And Position != 'n' And Position != 'N' ) cout << "Invalid Answer\n"; } while( Position != 'y' And Position != 'Y' And Position != 'n' And Position != 'N' ); } return Position;

int main() { char Position; Position = GetPosition(); if( Position == 'n' Or Position == 'N' ) cout << "\nCould you please sit down for the next exercise?\n";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
else cout << "\nWonderful!!!\n\n";

return 0;

Functions do not have to return a value in order to be involved with conditional statements. In fact, both issues are fairly independent. This means, void and non-void functions can manipulate values based on conditions internal to the functions. This is illustrated in the following program that is an enhancement to an earlier ergonomic program:
#include <iostream> using namespace std; #define Or || #define And && char GetPosition() { char Position; do { cout << "Are you sitting down now(y/n)? "; cin >> Position; if( Position != 'y' And Position != 'Y' And Position != 'n' And Position != 'N' ) cout << "Invalid Answer\n";

} while( Position != 'y' And Position != 'Y' And Position != 'n' And Position != 'N' ); } return Position;

void NextExercise() { char LayOnBack; cout << "Good. For the next exercise, you should lay on your back"; cout << "\nAre you laying on your back(1=Yes/0=No)? "; cin >> LayOnBack; if(LayOnBack == '0') { char Ready; do { cout << "Please lay on your back"; cout << "\nAre you ready(1=Yes/0=No)? "; cin >> Ready; }while(Ready == '0');

} else if(LayOnBack == '1') cout << "\nGreat.\nNow we will start the next exercise."; else cout << "\nWell, it looks like you are getting tired...";

int main() { char Position, WantToContinue; Position = GetPosition(); if( Position == 'n' Or Position == 'N' ) cout << "\nCould you please sit down for the next exercise?"; else { cout << "\nWonderful!\nNow we will continue today's exercise...\n"; cout << "\n...\n\nEnd of exercise\n"; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\nDo you want to continue(1=Yes/0=No)? "; cin >> WantToContinue; if( WantToContinue == '1' ) NextExercise(); else if( WantToContinue == '0' ) cout << "\nWell, it looks like you are getting tired..."; else { cout << "\nConsidering your invalid answer..."; cout << "\nWe had enough today"; } cout << "\nWe will stop the session now\nThanks.\n"; } return 0;

Conditional Returns
A function defined other than void must always return a value. Sometimes, a function will perform some tasks whose results would lead to different consequences. A function can return only one value (this is true for this context, but we know that there are ways to pass arguments so that a function can return more than one value) but you can make it render a result depending on a particular behavior. Image that a function is requesting an answer from the user. Since the user can provide different answers, you can treat each result differently. In the previous section, we saw an example of returning a value from a function. Following our employment application, here is an example of a program that performs a conditional return:
#include <iostream> using namespace std; bool GetAnswer() { char Ans; string Response; cout << "Do you consider yourself a hot-tempered individual(y=Yes/n=No)? "; cin >> Ans; if( Ans == 'y' ) return true; else return false;

int main() { bool Answer; Answer = GetAnswer(); if( Answer == true ) { cout << "\nThis job involves a high level of self-control."; cout << "\nWe will get back to you.\n"; } else cout << "\nYou are hired!\n"; } return 0;

Imagine you write the following function:


#include <iostream> using namespace std; #define Or || #define And && string GetPosition()

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ char Position; cout << "Are you sitting down now(y/n)? "; cin >> Position; if( Position == 'y' Or Position == 'Y' ) return "Yes"; else if( Position == 'n' Or Position == 'N' ) return "No";

int main() { string Answer; Answer = GetPosition(); cout << "\nAnswer = " << Answer; } return 0;

On paper, the function looks fine. If the user answers with y or Y, the function returns the string Yes. If the user answer with n or N, the function returns the string No. Unfortunately, this function has a problem: what if there is an answer that does not fit those we are expecting? In reality the values that we have returned in the function conform only to the conditional statements and not to the function. Remember that in if(Condidion)Statement, the Statement executes only if the Condition is true. Here is what will happen. If the user answers y or Y, the function returns Yes and stops; fine, it has returned something, we are happy. If the user answers n or N, the function returns No, which also is a valid value: wonderful. If the user enters another value (other than y, Y, n, or N), the execution of the function will not execute any of the return statements and will not exit. This means the execution will reach the closing curly bracket without encountering a return value. Therefore, the compiler will issue a warning. Although the warning looks like not a big deal, you should take care of it: never neglect warnings. The solution is to provide a return value so that, if the execution reaches the end of the function, it would still return something. Here is a solution to the problem:
#include <iostream> using namespace std; #define Or || #define And && string GetPosition() { char Position; cout << "Are you sitting down now(y/n)? "; cin >> Position; if( Position == 'y' Or Position == 'Y' ) return "Yes"; else if( Position == 'n' Or Position == 'N' ) return "No"; return "Invalid Answer";

int main() { string Answer; Answer = GetPosition(); cout << "\nAnswer = " << Answer; } return 0;

This is illustrated in the following program that has two functions with conditional returns:
#include <iostream> using namespace std; #define Or ||

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#define And && char GetPosition() { char Position; do { cout << "Are you sitting down now(y/n)? "; cin >> Position;

if( Position != 'y' And Position != 'Y' And Position != 'n' And Position != 'N' ) cout << "Invalid Answer\n"; } while(Position != 'y' And Position != 'Y' And Position != 'n' And Position != 'N' ); if( Position == 'y' Or Position == 'Y' ) return 'y'; else if( Position == 'n' Or Position == 'N' ) return 'n'; // If you reach this point, none of the answers was valid return Position;

void NextExercise() { char LayOnBack; cout << "Good. For the next exercise, you should lay on your back"; cout << "\nAre you laying on your back(1=Yes/0=No)? "; cin >> LayOnBack; if(LayOnBack == '0') { char Ready; do { cout << "Please lay on your back"; cout << "\nAre you ready(1=Yes/0=No)? "; cin >> Ready; } while(Ready == '0');

} else if(LayOnBack == '1') cout << "\nGreat.\nNow we will start the next exercise."; else cout << "\nWell, it looks like you are getting tired...";

bool ValidatePosition(char Pos) { if( Pos == 'y' Or Pos == 'Y' ) return true; else if( Pos == 'n' Or Pos == 'N' ) return false; // If you reached this point, we need to prevent a warning return false;

int main() { char Position, WantToContinue; bool SittingDown; Position = GetPosition(); SittingDown = ValidatePosition(Position); if( SittingDown == false ) cout << "\nCould you please sit down for the next exercise?"; else { cout << "\nWonderful!\nNow we will continue today's exercise...\n"; cout << "\n...\n\nEnd of exercise\n"; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\nDo you want to continue(1=Yes/0=No)? "; cin >> WantToContinue; if( WantToContinue == '1' ) NextExercise(); else if( WantToContinue == '0' ) cout << "\nWell, it looks like you are getting tired..."; else { cout << "\nConsidering your invalid answer..."; cout << "\nWe had enough today"; } cout << "\nWe will stop the session now\nThanks.\n"; return 0;

Previous

Copyright 2000-2009 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Intermediate Operations
Bit Manipulations
Introduction
We learned in the previous lesson that, when you declare a variable, the compiler reserves an amount of space in memory for that variable. Indeed, as we learned when studying bytes and words, a declared variable occupies space that resembles a group of small boxes. In our human understanding, it is not always easy to figure out how a letter such as as B is stored in 7 seven small boxes when we know that B is only one letter. Bit manipulation or a bit related operation allows you to control how values are stored in bits. This is not an operation you will need to perform very often, especially not in the early stages of your C++ journey. Nevertheless, bit operations (and related overloaded operators) are present on all GUI or application programming environments, so much that you should be aware of what they do or what they offer. At this time, you should (must) be aware of what a bit, byte, and a word are, as we saw in the previous lesson.

Bits Operators: The Bitwise NOT Operator ~


One of the operations you can perform on a bit consists of reversing its value. That is, if a bit holds a value of 1, you may want to change it to 0 and vice-versa. This operation can be taken care of by the bitwise NOT operator that is represented with the tilde symbol ~ The bitwise NOT is a unary operator that must be placed on the left side of its operand as in
~Value

To perform this operation, the compiler considers each bit that is part of the operand and inverts the value of each bit from 1 to 0 or from 0 to 1 depending on the value the bit is holding. This operation can be resumed in the following table:

Bit 1 0

~Bit 0 1

Consider a number with a byte value such as 248. In our study of numeric systems, we define how to convert numbers from one system to another (this could be a good time to review or study the numeric systems). Based on this, the binary value of decimal 248 is 1111 1000 (and its hexadecimal value is 0xF8). If you apply the bitwise NOT operator on it to reverse the values of its bits, you would get the following result:

Value 1 ~Value 0

1 0

1 0

1 0

1 0

0 1

0 1

0 1

Comparing Bits: The Bitwise AND Operator &


The bitwise & is a binary operator that uses the following syntax
Operand1 & Operand2

This operator considers two values and compares the bit of each with the corresponding bit of the other value. If both corresponding bits are 1, the comparison produces 1. Otherwise, that is, if either bit is 0, the comparison produces 0. This comparison is resumed as follows:

Bit1 0 1 0 1

Bit2 0 0 1 1

Bit1 & Bit2 0 0 0 1

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Imagine you have two byte values represented as 187 and 242. Based on our study of numeric systems, the binary value of decimal 187 is 1011 1011 (and its hexadecimal value is 0xBB). The binary value of decimal 242 is 1111 0010 (and its hexadecimal value is 0xF2). Lets compare these two values bit by bit, using the bitwise AND operator:

N1 1 N2 1 N1 & N2 1

0 1 0

1 1 1

Binary 1 1 0 1 0 0 1 0 0

1 1 1

1 0 0

Decimal 187 242 178

Most of the times, you will want the compiler to perform this operation and use the result in your program. This means that you can get the result of this operation and possibly display it on the console. The above operation can be performed by the following program:

#include <iostream> using namespace std; main() { const int N1 = 187; const int N2 = 242; cout << N1 << " & " << N2 << " = " << (N1 & N2) << "\n\n"; return 0; }

This would produce: 187 & 242 = 178

Comparing Bits: The Bitwise OR Operator |


You can perform another type of comparison on bits using the bitwise OR operator that is represented by |. Its syntax is: Value1 | Value2 Once again, the compiler compares the corresponding bits of each operand. If at least one of the equivalent bits is 1, the comparison produces 1. The comparison produces 0 only if both bits are 0. This operation is resumed as follows:

Bit1 0 1 0 1

Bit2 0 0 1 1

Bit1 | Bit2 0 1 1 1

Once again, lets consider decimals 187 and 242. Their bitwise OR comparison would render the following result:

N1 N2 N1 | N2

1 1 1

0 1 1

1 1 1

Binary 1 1 0 1 0 0 1 1 0

1 1 1

1 0 1

Decimal 187 242 251

You can also let the compiler perform the operation and produce a result. Here is an example:

#include <iostream> using namespace std; main() { const int N1 = 187;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
const int N2 = 242; cout << N1 << " | " << N2 << " = " << (N1 | N2) << "\n\n"; return 0; } This would produce: 187 | 242 = 251

Comparing Bits: The Bitwise-Exclusive XOR Operator ^


Like the previous two operators, the bitwise-exclusive OR operator performs a bit comparison of two values. It syntax is:
Value1 ^ Value2

The compiler compares the bit of one value to the corresponding bit of the other value. If one of the bits is 0 and the other is 1, the comparison produces 1. In the other two cases, that is, if both bits have the same value, the comparison produces 0. This operation is resumed as follows:

Bit1 0 1 0 1

Bit2 0 0 1 1

Bit1 ^ Bit2 0 1 1 0

We will again consider decimals 187 and 242. Their bitwise-exclusive XOR comparison would render the following result:

N1 1 N2 1 N1 ^ N2 0

0 1 1

1 1 0

Binary 1 1 0 1 0 0 0 1 0

1 1 0

1 0 1

Decimal 187 242 73

If the compiler performs this operation, it can produce a result as in the following example:
#include <iostream> using namespace std; main() { const int N1 = 187; const int N2 = 242; } cout << N1 << " ^ " << N2 << " = " << (N1 ^ N2) << "\n\n";

This would produce:


187 ^ 242 = 73

Bit Shift Operators: The Left Shift <<


In the previous lesson, we learned that bits are aligned in some consecutive manner to store data as needed. One operation you can perform on such bits consists of moving bits in a direction of your choice. C++ provides the left shift operator represented with << and its syntax is:
Value << ConstantInteger

The left shift operator, <<, is a binary operator whose right operand must be a constant integer. When performing the operation, the compiler would push Values bits to the left by the number of ConstantInteger. The number of ConstantInteger bits on the left side of Value

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
would disappear. The bits on the left side of Value would replace them. After moving to the left, the space left by the most right bits would be filled with 0 bits. Imagine you have a variable named Value and whose value is 42. The binary value of 42 is 0010 1010 (you are probably asking, "Why the hell do I need to know this?" and my answer is, "I have no idea" but you ain't got no choice; ain't no one else gonna learn this stuff for you). Imagine you want to shift Value to the left by 2 bits. You would proceed as follows:

0 0 0 1

0 0

0 1 0 1 0 42 Shifted to the left by 2 bits << 2 1 0 1 0 0 0

The resulting binary number is 1010 1000 and its decimal value is 1*27 + 0*26 + 1*25 + 0*24 + 1*23 + 0*22 + 0*21 + 0*20 = 1*128 + 0*64 + 1*32 + 0*16 + 1*8 + 0*4 + 0*2 + 0*1 = 128 + 0 + 32 + 0 + 8 + 0 + 0 + 0 = 128 + 32 + 8 = 168 This can also be illustrated in the following program:
#include <iostream> using namespace std; main() { const int Value = 42; } cout << Value << " << 2 = " << (Value << 2) << "\n\n";

This would produce:


42 << 2 = 168

Bit Shift Operators: The Right Shift >>


As opposed to the left operator, the right shift moves bits to the right by a natural number. Everything is done as for the left shift except that the concept is applied to the opposed direction. Therefore, if you shift 42 to the right, the binary result would be 0000 1010, whose decimal value is 10.

Inline Assembly
Introduction
All the variables that we have used so far were declared in, and passed to, the random memory (RAM). Once a variable is declared and put in the memory, whenever it is involved in a calculation or assignment, the microprocessor sends a request to the memory to retrieve the value of the variable. The Central Processing Unit (CPU), also called the microprocessor, has its own memory. The microprocessor is made of memory cells called registers. Unlike the memory in the RAM, the access of the memory in the microprocessor is more precise; so precise that the registers are referred to by using their names. Some of the most commonly used registers (also called general purpose registers) are called EAX, EBX, ECX, EDX, ESI, etc. These registers are mostly used in the Assembly Language for low-level programming. Most modern compilers allow you to include Assembly Language code in your program. Using this feature, you can write a section or sections of Assembly language. When Assembly is included in your C++ program, it is referred to as Inline Assembly.

Passing Values to Registers


Using registers allows the programmer to write assignments directly destined for the microprocessor. The assignments and operations in the Assembly language are called instructions. When instructions are used by registers, the processing of the program is fast because the microprocessor does not have to retrieve the values of the variables in the RAM; these values, since existing in the registers, are readily available.

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
A section that has Assembly code starts with __asm followed by some other techniques. When the compiler encounters this keyword, it knows that the subsequent code would be in Assembly language and it would treat it accordingly. For example, instead of performing a calculation in the RAM, the following program will assign values to two integer variables, namely Number1 and Number2, then it calculate their sum of those two numbers and stores the result in another variable called Result. After the calculation, the Assembly section sends the result back to the C++ compiler to display the variables and their values:
#ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

int main( int argc, char * argv[] ) { int Number1, Number2, Result;

__asm { MOV Number1, 248 // Initialize Number1 MOV Number2, 405 // Initialize Number2 MOV EAX, Number1 // Put the value of Number1 in the EAX register ADD EAX, Number2 // Add the value of Number2 to the content of EAX MOV Result, EAX // Put the content of EAX into Result } // That's it

cout << "Number1 = " << Number1 << endl; cout << "Number2 = " << Number2 << endl; cout << "\nAfter adding Number1 to Number2," << endl; cout << "Result = " << Result << endl;

return 0; }

This would produce:


umber1 = 248 Number2 = 405

After adding Number1 to Number2, Result = 653

Previous

Copyright 2004-2009 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Introduction to Arrays
Arrays Fundamentals

Introduction

An array of airplanes

An array of bugs

An array of cards

An array of characters

When you look at the stuff on each group above, you realize that the items on each picture share a lot of characteristics, though each one still maintains specific features that set it apart from the others. Everyone of the items on the first picture is an airplane; if you decide to be specific, then you may state that the first airplane of the group is bright green while the second is black; the first and the fourth airplanes don't have helices although all the others do. On the second picture (from left to right), all of these items are bugs; they don't seem to look alike, but everyone of them is still a bug. If you play cards sometimes (Solitaire or FreeCell), then you are familiar with the third picture. Everyone of the items on the third picture is a card, same size, same white background, though they display different card values, different character colors (and they would have different effects depending on how your game is going). Whenever you are typing, you are aligning arrays of characters, characters as those of the last picture. This shows that a word or a sentence is actually a group or letters. An array is a group of items that can be identified as similar because they are of the same nature. Arrays come in two flavors: one dimensional and multi-dimensional arrays. Everyone of the pictures above represents a single dimensional array.

Declaring an Array
Just like any variable you are already familiar with, an array has to be declared before being used. Yet the difference this time is that you need to tell the compiler what kind of array you are defining, an array of books? An array of students? An array of billiard balls? An arrays of clothes? This is because, once more, the compiler wants to know how much space your array is going to occupy in the computer memory. This is because when you declare an array of items, the compiler puts each one of the items in an appropriate location. Like any other variable, the syntax of declaring an array is:
DataType ArrayName[dimension\order]

The array is first identified by its kind, which could be a char, an int, a float, etc; followed by

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
its name that follows the C++ naming rules. The name is then followed by square brackets that specify the dimension of the array or its size. Here are examples of declaring arrays:
int age[12]; float grade[100]; double angle[360];

int Age[12]; declares a group or array of 12 values, each one being an integer. float Grade[100]; declares an array of 100 floating-point values. double Angle[360]; declares an array of double-precision numbers. There are 360 of these items in the group.

Initializing an Array
Just like any variable can be initialized, an array also can be initialized. To accomplish this, for a one-dimensional array, the syntax used is:
DataType ArrayName[dimension] = { element1, element2, , elementn};

Therefore, you can start with the data type to specify the kind of array you are declaring. This is followed by the array name, and the square brackets. After specifying the dimension or not, and after the closing square bracket, type the assignment operator. The elements, also called items, that compose the array are included between an opening curly bracket '{' and a closing curly bracket '}'. Each item is separate from the next by a comma operator. As a normal C/C++ initialization, you end it with a semi-colon. Here are examples of declaring an initializing arrays:
int number[12] = {18, 42, 25, 12, 34, 15, 63, 72, 92, 26, 26, 12}; double distance[5] = {44.14, 720.52, 96.08, 468.78, 6.28};

If you have decided to initialize the array while you are declaring it, you can omit the dimension. Therefore, these arrays can be declared as follows:
int number[] = {18, 42, 25, 12, 34, 15, 63, 72, 92, 26, 26, 12}; double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28};

Processing the Elements of an Array


After initializing an array, its elements are counted from left to right. Each element of the array, also called a member of the array, has a specific and constant position. The position of an item is also called its index. The first member of the array, the most left, has an index of 0. The second member of the array has an index of 1. Since each array has a number of items which can be specified as n, the last member of the array has an index of n-1 Based on this system of indexing, to locate a member of an array, use its index in the group. Imagine you declare and initialize an array as follows:
double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28};

To locate the value of the 3 rd member of the array, you would type distance[2]. In the same way, the 1st member of the array can be located with distance[0]. Once you can locate a member of the array, you can display its value using cout. Here is an example:
#include <iostream> using namespace std; int main() { double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28}; cout << "2nd member = " << distance[1] << endl; cout << "5th member = " << distance[4] << endl;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} return 0;

This would produce:


2nd member = 720.52 5th member = 6.28

Using this approach, each member of the array can have its value accessed. Here is an example:
#include <iostream> using namespace std; int main() { double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28}; cout cout cout cout cout } << << << << << "Distance "Distance "Distance "Distance "Distance 1: 2: 3: 4: 5: " " " " " << << << << << distance[0] distance[1] distance[2] distance[3] distance[4] << << << << << endl; endl; endl; endl; endl;

return 0;

This would produce:


Distance Distance Distance Distance Distance 1: 2: 3: 4: 5: 44.14 720.52 96.08 468.78 6.28

The Size of an Array


When declaring an array, we saw that you must specify the number of items that the array is made of. Here is an example:
float averagePrice[45];

Depending on how you want to deal with your array, you may sometimes need to increase or decrease its dimension. To do this, you would need to locate the declaration of the array and change its dimension. If the program is long and the array is declared in some unusual place, this could take some time. The alternative is to define a constant prior to declaring the array and use that constant to hold the dimension of the array. Here is an example:
#include <iostream> using namespace std; int main() { const int numberOfItems = 5; double distance[numberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28}; cout cout cout cout cout } << << << << << "Distance "Distance "Distance "Distance "Distance 1: 2: 3: 4: 5: " " " " " << << << << << distance[0] distance[1] distance[2] distance[3] distance[4] << << << << << endl; endl; endl; endl; endl;

return 0;

You can use such a constant in a for loop to scan the array and access each of its members. Here is an example:
#include <iostream> using namespace std; int main() { const int numberOfItems = 5; double distance[numberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28};

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "Members of the array\n"; for(int i = 0; i < numberOfItems; ++i) cout << "Distance " << i + 1 << ": " << distance[i] << endl; } return 0;

In both cases, this would produce:


Members of the array Distance 1: 44.14 Distance 2: 720.52 Distance 3: 96.08 Distance 4: 468.78 Distance 5: 6.28

We knew the dimensions of the arrays we have used so far, because we could count the number of members of the array. Imagine you declare a large array, possibly made of 100 or 300 members, you wouldn't start counting the number of members. C/C++ provides the sizeof operator that can be used to get the dimension of an array. The syntax you would use is:
sizeof(ArrayName) / sizeof(DataType)

Imagine you declare an array as follows:


int number[] = {18, 42, 25, 12, 34, 15, 63, 72, 92, 26, 26, 12, 127, 4762, 823, 236, 84, 5};

Instead of counting the number of members of this array (it makes me dizzy when I try), you can use the sizeof operator as follows:
int NumberOfItemsOfTheArray = sizeof(Number)/sizeof(int);

One of the advantages of the sizeof operator used to get the number of members of the array is that it can be used on a for loop to scan an array, either to locate the members or to look for a value in the array. Here is an example of using this concept:
#include <iostream> using namespace std; int main() { double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28}; // Using the sizeof operator to get the dimension of the array int index = sizeof(distance) / sizeof(double); cout << "Array members and their values\n"; // Using a for loop to scan an array for(int i = 0; i < index; ++i) cout << "Distance : " << i + 1 << distance[i] << endl; } return 0;

This would produce:


Array members and their values Distance : 144.14 Distance : 2720.52 Distance : 396.08 Distance : 4468.78 Distance : 56.28

Filling Up an Array
When you declare an array without initializing it, we have mentioned that the compiler reserves an amount of memory space for the members of the array. But that is only what the compiler does. Each part of such reserved space is filled with garbage. Therefore, you must make sure that you know the value held by a member of the array before making any attempt to process the value held by that member of the array. Consider the following example:
#include <iostream>

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
using namespace std; int main() { const int numberOfItems = 5; double distance[numberOfItems]; cout cout cout cout cout } << << << << << "Distance "Distance "Distance "Distance "Distance 1: 2: 3: 4: 5: " " " " " << << << << << distance[0] distance[1] distance[2] distance[3] distance[4] << << << << << endl; endl; endl; endl; endl;

return 0;

This would produce:


Distance Distance Distance Distance Distance 1: 2: 3: 4: 5: -9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061

As you can see, the members of the array in the beginning don't have any recognizable value. There are two solutions to this problem. You can either initialize the array or request the values of the members of the array from the user. So far, when we used an array, we made sure to provide the exact number of members we needed for the array. We also saw that we could declare and initialize an array without specifying its dimension. The advantage of not specifying the dimension of the array is that we trust the compiler to find out the number of elements of the array. If you decide to specify the dimension of the array and initialize it, make sure you specify the elements less than or equal to the number you specified. Here is an example:
#include <iostream> using namespace std; int main() { const int numberOfItems = 5; double distance[numberOfItems] = {44.14, 720.52, 96.08}; cout cout cout cout cout } << << << << << "Distance "Distance "Distance "Distance "Distance 1: 2: 3: 4: 5: " " " " " << << << << << distance[0] distance[1] distance[2] distance[3] distance[4] << << << << << endl; endl; endl; endl; endl;

return 0;

This would produce:


Distance Distance Distance Distance Distance 1: 2: 3: 4: 5: 44.14 720.52 96.08 0 0

If you provide more members than the number of elements you specified, the compiler would provide garbage values to the extra members. Here is an example:
#include <iostream> using namespace std; int main() { const int NumberOfItems = 5; double distance[NumberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28}; cout << "Distance 1: " << distance[0] << endl; cout << "Distance 2: " << distance[1] << endl; cout << "Distance 3: " << distance[2] << endl;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout cout cout cout cout } << << << << << "Distance "Distance "Distance "Distance "Distance 4: 5: 6: 7: 8: " " " " " << << << << << distance[3] distance[4] distance[5] distance[6] distance[7] << << << << << endl; endl; endl; endl; endl;

return 0;

This would produce:


Distance 1: 44.14 Distance 2: 720.52 Distance 3: 96.08 Distance 4: 468.78 Distance 5: 6.28 Distance 6: 2.64214e-308 Distance 7: 2.12414e-314 Distance 8: 1.00532e-307

Depending on the compiler you are using, you would also receive a (strong) warning.

Streaming Array Members


We have already seen how to define an array, how to locate the elements of an array, and how to display the values of these elements (displaying the value of a member of an array is one aspect of streaming). The arrays we have seen so far had their dimensions and their elements defined by the programmer. Many times you will have to get these elements from the user. When you need to get an array from the user, first decide on what kind of array it is. Next, try to think of the maximum number of members you will need for the array. When you define an array and specify its dimension, the compiler will reserve the number of cells in memory that can accommodate your array. Here is an example:
int Page[5];

Each member of the array can be located using its index, as we have seen so far. In the same way, you can request the value of any member of the array using its index. In the following example, we declare an array of 5 integers and then we request the values of the 1 st and the 4 th members:
#include <iostream> using namespace std; int main() { const int counter = 5; int page[counter]; cout << "Enter the number of pages of your books\n"; cout << "Book 1: "; cin >> page[0]; cout << "Book 4: "; cin >> page[3]; cout << "\nSummary of books"; cout << "\nBook 1: " << page[0] << " pages"; cout << "\nBook 4: " << page[3] << " pages\n"; } return 0;

Here is an example of running the program:


Enter the number of pages of your books Book 1: 842 Book 4: 1204 Summary of books Book 1: 842 pages

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Book 4: 1204 pages

Operations on Arrays
Each member of an array is a pseudo-variable and can be processed as such. This means that you can add the values of two members of the array(Number[2]+Number[0]), you can subtract the value of one of the members from another member(member[1]-Number[4]). In the same way, you can perform multiplication, division, or remainder operations on members of an array. One of the regular operations performed on an array consists of adding the values of the members to produce a sum. Here is an example:
#include <iostream> using namespace std; int main() { // We know that we need a constant number of elements const int max = 10; int number[max]; // We will calculate their sum int sum = 0; cout << "Please type 10 integers.\n"; for( int i = 0; i < max; i++ ) { cout << "Number " << i + 1 << ": "; cin >> number[i]; sum += number[i]; } cout << "\n\nThe sum of these numbers is " << Sum << "\n\n"; } return 0;

This would produce: Please type 10 integers. Number 1: 120 Number 2: 42 Number 3: 75 Number 4: 38 Number 5: 904 Number 6: 6 Number 7: 26 Number 8: 55 Number 9: 92 Number 10: 20 The sum of these numbers is 1378 Another type of operation regularly performed on an array consists of looking for a value held by one of its members. For example, you can try to know if one of the members holds a particular value you are looking for. Here is an example:
#include <iostream> using namespace std; int main() { // Declare the members of the array int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89}; int find; int i, m = 8; cout << "Enter a number to search: "; cin >> find;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
for (i = 0; (i < m) && (Numbers[i] != Find); ++i) continue; // Find whether the number typed is a member of the array if (i == m) cout << find << " is not in the list" << endl; else cout << find << " is the " << i + 1 << "th element in the list" << endl; return 0;

This would produce: Enter a number to search: 44 44 is the 4th element in the list One of the most regular operations performed consists of comparing the values of different members to get the lowest value of the members. Here is an example:
// Example of finding the minimum member of an array #include <iostream> using namespace std; int main() { // The members of the array int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89}; int minimum = numbers[0]; int a = 8; // Compare the members for (int i = 1; i < a; ++i) { if (numbers[i] < minimum) minimum = numbers[i]; } // Announce the result cout << "The lowest member value of the array is " << minimum << "." << endl; } return 0;

This would produce:


The lowest member value of the array is 8.

You can use this same approach to get the maximum value of the members of an array. Here is an example:
// Example of finding the maximum member of an array #include <iostream> using namespace std; int main() { // The members of the array int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89}; int maximum = numbers[0]; int a = 8; // Compare the members for (int i = 1; i < a; ++i) { if (numbers[i] > maximum) maximum = numbers[i]; } // Announce the result cout << "The highest member value of the array is " << maximum << "." << endl; } return 0;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Arrays and Functions


An array can be passed to a function as argument. An array can also be returned by a function. To declare and define that a function takes an array as argument, declare the function as you would do for any regular function and, in its parentheses, specify that the argument is an array. Here is an example:
#include <iostream> using namespace std; void DisplayTheArray(double member[5]); int main() { const int numberOfItems = 5; double distance[numberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28}; } return 0;

void DisplayTheArray(double member[5]) { for(int i = 0; i < 5; ++i) cout << "\nDistance " << i + 1 << ": " << member[i]; cout << endl; }

You don't have to specify the dimension of the array. This means that you can leave the square brackets empty:
#include <iostream> using namespace std; void DisplayTheArray(double member[]); int main() { const int NumberOfItems = 5; double distance[NumberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28}; } return 0;

void DisplayTheArray(double member[]) { for(int i = 0; i < 5; ++i) cout << "\nDistance " << i + 1 << ": " << member[i]; cout << endl; }

We have already seen that when you declare an array, the compiler reserves an amount of memory space for the members of the array. To locate these members, the compiler aligns them in a consecutive manner. For example (hypothetically), if a member is located at 1804 Lockwood drive, the next member would be located at 1805 Lockwood Drive. This allows the compiler not only to know where the members of a particular array are stored, but also in what block (like the block houses of a city) the array starts. This means that, when you ask the compiler to locate a member of an array, the compiler starts where the array starts and moves on subsequently until it finds the member you specified. If the compiler reaches the end of the block but doesn't find the member you specified, it stops, instead of looking for it all over the computer memory. Based on this, when you call a function that has an array as argument, the compiler only needs the name of the array to process it. Therefore, the above function can be called as follows:
#include <iostream> using namespace std; void DisplayTheArray(double member[]) { for(int i = 0; i < 5; ++i) cout << "\nDistance " << i + 1 << ": " << member[i]; cout << endl; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
int main() { const int numberOfItems = 5; double distance[numberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28}; cout << "Members of the array"; DisplayTheArray(distance); } return 0;

This would produce:


Members of the array Distance 1: 44.14 Distance 2: 720.52 Distance 3: 96.08 Distance 4: 468.78 Distance 5: 6.28

The good scenario we have used so far is that we know the number of members of our array and we can directly use it in the function that is passed the argument. Imagine that we want the function to know how many members the array has and we want to let the function know while we are calling it, after all, in some circumstances, we will not always know how many members we want the function to process. This should easily be done as follows:
#include <iostream> using namespace std; void DisplayTheArray(double member[]) { for(int i = 0; i < 5; ++i) cout << "\nDistance " << i + 1 << ": " << member[i]; cout << endl; } int main() { const int NumberOfItems = 5; double distance[NumberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28}; cout << "Members of the array"; DisplayTheArray(distance[3]); } return 0;

Unfortunately, this program will not compile. Remember, we saw that the compiler wants only the name of the array, because the name by itself represents the whole array. distance[3] is a specific value of a member of the array, it is not a group of values. In other words, distance[3] is the same as 468.78. It is as if we want to pass 468.78 as the value to be treated and not as a subsequent group of values, because that is what an array is. Therefore, the compiler complains that you are passing a value after you have specifically stated that the argument was a group of values and not a single value. When you declare and define a function that takes an array as argument, if you plan to process the array, for example, if you want the calling function to control the number of elements to be processed, you should/must pass another argument that will allow the function to know how many members of the array would be considered. Such a function can be declared as follows:
#include <iostream> using namespace std; void DisplayTheArray(double mbr[], int count); int main() { double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12}; // Processing 5 members of the array cout << "Members of the array";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
DisplayTheArray(distance, 5); // Processing all members of the array int sizeOfArray = sizeof(Distance)/sizeof(double); cout << "\nMembers of the array"; DisplayTheArray(distance, sizeOfArray); } return 0;

void DisplayTheArray(double member[], int counter) { for(int i = 0; i < counter; ++i) cout << "\nDistance " << i + 1 << ": " << member[i]; cout << endl; }

This would produce:


Members of the array Distance 1: 44.14 Distance 2: 720.52 Distance 3: 96.08 Distance 4: 468.78 Distance 5: 6.28 Members of the array Distance 1: 44.14 Distance 2: 720.52 Distance 3: 96.08 Distance 4: 468.78 Distance 5: 6.28 Distance 6: 68.04 Distance 7: 364.55 Distance 8: 6234.12

Using this same concept of passing accompanying arguments, you can control how the called function would process the array. For example, you can specify the starting and end point to the processing of the array. Here is an example:
#include <iostream> using namespace std; // This function process an array but starts and ends at specific positions void DisplayTheArray(double mbr[], int Start, int End); int main() { double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12}; // Scan the array from the 3rd to the 7th member cout << "Members of the array"; DisplayTheArray(distance, 2, 6); } return 0;

void DisplayTheArray(double member[], int start, int ending) { for(int i = start; i < ending; ++i) cout << "\nDistance " << i + 1 << ": " << member[i]; cout << endl; }

This would produce:


Members of the array Distance 3: 96.08 Distance 4: 468.78 Distance 5: 6.28 Distance 6: 68.04

When declaring a function that takes an array argument, as we learned with other arguments, you don't have to provide a name to the argument. Simply typing the square brackets on the right side of the data type in the parentheses is enough. The name of the argument is only

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
necessary when defining the function. Therefore, the above function can be declared as follows:
#include <iostream> using namespace std; // This function process an array but starts and ends at specific positions void DisplayTheArray(double[], int, int); int main() { double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12}; // Scan the array from the 3rd to the 7th member cout << "Members of the array"; DisplayTheArray(distance, 2, 6); } return 0;

void DisplayTheArray(double member[], int Start, int Ending) { for(int i = Start; i < Ending; ++i) cout << "\nDistance " << i + 1 << ": " << member[i]; cout << endl; }

Two-Dimensional Arrays
Introduction
A 2-dimensional array is an array of arrays. In other words, it is an array where each member of the array is also an array. Consider the following table Country\Data United States Cameroon Map Flag Area (sq km) Population 9,629,091 475,440 272,639,608 15,456,092

Guatemala

108,890

12,335,580

Italy

301,230

56,735,130

Oman

212,460

2,446,645

Declaring and Initializing a 2-Dimensional Array


This two-dimensional array is made of rows and columns . Each column represents one category of data that everyone of the rows shares with the other rows. As different as each map looks, it still remains a map; each country on the table is known for its map, its flag, its area, and its population, though remaining different from the others. To see another twodimensional array, look at a calendar that displays a month with its week days. Like the above table, a 2-dimensional array is made rows and columns. To declare it, use double pair of a opening and closing square brackets. Here is an example:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
int numberOfStudentsPerClass[12][50];

This declaration creates a first group of 12 elements; it could be an array of 12 classes. Each element of the array contains 50 elements. In other words, each of the 12 members of the group is an array of 50 items. Simply stated, this declarations creates 12 classes and each class contains 50 students. Before using the members of an arrays, you should/must make sure you know the values that its members hold. As done with one-dimensional arrays, there are two ways you can solve this problem: you can initialize the array or you can get its values by another means. You can initialize an array the same way you would proceed the a one-dimensional array: simply provide a list of values in the curly brackets. A multidimensional array is represented as an algebraic matrix as MxN. This means that the array is made of M rows and N columns. For example, a 5x8 matrix is made of 5 rows and 8 columns. To know the actual number of members of a multidimensional array, you can multiply the number of rows by the number of columns. Therefore a 2x16 array contains 2*16=32 members. Based on this, when initializing a 2-dimensional array, make sure you provide a number of values that is less than or equal to the number of members. Here is an example:
double distance[2][4] = {44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12};

To locate a member of the array, this time, each must be identified by its double index. The first member is indexed at [0][0]. The second is at [0][1]. For a 2x4 array as this one, the 5th member is at [1][0]. You can use this same approach to display the values of the members of the array. Here is an example:
#include <iostream> using namespace std; int main() { // A 2-Dimensional array double distance[2][4] = {44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12}; // Scan the array from the 3rd to the 7th member cout << "Members of the array"; cout << "\nDistance [0][0]" << ": " << distance[0][0]; cout << "\nDistance [0][1]" << ": " << distance[0][1]; cout << "\nDistance [0][2]" << ": " << distance[0][2]; cout << "\nDistance [0][3]" << ": " << distance[0][3]; cout << "\nDistance [1][0]" << ": " << distance[1][0]; cout << "\nDistance [1][1]" << ": " << distance[1][1]; cout << "\nDistance [1][2]" << ": " << distance[1][2]; cout << "\nDistance [1][3]" << ": " << distance[1][3]; cout << endl; return 0;

This would produce:


Members of the array Distance [0][0]: 44.14 Distance [0][1]: 720.52 Distance [0][2]: 96.08 Distance [0][3]: 468.78 Distance [1][0]: 6.28 Distance [1][1]: 68.04 Distance [1][2]: 364.55 Distance [1][3]: 6234.12

To make the above array a little easier to read when initializing it, you can type the values of each row on its own line. For example, the above array can be initialized as follows:
double distance[2][4] = { 44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12 };

C++ also allows you to include each row in its own pair of curly brackets. You must separate each row from the next with a comma. Once again, this makes code easier to read. Here is an example:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
double distance[2][4] = { { 44.14, 720.52, 96.08, 468.78 }, { 6.28, 68.04, 364.55, 6234.12 } };

Processing a 2-Dimensional Array


To scan a 2-dimensional array, you should know how many columns the array contains. You can use two for loops to navigate the array. Here is an example:
#include <iostream> using namespace std; int main() { // A 2-Dimensional array double distance[][4] = { { 44.14, 720.52, 96.08, 468.78 }, { 6.28, 68.04, 364.55, 6234.12 } }; // Scan the array from the 3rd to the 7th member cout << "Members of the array"; for(int i = 0; i < 2; ++i) for(int j = 0; j < 4; ++j) cout << "\nDistance [" << i << "][" << j << "]: " << distance[i][j]; cout << endl; return 0;

This would produce the same result as previously.

Multidimensional Arrays
Multi-dimensional arrays are characterized by more than one line of representation. Here are examples of a three-dimensional arrays

Previous

Copyright 2000-2005 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Introduction to Pointers
Pointers Fundamentals
Introduction
When writing a program, you declare the necessary variables that you will need in order to accomplish your work. When declaring variables, you are simply asking the computer to reserve a set amount of space in its memory for a particular object you want to use. When you declare a variable, the computer reserves an amount of space for that variable, and uses the variable's name to refer to that memory space. This will allow you to store something, namely the value of that variable, in that space. Indeed, the computer refers to that space using an address. Therefore, everything you declare has an address, just like the address of your house. You can find out what address a particular variable is using.

A Review of References and Functions


Here are a few things you know already about writing a program: To use a variable, you declare it first to tell the compiler what kind of variable you are planning to use and what its name is . Once you declare a variable, the compiler reserves and assigns it a portion of space in memory and locates it there so that whenever you need that variable, you just call it and then use it. To use a function, you have to define it, tell the compiler what the function is supposed to do, and whether the function is supposed to give back a result or not, after it has performed its assignment. To see a variable's address, you can use the & operator followed by the name of the variable. For example, after declaring an integer as
int numberOfStudents;

you can find the address where the NumberOfStudents variable is located by using:
cout << &numberOfStudents;

This program would give you the address of the declared variable:
#include <iostream> using namespace std;

int main() { int value;

cout << "Value lives at " << &value;

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

After executing the program, you could get:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Value lives at: 0x0065FDF4

Using Pointers
Why Use Pointers?
Every time you declare a variable, the compiler puts it somewhere, which you can now refer to as an address. Once you know that address, you can use it. Like a reference, when you pass an argument to a function, the argument is passed using its address. This allows the calling function to dig into the address of the variable (the argument) and use the value directly. This transaction, like that of passing an argument by reference, allows the calling function to alter the real value of the argument. Using this ability, a pointer can allow you to return many values from a function; as opposed to a regular argument passing where the data, although changed inside of the calling function, will regain its previous value once the calling function is exited. Therefore, passing arguments as pointers allows a function to return many values, even if a function is declared as void. When you declare an array, you must specify the dimension of the array. That's already a problem: what if you don't know and don't want to know the dimension of the array? Pointers provide an ability that regular arrays do not have. Since pointers have a different and better system of managing memory, a pointer can store an array of almost any size; this is tremendous when dealing with arrays of characters or a whole text. Using this feature, when declaring a pointer in replacement of an array, you do not have to worry about the size of the array, the compiler will take care of that. Again, this feature allows you to pass pointers to a function (just like arrays) and return a value that has been altered even if the function is declared as void. This is even more dynamic with multidimensional arrays.

Definition
Pointers are not particularly useful when declared and used inside of one function. They show their capabilities when different functions (and/or objects) exchange data stored in those pointers. As you can see from the execution of the program above, the address of a variable is very difficult to read and interpret. Fortunately, we don't need to know that address and we don't need to know what it means or where the variable is located. C++ provides an alternative to this problem. Instead of referring to a variable's address directly, you are allowed to declare another variable, and then use that new variable to refer to the address of the variable you are interested in. A pointer is a variable that refers to another variable's address. Just like any variable in C++, you should declare and initialize a pointer variable before using it. To declare a pointer variable, use an identifier, followed by an asterisk (*), followed by the name of the pointer, and a semi-colon. Here is the formula:
DataType * PointerName;

The identifier should be one of those we have learned already. This means it could be an int, a char, a double, etc. The identifier should be the same type of identifier the pointer variable will point to. Therefore, if you are declaring a pointer that will point to an integer variable, the pointer identifier should be an integer. The asterisk (*) lets the compiler know that the variable that follows is a pointer. There are three ways you can type the asterisk. These are
DataType* PointerName; DataType * PointerName; DataType *pointerName;

By default, it does not matter how you append the *, the compiler will know that the thing that follows is a variable. Be careful when declaring various pointers. If you declare a few of them on the same line, like this:
DataType* pointer1, pointer2;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Only the first variable is a pointer, the second is a regular variable. If you want to declare different variables, you use:
DataType* pointer1, *pointer2;

Or
DataType* pointer1; DataType* pointer2;

Since the name of the pointer is indeed the name of a variable, you will follow the naming rules that govern every C++ variable.
#include <iostream> using namespace std;

int main() { int value; int *pointer;

cout << "Value lives at " << &value << "\n"; cout << "Pointer lives at " << &pointer;

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

After executing the program, you might get:


Value lives at: 0x0065FDF4 Pointer lives at: 0x0065FDF0

Initializing a Pointer
One of the reasons you are using a pointer is to find an alternative to knowing the address of a variable. Therefore, from now on, we are not interested in a variable's real address. Instead, we will use a pointer to point to that variable. As we have learned already, a variable should be initialized before being used. This allows the compiler to put something into the memory space allocated for that variable. To use a pointer P effectively, for its intended purpose, you need to tell the compiler that: pointer P will be used to point to the address of variable V. You do this by initializing the pointer. A pointer is initialized (almost) like any other variable, using the assignment operator (=). There are two main ways you can initialize a pointer. When declaring a pointer like this:
int* Pointer;

initialize it by following the assignment operator with & operator and the name of the variable, like this
int* Pointer = &Variable;

You can also initialize a pointer on a different line, after declaring it. This time, you should not use the asterisk on the Pointer, but the compiler should know that the pointer will point to a variable's address; therefore, the name of the variable will still use the &.
#include <iostream>

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
using namespace std;

int main() { int value = 12; int *pointer = &value;

cout << "Value lives at: " << value << "\n"; cout << "Pointer lives at: " << *pointer; cout << "\n\n"; return 0; }

The program would produce:


Value lives at: 12 Pointer lives at: 12

This program could also have the pointer initialized as:


#include <iostream> using namespace std;

int main() { int Value = 12; int *pointer;

cout << "Value lives at: " << value << "\n";

Pointer = &value; cout << "Pointer lives at: " << *pointer; cout << "\n\n"; return 0; }

And it would produce the same result. As another of the program, you can first declare both variables, then initialize them later on, when needed:
#include <iostream> using namespace std;

int main() { int value; int *pointer;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
pointer = &value; Value = 26; cout << "Value = " << value << "\n"; cout << "*Pointer = " << *pointer << "\n";

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

Once you have declare a variable and assign it to a pointer, during the course of your program, the value of a variable is likely to change, you can therefore assign it a different value:
#include <iostream> using namespace std;

int main() { int value; int *pointer;

Pointer = &value; Value = 26; cout << "Value = " << value << "\n"; cout << "*pointer = " << *pointer << "\n";

Value = 35; cout << "Value = " << value << "\n"; cout << "*pointer = " << *pointer << "\n";

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

As you know now, both *pointer and Value have the same value. This allows you to change the value of the pointer directly and affect the main variable meanwhile. Therefore, you can safely change the value of the pointer and it will be assigned accordingly. To see an example, make the following change to the file:
#include <iostream> using namespace std;

int main() { int value; int *pointer;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Pointer = &value; Value = 26; cout << "Value = " << value << "\n"; cout << "*pointer = " << *pointer << "\n";

Value = 35; cout << "Value = " << value << "\n"; cout << "*pointer = " << *pointer << "\n";

*pointer = 144; cout << "Value = " << value << "\n"; cout << "*pointer = " << *pointer << "\n";

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

This would produce:


Value = 26 *pointer = 26 Value = 35 *pointer = 35 Value = 144 *pointer = 144

A Pointer to a Pointer
Instead of pointing to a regular variable, a pointer can be made to point to another pointer. To apply this, always remember that you must specify what target a pointer is pointing to. Once again, consider the following example:
#include <iostream> using namespace std;

int main() { int value = 26; int *pointer;

pointer = &value;

cout << " Value

= " << value << "\n";

cout << "*Pointer = " << *pointer << "\n";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

return 0; }

This would produce:


Value = 26

*Pointer = 26

In this program, if necessary, you can declare a new variable that is a pointer that itself points to another pointer. When declaring such a variable, precede it with two *. After declaring the pointer, before using it, you must initialize it with a reference to a pointer, that is, a reference to a variable that was declared as a pointer. Here is an example:
#include <iostream> using namespace std;

int main() { int value = 26; int *pointer; int **pointerToPointer;

pointer = &value; pointerToPointer = &pointer;

cout << "

Value

= " << value << "\n";

cout << " *Pointer = " << *pointer << "\n"; cout << "**Pointer = " << **pointerToPointer << "\n";

return 0; }

This would produce:


Value = 26

*Pointer = 26 **Pointer = 26

Just as demonstrated earlier, after initializing a pointer, if you change the value of the variable it points to, the pointer would be updated. Consider the following program:
#include <iostream> using namespace std;

int main() { int value = 26; int *pointer; int **pointerToPointer;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

pointer = &value; pointerToPointer = &pointer;

cout << "

Value

= " << value << "\n";

cout << " *Pointer = " << *pointer << "\n"; cout << "**Pointer = " << **pointerToPointer << "\n";

value = 4805;

cout << "After changing the value of the main variable...\n"; cout << " Value = " << value << "\n";

cout << " *Pointer = " << *pointer << "\n"; cout << "**Pointer = " << **pointerToPointer << "\n";

return 0; }

This would produce:


Value = 26

*Pointer = 26 **Pointer = 26 After changing the value of the main variable... Value = 4805

*Pointer = 4805 **Pointer = 4805

Notice that, by changing the value of the original variable, when accessing its pointer or the pointer to its pointer, they reflect the new value. In the same way, instead of (directly) changing the value of the variable, you can change the value of its pointer. You can also change the value of the pointer to its pointer. Like a chain reaction, all variables would be updated. Consider the following program:
#include <iostream> using namespace std;

int main() { int value = 26; int *pointer; int **pointerToPointer;

pointer = &value; pointerToPointer = &pointer;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << " Value = " << value << "\n";

cout << " *Pointer = " << *pointer << "\n"; cout << "**Pointer = " << **pointerToPointer << "\n";

value = 4805;

cout << "\nAfter changing the value of the main variable...\n"; cout << " Value = " << value << "\n";

cout << " *Pointer = " << *pointer << "\n"; cout << "**Pointer = " << **pointerToPointer << "\n";

*pointer = -728;

cout << "\nAfter changing the value of the pointer...\n"; cout << " Value = " << value << "\n";

cout << " *Pointer = " << *pointer << "\n"; cout << "**Pointer = " << **pointerToPointer << "\n";

**pointerToPointer = 945580;

cout << "\nAfter changing the value of the pointer to pointer...\n"; cout << " Value = " << value << "\n";

cout << " *Pointer = " << *pointer << "\n"; cout << "**Pointer = " << **pointerToPointer << "\n";

return 0; }

This would produce:


Value = 26

*Pointer = 26 **Pointer = 26

After changing the value of the main variable... Value = 4805

*Pointer = 4805 **Pointer = 4805

After changing the value of the pointer... Value = -728

*Pointer = -728

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
**Pointer = -728

After changing the value of the pointer to pointer... Value = 945580

*Pointer = 945580 **Pointer = 945580

Operations on Pointers
Introduction
Consider that, added just a few rules, a pointer is a variable like any other: it can get its value from the user (indirectly), you can apply any of the algebraic operations we have learned, it can be incremented, it can be applied on a function, etc. A variable is a value that is supposed to change some time to time. Since a pointer is a variable whose value points to another variable, the value of a pointer is affected by the variable it points to. You can use this indirection to change the value of a pointer when changing its main variable. To get a value from the user, we have already learned that you can use the cin operator. When using a pointer to get a value from the user, don't forget the * operator, otherwise, the compiler would get confused. We have already learned how to request and display the value of a regular variable from the user:
#include <iostream> using namespace std;

int main() { int students;

cout << "Number of students: "; cin >> students;

cout << "\nNumber of students: " << students;

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

Once you have gotten a value and store it in a variable, it is available:


#include <iostream> using namespace std;

int main() { int students;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
int *ptrStudents;

ptrStudents = &students; cout << "Number of students: "; cin >> students; cout << "\nNumber of students: " << students << "\nThat is: " << *ptrStudents << " students."; cout << "\n\n"; return 0; }

This could produce:


Number of students: 24

Number of students: 24 That is: 24 students

In the same way, you can request a value from the user and store it in the pointer. To see an example, make the following change to the file:
#include <iostream> using namespace std;

int main() { int students; int *ptrStudents;

ptrStudents = &students; cout << "Number of students: "; cin >> *ptrStudents;

cout << "\nNumber of students: " << students << "\nThat is: " << *ptrStudents << " students.";

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

Of course, you can use various pointers on the same program. Apply an example by making the following changes:
#include <iostream> using namespace std;

int main()

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ int boys; int girls; int *ptrBoys; int *ptrGirls;

ptrBoys = &boys; ptrGirls = &girls;

cout << "Number of male students: "; cin >> *ptrboys;

cout << "Number of female students: "; cin >> *ptrGirls; cout << "\nNumber of students:";

cout << "\nBoys:" << "\t" << Boys << "\nThat is: " << *ptrBoys << " students."; cout << "\nGirls:" << "\t" << Girls << "\nThat is: " << *ptrGirls << " students.";

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

We have learned how to perform algebraic calculations and expressions in C++. When performing these operations on pointers, remember to use the * for each pointer involved. The calculations should be as smooth:
#include <iostream> using namespace std;

int main() { int boys; int girls; int total; int *ptrBoys; int *ptrGirls; int *ptrTotal;

ptrBoys = &boys; ptrGirls = &girls;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
ptrTotal = &total;

cout << "Number of male students: "; cin >> *ptrBoys; cout << "Number of female students: "; cin >> *ptrGirls;

cout << "\nNumber of students:"; cout << "\nBoys:" << "\t" << Boys << "\nThat is: " << *ptrBoys << " students."; cout << "\nGirls:" << "\t" << Girls << "\nThat is: " << *ptrGirls << " students.";

Total = Boys + Girls;

*ptrTotal = *ptrBoys + *ptrGirls;

cout << "\n\nTotal number of students: " << total; cout << "\nThere are " << *ptrTotal << " students";

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

This would produce:


Number of male students: 26 Number of female students: 24

Boys: 26 That is: 26 students Girls: 24 That is: 24 students

Total number of students: 50 There are 50 students

Passing Pointers to Functions


We know that a function uses arguments in order to carry its assignment. The arguments are usually provided to the function. When necessary, a function also declares its own variable to get the desired return value. Like other variables, pointers can be provided to a function, with just a few rules. When declaring a function that takes a pointer as an argument, make sure you use the

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
asterisk for the argument or for each argument. When calling the function, use the references to the variables. The function will perform its assignment on the referenced variable(s). After the function has performed its assignment, the changed value(s) of the argument(s) will be preserved and given to the calling function. Here is a starting file from what we have learned so far:
#include <iostream> using namespace std;

int main() { int shirts = 12; int pants = 5;

cout << "Shirts = " << shirts << endl; cout << "Pants = " << pants << endl;

cout << endl; return 0; }

This would produce:


Shirts = 12 Pants = 5

To pass arguments to a function, you can make the following changes:


#include <iostream> using namespace std;

int main() { int shirts = 3; int pants = 5; void Deposit(int s, int p);

cout << "When starting, within main():\n"; cout << "\tShirts = " << shirts << endl; cout << "\tPants = " << pants << endl;

Deposit(Shirts, Pants);

cout << "\n\nAfter calling Deposit(), within main():\n"; cout << "\tShirts = " << shirts << endl;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\tPants = " << pants << endl; cout << endl; return 0; }

void Deposit(int s, int p) { s = 8; p = 12;

cout << "Within Deposit()" << "\n\tShirts = " << s << "\n\tPants = " << p; }

After executing, the program would produce:


When starting, within main(): Shirts = 3 Pants = 5 Within Deposit() Shirts = 8 Pants = 12 After calling Deposit(), Within main(): Shirts = 3 Pants = 5

To pass pointer arguments, use the asterisks when declaring the function, and use the ampersand & when calling the function. Here is an example:
#include <iostream> using namespace std;

int main() { int shirts = 12; int pants = 5; void Deposit(int s, int p); void Pickup(int *sht, int *pt);

cout << "When starting, within main():\n"; cout << "\tShirts = " << shirts << endl; cout << "\tPants = " << pants << endl;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Deposit(shirts, pants); cout << "\n\nAfter calling Deposit(), within main():\n"; cout << "\tShirts = " << shirts << endl; cout << "\tPants = " << pants << endl;

Pickup(&shirts, &pants); cout << "\n\nAfter calling Pickup(), within main():\n"; cout << "\tShirts = " << shirts << endl; cout << "\tPants = " << pants << endl;

cout << endl; return 0; }

void Deposit(int s, int p) { s = 8; p = 5;

cout << "\nWithin Deposit()" << "\n\tShirts = " << s << "\n\tPants = " << p; }

void Pickup(int *sht, int *pt) { *sht *pt = 17; = 26;

cout << "\nWithin Pickup()" << "\n\tShirts = " << *sht << "\n\tPants = " << *pt; }

The result of executing the program is:


When starting, within main(): Shirts = 12 Pants = 5

Within Deposit() Shirts = 8 Pants = 5

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
After calling Deposit(), within main(): Shirts = 12 Pants = 5

Within Pickup() Shirts = 26 Pants = 17

After calling Pickup(), within main(): Shirts = 26 Pants = 17

A Function That Returns a Pointer


If you want a function to return a pointer, when declaring the function, make sure that you specify its return type as a pointer and you can use a type of your choice. Here is an example of such a declaration:
#include <iostream> using namespace std;

int main() { int *GetNumber();

return 0; }

In this case, we have declared a function named GetNumber that will return a pointer to int. When implementing the function, you can apply any of the techniques we have used so far inside the function. The most important rule to keep in mind is that the function must return a pointer and not a regular value. In the same way, when calling a function that returns a pointer, you can use its value only where the returned pointer is appropriate. For example, you can assign its returned value only to a pointer of the same type. Here is an example:
#include <iostream> using namespace std;

int main() { int *GetNumber(); int *number;

number = GetNumber();

cout << "Number = " << *number << endl; return 0;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
}

int *GetNumber() { int *a = new int(2885);

return a; }

This would produce:


Number = 2885

Pointers and Memory Management


By definition, the variables in your program are meant to "vary", that is, their values change regularly. When you declare a variable, such as
int Shirts;

the compiler reserves an appropriate amount of memory space for that particular variable. This is done when the program is compiling but before its execution. This means of providing memory space is called static allocation, the memory space is "allocated" to that variable. When the program executes, this static memory allocation does not change; but the memory space might be empty, especially if the variable is not initialized. This is important: the fact that a variable is not initialized means its memory space is empty, it is not equal to zero; it is simply empty. Nothing is occupying it. You can also ask the compiler to provide memory when the program is executing. This is called dynamic allocation. Dynamic allocation is performed using the new operator like this:
PointerName = new DataType;

The keyword new is required. The data type can be any of those we are already familiar with, but it must be appropriate to the variable it is pointing to. This means that, if it is pointing to an integer variable, the data type must be an integer. For example, our corresponding dynamic allocation would be:
ptrShirts = new int;

After dynamically allocating memory, you can assign a new value to the pointer for any purpose. Once the memory is not anymore in use, you should reclaim it. This is done with the delete keyword, like this:
delete ptrShirts;

Here is a starting point for this section :


#include <iostream> using namespace std;

int main() { int studentAge = 12;

cout << "Student age = " << studentAge << endl;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << endl; return 0; }

Now, let's add a pointer and try to access it without initializing it:
#include <iostream> using namespace std;

int main() { int studentAge = 12; int* age;

cout << "Student age = " << studentAge << endl; cout << "*Age = " << *age << endl;

cout << endl; return 0; }

You will get a value that is not insignificant. Depending on the compiler, you might even get a nasty dialog box and a warning. This is because you were trying to access a pointer that has not been initialized. You can initialize the pointer like this:
#include <iostream> using namespace std;

int main() { int studentAge = 12; int* age;

Age = &studentAge;

cout << "Student age = " << studentAge << endl; cout << "*Age = " << *age << endl;

cout << endl; return 0; }

To illustrate that an un-initialized variable has an address (although empty), you can change the file as follows:
#include <iostream>

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
using namespace std;

int main() { int studentAge; int* ptrAge;

ptrAge = &studentAge;

cout << "Student age = " << studentAge << endl; cout << "*ptrAge = " << *ptrAge << endl;

cout << endl; return 0; }

When you initialize a variable, its value gets stored in the memory space that was statically allocated by the compiler. In the same way, since its corresponding pointer points to its address, you can initialize the pointer and still access the value assigned to the variable it is pointing to. To see an example of a pointer, and not the variable itself being initialized, make the following changes to the file:
#include <iostream> using namespace std;

int main() { int studentAge; int *age;

age = &studentAge; cout << "Student age = " << studentAge << endl; cout << "*Age = " << *age << endl;

*Age = 15; cout << "Student age = " << studentAge << endl; cout << "*Age cout << "\n"; return 0; } = " << *age << endl;

This results in:


*Age

Student age = -858993460 = -858993460

Student age = 15

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
*Age = 15

To dynamically allocate memory, you assign the pointer with the new keyword followed by the appropriate identifier:
#include <iostream> using namespace std;

int main() { int studentAge; int *age;

age = &studentAge; cout << "Student age = " << studentAge << endl; cout << "*Age = " << *age << endl;

*age = 15; cout << "Student age = " << studentAge << endl; cout << "*Age = " << *age << endl;

age = new int; cout << "Student age = " << studentAge << endl; cout << "*Age cout << "\n"; return 0; } = " << *age << endl;

As you can see, since the value of the pointer has been dynamically assigned, its address is now empty. If you want to access its content, you have to reassign it another value; this is one of the mistakes that happen regularly in a program. When this happens, the program will compile fine, without any error or warning, but the result Therefore, you should always know the value of a pointer. In our example, you can reassign a value to the empty pointer:
age = new int; *Age = 17; cout << "Student age = " << studentAge << endl; cout << "*Age cout << "\n"; } = " << *age << endl;

After using a pointer, don't forget to clean your memory. You do this using the delete operator:
#include <iostream.h> int main() { int studentAge; int *age; age = &studentAge;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "Student age = " << studentAge << endl; cout << "*Age = " << *age << endl; *age = 15; cout << "Student age = " << studentAge << endl; cout << "*Age = " << *age << endl; Age = new int; *age = 17; cout << "Student age = " << studentAge << endl; cout << "*Age = " << *age << endl; delete age; cout << "\n"; return 0; }

Previous

Copyright 2000-2005 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Arrays and Pointers


The Relationship Between a Pointer and an Array
Introduction
Here is an example of an array as we learned when studying them: #include <iostream> using namespace std; int main() { int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; cout cout cout cout cout cout cout cout cout cout cout cout cout } In this case, the Number variable is an array of 12 integer values. Because a variable declared as array is first of all a variable, using its name, let us find its address. Consider the following program: #include <iostream> using namespace std; int main() { int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; cout << "\n Number : cout << "\n&Number : cout << "\n&number[0] : return 0; } This would produce: Number &Number : : 1245020 1245020 1245020 " << Number; " << &Number; " << &number[0] << endl; << << << << << << << << << << << << << "List of Numbers"; "\nNumber 1: " << "\nNumber 2: " << "\nNumber 3: " << "\nNumber 4: " << "\nNumber 5: " << "\nNumber 6: " << "\nNumber 7: " << "\nNumber 8: " << "\nNumber 9: " << "\nNumber 10: " << "\nNumber 11: " << "\nNumber 12: " << number[0]; number[1]; number[2]; number[3]; number[4]; number[5]; number[6]; number[7]; number[8]; number[9]; number[10]; number[11];

return 0;

&number[0] :

This demonstrates that Number, &Number, and &number[0] have the same value. As we learned with pointers, the use of the ampersand "&" allows us to get the address of a variable. Therefore, &Number gives us the address of the array variable. Furthermore, since &Number and &number[0] have the same value, and seeing that all three (Number, &Number, and &number[0]) have the same value, this demonstrates that the name of the variable in fact carries, or holds, or represents, the address of the first value of the array. In fact, consider the following program: #include <iostream>

using namespace std;

int main() {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

cout << "An integer occupies " << sizeof(int) << " bytes\n"; cout << "\n Number: " << Number;

cout << "\n&number[0]: " << &number[0] << endl; cout << "\n Number+1: " << Number+1;

cout << "\n&Number:[1] " << &number[1] << endl; cout << "\n Number+2: " << Number+2;

cout << "\n&Number:[2] " << &number[2] << endl;

return 0; } This would produce: An integer occupies 4 bytes

Number:

1245020

&number[0]: 1245020

Number+1:

1245024

&Number:[1] 1245024

Number+2:

1245028

&Number:[2] 1245028 Notice that, by adding numbers to the name of the variable, we are able to get the address of any member of the array.

Relating a Pointer to an Array


Now that we know that the name of an array holds the address of the first member of the array, we realize that we can declare a pointer of the same data type as the array and initialize it with the array. Here is an example: int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int *pNumbers = Number; After this declaration and initialization, Number and pNumbers have the same value: #include <iostream>

using namespace std;

int main() { int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int *pNumbers = Number;

cout << "Addresses"; cout << "\n Number : " << Number; " << pNumbers;

cout << "\npNumbers :

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return 0; } This would produce: Addresses Number : 1245020 1245020

pNumbers :

In other words, pNumbers points to the beginning of the array. As you can see from the previous result, pNumbers holds an address and not a value, that is, not the value of the first member of the array. Since pNumbers points to the first member of the array (by virtue of its relationship to the array, which we have demonstrated by showing that pNumbers and Number hold the same value, which is the same as the address of the first member of the array), to get the value that pNumbers holds, we learned, when studying pointers, that you must use the asterisk operator. Therefore, number[0], which is the value of the first member of the array, is the same as *pNumbers, which is the value of the first member of the array. This can be verified in the following program: #include <iostream>

using namespace std;

int main() { int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int *pNumbers = Number;

cout << "Values"; cout << "\n number[0] : : " << number[0]; " << *pNumbers;

cout << "\n*pNumber

return 0; } This would produce: Values number[0] : *pNumber : 31 31

We saw already that pNumbers is an address; it is not a value. In the same way, Number is an address. To get the value of a member of the Number array, we know that, using the square brackets, we can provide the index of the member we want and retrieve its value. In the same way, using a pointer that has been initialized to an array variable, we can use the square bracket and the index of the member whose value we want to retrieve. This is demonstrated in the following program: #include <iostream>

using namespace std;

int main() { int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int *pNumbers = Number;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

cout << "Addresses"; cout << "\n Number : " << Number; " << pNumbers;

cout << "\npNumbers :

cout << "\n\nValues"; cout << "\n Number [0] : cout << "\npNumbers[0] : cout << "\n Number [1] : cout << "\npNumbers[1] : " << number[0]; " << pNumbers[0]; " << number[1]; " << pNumbers[1];

return 0; } This would produce: Addresses Number : 1245020 1245020

pNumbers :

Values Number [0] : pNumbers[0] : Number [1] : pNumbers[1] : 31 31 28 28

At this time, we know how to get the address of the first member of the array, with either Number or pNumbers. To get the address of the second member of the array, we increment that address value, as in Number+1. Since Number is an address and not a value, adding 1 to it adds the size of its type, in this case 4 bytes, in order to get to the next address. In the same way, using a pointer that has been initialized with an array, to get the address of the next member of the array, simply increment its name. Here is an example: #include <iostream>

using namespace std;

int main() { int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int *pNumbers = Number;

cout << "Addresses"; cout << "\n Number cout << "\npNumbers : : " << Number; " << pNumbers; " << Number+1; " << pNumbers+1; " << Number+2; " << pNumbers+2;

cout << "\n Number +1 : cout << "\npNumbers+1 : cout << "\n Number +2 : cout << "\npNumbers+2 :

return 0;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} This would produce: Addresses Number pNumbers : : 1245020 1245020 1245024 1245024 1245028 1245028

Number +1 : pNumbers+1 : Number +2 : pNumbers+2 :

Now we know that by writing pNumbers or pNumbers+n, we get the address of the member that "lives" at pNumbers or pNumbers+n. We already saw that, by writing *pNumbers, we can get the value of the first member of the array. When writing *pNumbers, we are in fact asking the compiler to retrieve the value that pNumbers points to. If we want to get the value of the next member of the array, we must first give its address, which is done by adding the index of the member of the array to pNumbers. Once we have communicated the address, we use the asterisk operator to retrieve the actual value of the member of the array. Because the asterisk operator has a higher precedence than the addition operator, to get the address before the value, you must use parentheses to delimit the operation: #include <iostream>

using namespace std;

int main() { int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int *pNumbers = Number;

cout << "Values - Using the Array"; cout << "\n number[0]: cout << "\n number[1]: cout << "\n number[2]: cout << "\n number[3]: cout << "\n number[4]: " << number[0]; " << number[1]; " << number[2]; " << number[3]; " << number[4];

cout << "\n\nValues - Using the Pointer - No Parentheses"; cout << "\n*pNumbers: cout << "\n*pNumbers+1: cout << "\n*pNumbers+2: cout << "\n*pNumbers+3: cout << "\n*pNumbers+4: " << *pNumbers; " << *pNumbers+1; " << *pNumbers+2; " << *pNumbers+3; " << *pNumbers+4;

cout << "\n\nValues - Using the Pointer - With Parentheses"; cout << "\n*pNumbers: " << *pNumbers;

cout << "\n*(pNumbers+1): " << *(pNumbers+1); cout << "\n*(pNumbers+2): " << *(pNumbers+2); cout << "\n*(pNumbers+3): " << *(pNumbers+3); cout << "\n*(pNumbers+4): " << *(pNumbers+4);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return 0; } This would produce: Values - Using the Array number[0]: number[1]: number[2]: number[3]: number[4]: 31 28 31 30 31

Values - Using the Pointer - No Parentheses *pNumbers: *pNumbers+1: *pNumbers+2: *pNumbers+3: *pNumbers+4: 31 32 33 34 35

Values - Using the Pointer - No Parentheses *pNumbers: 31

*(pNumbers+1): 28 *(pNumbers+2): 31 *(pNumbers+3): 30 *(pNumbers+4): 31

Press any key to continue... Therefore, as long as you increment the address of the variable, you can use a for loop to navigate the array to get the value of each member of the array: #include <iostream>

using namespace std;

int main() { int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int *pNumbers = Number; int numberOfMembers = sizeof(Number) / sizeof(int);

cout << "List of Numbers"; for(int i = 0; i < NumberOfMembers; i++) cout << "\nNumber " << i + 1 << ": " << *(pNumbers+i);

return 0; }

A Pointer as Argument
Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Introduction
As we have seen so far, a function can use one or more arguments in order to carry its assignment. When necessary, a function also declares its own variable(s) to get the desired return value. A variable declared in the body of a function is referred to as a local variable. Here is an example: #include <iostream> using namespace std;

double

CalculateNetPrice(double disc);

int main() { double finalPrice; double discount = 20;

finalPrice = CalculateNetPrice(discount);

cout << "\nAfter applying a 20% discount"; cout << "\nFinal Price = " << finalPrice << "\n";

return 0; }

double {

CalculateNetPrice(double d)

double origPrice;

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

return origPrice - (origPrice * d / 100); } Here is an example of running the program: Please enter the original price: 125.55

After applying a 20% discount Final Price = 100.44 Press any key to continue Like other variables, a pointer can be passed to a function. When declaring and when implementing a function that takes a pointer as an argument, use the asterisk for the argument or for each argument. Here is an example: #include <iostream> using namespace std;

double

CalculateNetPrice(double *disc);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
int main() {

return 0; }

double {

CalculateNetPrice(double *discount)

double origPrice;

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

return origPrice - (origPrice * *discount / 100); } When calling the function, use the reference(s) to the variable(s). The function will perform its assignment on the referenced variable(s). After the function has performed its assignment, the changed value(s) of the argument(s) will be preserved and given to the calling function. Here is an example: int main() { double finalPrice; double discount = 20;

finalPrice = CalculateNetPrice(&discount);

cout << "\nAfter applying a 20% discount"; cout << "\nFinal Price = " << finalPrice << "\n";

return 0; } An example of running the program is: Please enter the original price: 100

After applying a 20% discount Final Price = 80

Practical Learning: Passing Pointers as Arguments


1. Create a new project named Fire Insurance2 2. Create a C++ source file named Main.cpp 3. Change the Main.cpp file as follows: #include <iostream> using namespace std;

double GetAnnualPremium();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
double GetCoverage(); double GetPolicy(); double CalculatePremium(double Rt, double Cvr, double Plc);

int main() { double Rate, Coverage, Policy, Premium;

cout << "Fire Insurance - Customer Processing\n"; Rate = GetAnnualPremium();

Coverage = GetCoverage(); Policy = GetPolicy();

Premium = CalculatePremium(Rate, Coverage, Policy);

cout << "\n********************************"; cout << "\nFire Insurance - Customer Quote"; cout << "\n________________________________"; cout << "\nAnnual Premium: $" << Rate; cout << "\nCoverage: cout << "\nPolicy: cout << "\nPremium: $" << Coverage; $" << Policy; $" << Premium;

cout << "\n********************************\n";

return 0; }

double GetAnnualPremium() { double AnlPrem;

cout << "Enter the annual premium: $"; cin >> AnlPrem; return AnlPrem; }

double GetCoverage() { double Cover;

cout << "Enter the coverage: $"; cin >> Cover; return Cover; }

double GetPolicy()

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ double Plc;

cout << "Enter the policy amount: $"; cin >> Plc; return Plc; }

double CalculatePremium(double Rate, double Cover, double Pol) { double Prem; int Unit;

Unit = Pol / Cover; Prem = Rate * Unit; return Prem; } 4. Test the program. Here is an example: Fire Insurance - Customer Processing Enter the annual premium: $0.55 Enter the coverage: $92 Enter the policy amount: $45000

******************************** Fire Insurance - Customer Quote ________________________________ Annual Premium: $0.55 Coverage: Policy: Premium: $92 $45000 $268.95

******************************** 5. Return to your programming environment 6. To process arguments as pointers and call the CalculatePremium() function within main(), change the program as follows:

#include <iostream> using namespace std;

double CalculatePremium(double *Rt, double *Cvr, double *Plc);

int main() { double Rate, Coverage, Policy, Premium;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "Fire Insurance - Customer Processing\n"; cout << "Enter the annual premium: $"; cin >> Rate; cout << "Enter the coverage: cout << "Enter the policy amount: $"; cin >> Coverage; $"; cin >> Policy;

Premium = CalculatePremium(&Rate, &Coverage, &Policy);

cout << "\n********************************"; cout << "\nFire Insurance - Customer Quote"; cout << "\n________________________________"; cout << "\nAnnual Premium: $" << Rate; cout << "\nCoverage: cout << "\nPolicy: cout << "\nPremium: $" << Coverage; $" << Policy; $" << Premium;

cout << "\n********************************\n";

return 0; }

double CalculatePremium(double *Rate, double *Cover, double *Pol) { double Prem; int Unit;

Unit = *Pol / *Cover; Prem = *Rate * Unit; return Prem; } 7. Test the application and return to your programming environment

The Effect of Passing a Pointer as Argument


Consider the following program: #include <iostream> using namespace std;

void GetTheOriginalPrice(double OrigPrice);

int main() { double OriginalPrice = 0;

cout << "First in main() --"; cout << "\nOriginal Price = $" << OriginalPrice << endl;

GetTheOriginalPrice(OriginalPrice);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\nBack in main() --"; cout << "\nOriginal Price = $" << OriginalPrice << endl;

return 0; }

void GetTheOriginalPrice(double OrigPrice) { cout << "\nNow we are in the GetTheOriginalPrice() function"; cout << "\nPlease enter the original price: "; cin >> OrigPrice;

cout << "\nIn the GetTheOriginalPrice() function"; cout << "\nOriginal Price = $" << OrigPrice << endl; } Here is an example of running the program: First in main() -Original Price = $0

Now we are in the GetTheOriginalPrice() function Please enter the original price: 100

In the GetTheOriginalPrice() function Original Price = $100

Back in main() -Original Price = $0

Notice that the value of the OriginalPrice variable is kept intact in the main() function, as 0, before and after calling the GetTheOriginalPrice() function. Like a reference, when passing a pointer as argument to a function, the function that is receiving the argument is in fact accessing the argument's address. Therefore, like a reference, the called function has the ability to alter the value held by the pointer. The effect is the same as for the reference: if the called function modifies the value of the pointer, that value is permanently changed. This is a feature you can use to your advantage. This effect is illustrated in the following program: #include <iostream> using namespace std;

void GetTheOriginalPrice(double *OrigPrice);

int main() { double OriginalPrice = 0;

cout << "First in main() --"; cout << "\nOriginal Price = $" << OriginalPrice << endl;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
GetTheOriginalPrice(&OriginalPrice);

cout << "\nBack in main() --"; cout << "\nOriginal Price = $" << OriginalPrice << endl;

return 0; }

void GetTheOriginalPrice(double *OrigPrice) { cout << "\nNow we are in the GetTheOriginalPrice() function"; cout << "\nPlease enter the original price: "; cin >> *OrigPrice;

cout << "\nIn the GetTheOriginalPrice() function"; cout << "\nOriginal Price = $" << *OrigPrice << endl; } Here is an example of executing this program: First in main() -Original Price = $0

Now we are in the GetTheOriginalPrice() function Please enter the original price: 100

In the GetTheOriginalPrice() function Original Price = $100

Back in main() -Original Price = $100

Press any key to continue... Notice that, this time, after calling the GetTheOriginalPrice() function, the value of the OriginalPrice variable is permanently changed and the second time it is accessed in the main() function, it holds a different value than the first time it was called.

Practical Learning: Passing Reference Pointers to Functions


1. To process variables by passing them as reference pointers, change the Main.cpp file as follows: #include <iostream> using namespace std;

void GetAnnualPremium(double *Prem); void GetCoverage(double *Cvr); void GetPolicy(double *Plc); double CalculatePremium(double *Rt, double *Cvr, double *Plc);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
int main() { double Rate, Coverage, Policy, Premium;

cout << "Fire Insurance - Customer Processing\n"; GetAnnualPremium(&Rate); GetCoverage(&Coverage); GetPolicy(&Policy);

Premium = CalculatePremium(&Rate, &Coverage, &Policy);

cout << "\n********************************"; cout << "\nFire Insurance - Customer Quote"; cout << "\n________________________________"; cout << "\nAnnual Premium: $" << Rate; cout << "\nCoverage: cout << "\nPolicy: cout << "\nPremium: $" << Coverage; $" << Policy; $" << Premium;

cout << "\n********************************\n";

return 0; }

void GetAnnualPremium(double *AnlPrem) { cout << "Enter the annual premium: $"; cin >> *AnlPrem; }

void GetCoverage(double *Cover) { cout << "Enter the coverage: $"; cin >> *Cover; }

void GetPolicy(double *Plc) { cout << "Enter the policy amount: $"; cin >> *Plc; }

double CalculatePremium(double *Rate, double *Cover, double *Pol) { double Prem; int Unit;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Unit = *Pol / *Cover; Prem = *Rate * Unit; return Prem; } 2. Test the application. Here is an example: Fire Insurance - Customer Processing Enter the annual premium: $0.74 Enter the coverage: $120 Enter the policy amount: $60000

******************************** Fire Insurance - Customer Quote ________________________________ Annual Premium: $0.74 Coverage: Policy: Premium: $120 $60000 $370

********************************

Press any key to continue... 3. Return to your programming environment

Constant Pointers as Arguments


The previous section demonstrates to us that, when passing a pointer as argument, the effect is the same as passing an argument as reference. This shows that, passing a pointer as argument gives the called function direct access to the address of the variable. Besides permanently changing the value of the argument, this process also speeds up code execution because the called function does not deal with a copy of the variable but the variable itself. Although there are various good reasons to pass pointers as arguments, sometimes you may not want the called function to modify the value held by the variable. In fact you can prevent this. If a function that receives a pointer as argument is not supposed to modify the value of the argument, you can pass the argument as a constant pointer. To do this, type the const keyword on the left side of the data type of the pointer argument. Here is an example: #include <iostream> using namespace std;

double

CalculateNetPrice(const double *Disc);

int main() { double FinalPrice; double Discount = 20;

FinalPrice = CalculateNetPrice(&Discount);

cout << "\nAfter applying a 20% discount";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\nFinal Price = " << FinalPrice << "\n";

return 0; }

double {

CalculateNetPrice(const double *Discount)

double OrigPrice;

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

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

Practical Learning: Passing Constant Pointers


1. To pass arguments as constant pointers, change the CalculatePremium() function as follows: #include <iostream> using namespace std;

void GetAnnualPremium(double *Prem); void GetCoverage(double *Cvr); void GetPolicy(double *Plc); double CalculatePremium( const double *Rt, const double *Cvr, const double *Plc );

int main() { double Rate, Coverage, Policy, Premium;

cout << "Fire Insurance - Customer Processing\n"; GetAnnualPremium(&Rate); GetCoverage(&Coverage); GetPolicy(&Policy);

Premium = CalculatePremium(&Rate, &Coverage, &Policy);

cout << "\n********************************"; cout << "\nFire Insurance - Customer Quote"; cout << "\n________________________________"; cout << "\nAnnual Premium: $" << Rate; cout << "\nCoverage: cout << "\nPolicy: cout << "\nPremium: $" << Coverage; $" << Policy; $" << Premium;

cout << "\n********************************\n";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return 0; }

void GetAnnualPremium(double *AnlPrem) { cout << "Enter the annual premium: $"; cin >> *AnlPrem; }

void GetCoverage(double *Cover) { cout << "Enter the coverage: $"; cin >> *Cover; }

void GetPolicy(double *Plc) { cout << "Enter the policy amount: $"; cin >> *Plc; }

double CalculatePremium( const double *Rate, const double *Cover, const double *Pol ) { double Prem; int Unit;

Unit = *Pol / *Cover; Prem = *Rate * Unit; return Prem; } 2. Test the application and return to your programming environment 3. Save All

Pointers and Multi-Dimensional Arrays


From our study of multidimensional arrays, we know how to create a two-dimension array as follows: #include <iostream>

using namespace std;

int main() {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
int number[2][6] = { { 31, 28, 31, 30, 31, 30 }, { 31, 31, 30, 31, 30, 31 } };

cout << "List of Numbers"; for(int i = 0; i < 2; i++) for(int j = 0; j < 6; j++) cout << "\nNumber [" << i << "][" << j << "]: " << number[i][j];

return 0; } In this case, Number is a variable that represents 2 groups of 6 integers each. From our first lesson on pointers, we saw that a pointer is simply created by providing a data type, followed by an asterisk, and followed by the name of the variable. Here is an example: int *pNumbers; We also established that this declaration by itself gives way to an array after an initialization. This means that we can safely assign the name of an array to the pointer and the pointer would be initialized. Since *pNumbers in this example is first of all a variable, to declare an array of this variable, simply add a dimension and the necessary square brackets required to declare any array. This can be done as follows: int *pNumbers[2]; This declaration creates two pointers, and each pointer points to an array of integers. After this declaration, you can initialize each pointer as you see fit. In fact, each pointer can point to an array of a different dimension. This means that one pointer can point to an array of 15 members and another pointer from this declaration can point to an array of 68 members. You have the choice. Since the compiler cannot predict and cannot decide on the number of members of each array, it is your responsibility to communicate this. If you want to use the members of an existing array to initialize the pointer, first specify which pointer you want to initialize, using its index. To access the first pointer, you would type *(pNumbers+0), which is the same as *(pNumbers) or *pNumbers. The second pointer can be accessed with *(pNumbers+1). Once you have specified which pointer you are interested in, you can initialize it with the desired dimension of the array. For a two-dimensional array, you would be initializing the pointer with the corresponding column, that is, the second index of the array. Here is an example: *(pNumbers+1) = number[3]; In this case, the second pointer points to the array that is the second column of the Number variable. Keep in mind that, this time, *pNumbers is a pointer and not a value. Therefore, to access a member of the array, you must first specify the desired pointer. Then, using its index, you can get the corresponding value. Here is an example: #include <iostream>

using namespace std;

int main() { int number[2][6] = { { 31, 28, 31, 30, 31, 30 }, { 31, 31, 30, 31, 30, 31 } };

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
int *pNumbers[2];

*pNumbers = number[0]; (*pNumbers)[0] (*pNumbers)[1] (*pNumbers)[2] (*pNumbers)[3] (*pNumbers)[4] (*pNumbers)[5] = number[0][0]; = number[0][1]; = number[0][2]; = number[0][3]; = number[0][4]; = number[0][5];

*(pNumbers+1) = number[1]; (*(pNumbers+1))[0] = number[1][0]; (*(pNumbers+1))[1] = number[1][1]; (*(pNumbers+1))[2] = number[1][2]; (*(pNumbers+1))[3] = number[1][3]; (*(pNumbers+1))[4] = number[1][4]; (*(pNumbers+1))[5] = number[1][5];

cout << "List of Numbers"; cout << "\n(*pNumbers)[0] cout << "\n(*pNumbers)[1] cout << "\n(*pNumbers)[2] cout << "\n(*pNumbers)[3] cout << "\n(*pNumbers)[4] cout << "\n(*pNumbers)[5] = " << (*pNumbers)[0]; = " << (*pNumbers)[1]; = " << (*pNumbers)[2]; = " << (*pNumbers)[3]; = " << (*pNumbers)[4]; = " << (*pNumbers)[5] << endl;

cout << "\n(*(pNumbers+1))[0] = " << (*(pNumbers+1))[0]; cout << "\n(*(pNumbers+1))[1] = " << (*(pNumbers+1))[1]; cout << "\n(*(pNumbers+1))[2] = " << (*(pNumbers+1))[2]; cout << "\n(*(pNumbers+1))[3] = " << (*(pNumbers+1))[3]; cout << "\n(*(pNumbers+1))[4] = " << (*(pNumbers+1))[4]; cout << "\n(*(pNumbers+1))[5] = " << (*(pNumbers+1))[5] << endl;

return 0; } This would produce: List of Numbers (*pNumbers)[0] (*pNumbers)[1] (*pNumbers)[2] (*pNumbers)[3] (*pNumbers)[4] (*pNumbers)[5] = 31 = 28 = 31 = 30 = 31 = 30

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
(*(pNumbers+1))[0] = 31 (*(pNumbers+1))[1] = 31 (*(pNumbers+1))[2] = 30 (*(pNumbers+1))[3] = 31 (*(pNumbers+1))[4] = 30 (*(pNumbers+1))[5] = 31

Press any key to continue...

Dynamic Arrays
Allocating Memory
Based on this relationship between arrays and pointers, you can use the new operator to dynamically create an array. This has the advantage of allowing you to allocate the desired amount of space and getting rid of it once not needed anymore. The syntax of dynamically creating an array of pointers is: DataType *ArrayName = new DataType[Dimensions]; To start, type the kind of array you want to create: this is the DataType. The ArrayName is a regular name you want to give to the variable. Since this is a pointer, the array name must be preceded by an asterisk operator. Assign the new operator to the array name. The new operator is followed by the same kind of data type of the first parameter, DataType. The the necessary number of members of the array as the Dimension. This Dimension is included between square brackets, as every array. Here are examples of dynamic arrays: double *Distance = new double[12]; unsigned int *pRanges = new unsigned int[120]; float *Prices = new float[44]; After dynamically creating an array, the compiler allocates the necessary memory space for all the members of the array, based on the data type and accommodating each. Just like any variable, the memory allocated for each member of the array contains garbage. It is your responsibility to fill it up for appropriate values. This can be taken care of by assigning a value to each member of the array. Each member of the array can be accessed by using its index on the name of the array. You have two options. You can apply the index of an array member on the name of the pointer. Here is an example: int *pNumbers = new int[12];

pNumbers[0] = 31; pNumbers[1] = 29; pNumbers[2] = 31; pNumbers[3] = 30; You can also access the address of the desired member, then assign it a value. Here is an example: int *pNumbers = new int[12];

*(pNumbers+4) = 31;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
*(pNumbers+5) = 30; *(pNumbers+6) = 31; *(pNumbers+7) = 31; In the same way, you can use either method to retrieve the value of a member of the array: #include <iostream> using namespace std;

int main() { int *pNumbers = new int[12];

pNumbers[0] pNumbers[1] pNumbers[2] pNumbers[3] *(pNumbers+4) *(pNumbers+5) *(pNumbers+6) *(pNumbers+7) *(pNumbers+8) *(pNumbers+9)

= 31; = 29; = 31; = 30; = 31; = 30; = 31; = 31; = 30; = 31;

pNumbers[10] = 30; pNumbers[11] = 31;

cout << "List of numbers"; cout << "\nNumber 1: cout << "\nNumber 2: cout << "\nNumber 3: cout << "\nNumber 4: cout << "\nNumber 5: cout << "\nNumber 6: cout << "\nNumber 7: cout << "\nNumber 8: cout << "\nNumber 9: " << *pNumbers; " << *(pNumbers+1); " << *(pNumbers+2); " << *(pNumbers+3); " << pNumbers[4]; " << pNumbers[5]; " << pNumbers[6]; " << pNumbers[7]; " << *(pNumbers+8);

cout << "\nNumber 10: " << *(pNumbers+9); cout << "\nNumber 11: " << pNumbers[10]; cout << "\nNumber 12: " << pNumbers[11];

return 0; } This would produce: List of numbers Number 1: 31

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Number 2: Number 3: Number 4: Number 5: Number 6: Number 7: Number 8: Number 9: 29 31 30 31 30 31 31 30

Number 10: 31 Number 11: 30 Number 12: 31

Press any key to continue...

Disposing of Memory
After using a pointer that was pointing to an array, when you do not need it anymore, you should delete it from memory and reclaim the space it was using. This is done using the delete operator. The syntax used is: delete [] VariableName; The required delete operator is used to let the compiler know that you want to delete a pointer variable that was pointing to an array. The delete keyword is followed by empty square brackets. These brackets allow the compiler to know that you are deleting a pointer to an array. You must use the square brackets and they must be empty. The VariableName must be the name of the pointer. Here is an example: #include <iostream>

using namespace std;

int main() { int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int *pNumbers = Number; int numberOfMembers = sizeof(Number) / sizeof(int);

cout << "List of Numbers"; for(int i = 0; i < NumberOfMembers; i++) cout << "\nNumber " << i + 1 << ": " << *(pNumbers+i);

delete [] pNumbers;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return 0; } This operation is usually performed on a dynamically created array, that is, on a pointer that was used to create an array. The formula is the same: after using the dynamic array, delete the pointer using the delete operator. To avoid memory leak, you can also assign NULL to the name of the array. Here is an example #include <iostream>

using namespace std;

int main() { const int Size = 12; int *pNumbers = new int[Size];

pNumbers[0] pNumbers[1] pNumbers[2] pNumbers[3] *(pNumbers+4) *(pNumbers+5) *(pNumbers+6) *(pNumbers+7) *(pNumbers+8) *(pNumbers+9)

= 31; = 28; = 31; = 30; = 31; = 30; = 31; = 31; = 30; = 31;

pNumbers[10] = 30; pNumbers[11] = 31;

cout << "List of numbers"; for(int i = 0; i < Size; i++) cout << "\nNumber " << i + 1 << ": " << *(pNumbers+i);

delete [] pNumbers; pNumbers = NULL;

return 0; }

Dynamic Multi-Dimensional Arrays


As done with the two-dimension array, to declare a pointer to a multi-dimensional array, type a name for the variable,

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
preceded by the pointers type and the asterisk operator. To make it an array, make sure you specify its dimension. Here is an example: int *pNumbers[2]; Since this creates two pointers, and each pointer is an array, you must initialize each pointer. This can be done using the new operator and following the same syntax used previously. For example, to specify the first pointer as an array of 8 members, you would type: *pNumbers = new int[8]; To provide a value to a member of the array, provide the address of its pointer and specify its index. After using a pointer, you should make sure you delete it and reclaim the memory it was using. This can be summarized as follows: #include <iostream>

using namespace std;

int main() { int *pNumbers[2];

*pNumbers = new int[0]; (*pNumbers)[0] (*pNumbers)[1] (*pNumbers)[2] (*pNumbers)[3] (*pNumbers)[4] (*pNumbers)[5] = 31; = 29; = 31; = 30; = 31; = 30;

*(pNumbers+1) = new int[1]; (*(pNumbers+1))[0] = 31; (*(pNumbers+1))[1] = 31; (*(pNumbers+1))[2] = 30; (*(pNumbers+1))[3] = 31; (*(pNumbers+1))[4] = 30; (*(pNumbers+1))[5] = 31;

cout << "List of Numbers"; cout << "\n(*pNumbers)[0] cout << "\n(*pNumbers)[1] cout << "\n(*pNumbers)[2] cout << "\n(*pNumbers)[3] cout << "\n(*pNumbers)[4] cout << "\n(*pNumbers)[5] = " << (*pNumbers)[0]; = " << (*pNumbers)[1]; = " << (*pNumbers)[2]; = " << (*pNumbers)[3]; = " << (*pNumbers)[4]; = " << (*pNumbers)[5] << endl;

cout << "\n(*(pNumbers+1))[0] = " << (*(pNumbers+1))[0]; cout << "\n(*(pNumbers+1))[1] = " << (*(pNumbers+1))[1];

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\n(*(pNumbers+1))[2] = " << (*(pNumbers+1))[2]; cout << "\n(*(pNumbers+1))[3] = " << (*(pNumbers+1))[3]; cout << "\n(*(pNumbers+1))[4] = " << (*(pNumbers+1))[4]; cout << "\n(*(pNumbers+1))[5] = " << (*(pNumbers+1))[5] << endl;

delete [] *pNumbers; delete [] *(pNumbers+1);

return 0; } This would produce; List of Numbers (*pNumbers)[0] (*pNumbers)[1] (*pNumbers)[2] (*pNumbers)[3] (*pNumbers)[4] (*pNumbers)[5] = 31 = 29 = 31 = 30 = 31 = 30

(*(pNumbers+1))[0] = 31 (*(pNumbers+1))[1] = 31 (*(pNumbers+1))[2] = 30 (*(pNumbers+1))[3] = 31 (*(pNumbers+1))[4] = 30 (*(pNumbers+1))[5] = 31

Press any key to continue...

Pointers and Arrays With Functions


Single Dimensional Arrays and Functions
When we studied arrays and functions, we saw that, to pass an array as argument to a function, you can type the name of the argument followed by parentheses. If you want to process the members of the array, you should also pass another argument that holds the number of members of the array. Here is an example: int SumOfNumbers(int Nbr[], int Size);

When calling such a function, the name of the argument is sufficient to the compiler: #include <iostream> using namespace std;

int {

SumOfNumbers(int Nbr[], int Size)

int Sum = 0; for(int i = 0; i < Size; i++) Sum += Nbr[i];

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return Sum; }

int main() { int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int numberOfMembers = sizeof(Number) / sizeof(int);

int Value = SumOfNumbers(number, numberOfMembers);

cout << "Sum of numbers: " << Value;

return 0; } This would produce: Sum of numbers: 365 When calling the function, the name of the array allows the compiler to pass the whole array because that name is in fact a pointer to the variable. Based on this, instead of passing an array as argument, you can instead use a pointer. We have established that, once a pointer has been initialized as holding the address of an array, the name of the array and the name of the pointer point to the same address. This means that you can also use the name of the pointer when calling such a function. Remember that the name of the pointer preceded by an asterisk is a value; therefore, you should not use it as argument when calling the function. Based on the relationship we have studied so far between pointers and arrays, the above program can also be written as follows: #include <iostream> using namespace std;

int {

SumOfNumbers(int *nbr, int size)

int sum = 0; for(int i = 0; i < size; i++) sum += nbr[i];

return Sum; }

int main() { int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int *pNumbers = number; int numberOfMembers = sizeof(number) / sizeof(int);

int Value = SumOfNumbers(pNumbers, numberOfMembers);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "Sum of numbers: " << Value;

return 0; } This would produce the same result.

Multi-Dimensional Arrays and Functions


To declare a function that takes a multi-dimensional array as argument, you can type the array name followed by an empty pair of square brackets, followed by a second pair of square brackets that contain the number of columns. If you are using a pointer as argument, for example a variable that points to a two-dimensional array, provide the type of variable followed by an asterisk that indicates that the argument is a pointer, and followed by a pair of square brackets. The square brackets can be empty or contain the number of columns. Such a function can be declared as follows: void DisplayNumbers(int *nbr[]);

Before calling such a function, after appropriately initializing the pointer, provide only the name of the pointer. Here is an example: #include <iostream> using namespace std; void DisplayNumbers(int *Nbr[]);

int main() { int number[2][6] = { { 31, 28, 31, 30, 31, 30 }, { 31, 31, 30, 31, 30, 31 } }; int *pNumbers[2]; *pNumbers = number[0]; (*pNumbers)[0] = number[0][0]; (*pNumbers)[1] = number[0][1]; (*pNumbers)[2] = number[0][2]; (*pNumbers)[3] = number[0][3]; (*pNumbers)[4] = number[0][4]; (*pNumbers)[5] = number[0][5]; *(pNumbers+1) = number[1]; (*(pNumbers+1))[0] = number[1][0]; (*(pNumbers+1))[1] = number[1][1]; (*(pNumbers+1))[2] = number[1][2]; (*(pNumbers+1))[3] = number[1][3]; (*(pNumbers+1))[4] = number[1][4]; (*(pNumbers+1))[5] = number[1][5]; cout << "List of Numbers"; DisplayNumbers(pNumbers); return 0; } void { DisplayNumbers(int *nbr[]) cout cout cout cout cout cout cout cout cout cout cout cout } If you want to process the argument in the function where it is passed as argument and if you would not know the dimension of the array in advance, you can pass two additional arguments that represent the rows and columns of the array. Here is an example: #include <iostream> using namespace std; << << << << << << << << << << << << "\n(*pNumbers)[0] "\n(*pNumbers)[1] "\n(*pNumbers)[2] "\n(*pNumbers)[3] "\n(*pNumbers)[4] "\n(*pNumbers)[5] "\n(*(pNumbers+1))[0] "\n(*(pNumbers+1))[1] "\n(*(pNumbers+1))[2] "\n(*(pNumbers+1))[3] "\n(*(pNumbers+1))[4] "\n(*(pNumbers+1))[5] = = = = = = = = = = = = " " " " " " " " " " " " << << << << << << << << << << << << (*nbr)[0]; (*nbr)[1]; (*nbr)[2]; (*nbr)[3]; (*nbr)[4]; (*nbr)[5] << endl; (*(nbr+1))[0]; (*(nbr+1))[1]; (*(nbr+1))[2]; (*(nbr+1))[3]; (*(nbr+1))[4]; (*(nbr+1))[5] << endl;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
void DisplayNumbers(int *Nbr[], int r, int c); int main() { int number[2][6] = { { 31, 28, 31, 30, 31, 30 }, { 31, 31, 30, 31, 30, 31 } }; int *pNumbers[2]; *pNumbers = number[0]; for(int i = 0; i < 6; i++) (*pNumbers)[i] = number[0][i]; *(pNumbers+1) = number[1]; for(int i = 0; i < 6; i++) (*(pNumbers+1))[i] = number[1][i]; cout << "List of Numbers"; DisplayNumbers(pNumbers, 2, 6); return 0; }

void {

DisplayNumbers(int *nbr[], int rows, int columns)

for(int i = 0; i < rows; i++) for(int j = 0; j < columns; j++) cout << "\nNumber[" << i << "][" << j << "]: " << (*(nbr+i))[j]; } Here is an example of executing this program: List of Numbers Number[0][0]: 31 Number[0][1]: 28 Number[0][2]: 31 Number[0][3]: 30 Number[0][4]: 31 Number[0][5]: 30 Number[1][0]: 31 Number[1][1]: 31 Number[1][2]: 30 Number[1][3]: 31 Number[1][4]: 30 Number[1][5]: 31

Previous

Copyright 1998-2005 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Pointers and Functions


Pointers to Functions
Introduction
Imagine you are writing a program to process cylinder-related calculations, that is, to get its diameter, its circumference, its areas, and volume. The formulas used are reviewed in our Geometric Formulas section. You could start your program as follows:

#include <iostream> using namespace std; int main() { double Radius; Radius = 25.55; cout << "Cylinder Summary"; cout << "\nRadius: " << Radius; return 0; } This would produce: Cylinder Summary Radius: 25.55 Press any key to continue... When we studied functions that return a value, we saw that the result of such a function can be assigned to a value locally declared in the calling function: #include <iostream> using namespace std; int main() { double Radius, Diameter; double CalculateDiameter(double R); Radius = 25.52; Diameter = CalculateDiameter(Radius); cout << "Cylinder Summary"; cout << "\nRadius: " << Radius; cout << "\nDiameter: " << Diameter; return 0; } double CalculateDiameter(double Rad) { return Rad * 2; } At this time, we know that when a function returns a value, the calling of the function is a complete value that can be assigned to a variable. In fact, when calling a function that takes an argument, if that argument itself is gotten from a value returned by a function, the calling of the second function can be done directly when calling the first function. This seemingly complicated scenario can be easily demonstrated as follows: #include <iostream> using namespace std; int main() { double Radius, Circumference; double CalculateDiameter(double R); double CalculateCircumference(double D);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Radius = 25.52; // // // // // // // // // // Instead of calling the CalculateDiameter() function first and assign it to another, locally declared variable, such as in "double Diameter = CalculateDiameter(Radius)", we can call the CalculateDiameter(Radius) directly when we are calling the CalculateCircumference() function. This is possible because the CalculateCircumference() function takes an argument that is the result of calling the CalculateDiameter() function. As long as we only need the circumference and we don't need the diameter, we don't have to explicitly call the CalculateDiameter() function.

Circumference = CalculateCircumference(CalculateDiameter(Radius)); cout << "Cylinder Summary"; cout << "\nRadius: " << Radius; cout << "\nCircumference: " << Circumference << endl; return 0; } double CalculateDiameter(double Rad) { return Rad * 2; } double CalculateCircumference(double Diam) { const double PI = 3.14159; return Diam * PI; } In some circumstances, such as this one, we may find out that the value we want to process in a function is in fact a value gotten from an intermediary function. Unfortunately, a regular function cannot be passed to a function like a regular variable. In reality, the C++ language allows this but the function must be passed as a pointer.

Practical Learning: Reviewing Functions


A loan is the amount of money a person or a company would borrow from another person or another company. There are various calculations involved in loan-related calculations. For example, when you borrow money from a bank, the bank applies a percentage of the amount you would pay each period of time which could be a few days, each month, each quarter, at the end of a year or after a few years. Whether you pay monthly or on another period, there is a total amount that the loan would have cost you at the end. In this and some other subsequent sections, we will review a few ways of processing loans. 1. Create a new C++ project named LoanProcessing1 2. Create a new source file named Main.cpp 3. Change the Main.cpp file as follows: #include <iostream> using namespace std; double GetPrincipal(); double GetInterestRate(); double GetPeriod(); int main() { double Principal, IntRate; int NumberOfPeriods; cout << "This program allows you to calculate the amount of money a " << "customer will owe at the end of the lifetime of a loan\n"; cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Principal = GetPrincipal(); IntRate = GetInterestRate(); NumberOfPeriods= GetPeriod(); cout cout cout cout cout cout cout << << << << << << << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; "\n=================================="; "\nEstimate on loan"; "\n----------------------------------"; "\nPrincipal: $" << Principal; "\nInterest: " << IntRate << "%"; "\nPeriod: " << NumberOfPeriods << " Months";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\n==================================\n"; return 0; } double GetPrincipal() { double P; cout << "Enter the Principal: $"; cin >> P; return P; } double GetInterestRate() { double r; cout << "Enter the Interest Rate (%): "; cin >> r; return r; } double GetPeriod() { double t; cout << "Enter the number of months: "; cin >> t; return t; } 4. Test the application. Here is an example: This program allows you to calculate the amount of money a customer will owe at the end of the lifetime of a loan %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Loan Processing Enter the Principal: $750 Enter the Interest Rate (%): 11.25 Enter the number of months: 8 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ================================== Estimate on loan ---------------------------------Principal: $750 Interest: 11.25% Period: 8 Months ================================== Press any key to continue... 5. Return to your programming environment 6. In the above program, the clerk was asked to provide the number of months for the period of the loan. Depending on the loan, one customer may want to specify the number of days necessary to pay the loan. Another customer may want to pay a loan over a number of years. To make this possible, we will allow the clerk to select the type of period for a loan. Change the Main.cpp file as follows: #include <iostream> using namespace std; double GetPrincipal(); double GetInterestRate(); double GetPeriod(int &PeriodType, double &NumberOfPeriods); int main() { double int int string a " << "customer will owe at the end of the lifetime of a loan\n"; cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Principal = GetPrincipal(); IntRate = GetInterestRate(); GetPeriod(TypeOfPeriod, Periods); if( TypeOfPeriod == 0 )

Principal, IntRate; TypeOfPeriod; Periods; PeriodName;

cout << "This program allows you to calculate the amount of money

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ // Since the user made a bad selection, stop the program here cout << "Press any key to stop..."; return 0; } "if" // condition produces true, the "return 0" means the function // would be terminated. If the condition is false, the inside of // this "if" condition would not execute and the function would // continue. This means that, if the condition is false, then // the "else' is implied. Therefore, we don't have to write an // "else" condition: it is automatic. if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; } cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; cout cout cout cout cout cout << << << << << << "\n=================================="; "\nEstimate on loan"; "\n----------------------------------"; "\nPrincipal: $" << Principal; "\nInterest: " << IntRate << "%"; "\nPeriod: " << Periods << PeriodName; // Since this "if" condition has a "return 0" line, if the

cout << "\n==================================\n"; return 0; } double GetPrincipal() { double P; cout << "Enter the Principal: $"; cin >> P; return P; } double GetInterestRate() { double r; cout << "Enter the Interest Rate (%): "; cin >> r; return r; } void GetPeriod(int &TypeOfPeriod, int &Periods) { cout << "How do you want to enter the length of time?"; cout << "\n1 - In Days"; cout << "\n2 - In Months"; cout << "\n3 - In Years"; cout << "\nYour Choice: "; cin >> TypeOfPeriod; if( TypeOfPeriod == 1 ) { cout << "Enter the number of days: "; cin >> Periods; } else if( TypeOfPeriod == 2 ) { cout << "Enter the number of months: "; cin >> Periods; } else if( TypeOfPeriod == 3 ) { cout << "Enter the number of years: "; cin >> Periods; } else { TypeOfPeriod = 0; // The user made an invalid selection. So, we will give up cout << "\nBad Selection\n";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} } 7. Test the application. Here is an example: This program allows you to calculate the amount of money a customer will owe at the end of the lifetime of a loan %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Loan Processing Enter the Principal: $1500 Enter the Interest Rate (%): 10.75 How do you want to enter the length of time? 1 - In Days 2 - In Months 3 - In Years Your Choice: 3 Enter the number of years: 2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ================================== Estimate on loan ---------------------------------Principal: $1500 Interest: 10.75% Period: 2 Years ================================== Press any key to continue... 8. Test the program again, making a different selection for the period. Here is an example: This program allows you to calculate the amount of money a customer will owe at the end of the lifetime of a loan %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Loan Processing Enter the Principal: $650 Enter the Interest Rate (%): 14.25 How do you want to enter the length of time? 1 - In Days 2 - In Months 3 - In Years Your Choice: 8 Bad Selection Press any key to stop... 9. Return to your programming environment 10. Create a new unit and save it as Loan 11. In the Loan.h file, create the following namespace and function: #ifndef LoanH #define LoanH

namespace Finance { double InterestAmount(double P, double r, double t); }

#endif 12. In the Loan.cpp file, implement the function as follows: #include "Loan.h"

namespace Finance { // Interest = Principal * rate * time in years double InterestAmount(double P, double r, double t) {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return P * (r / 100) * t; } } 13. To prepare a test of the function, change the Main.cpp as follows: #include <iostream> #include "Loan.h" using namespace std;

double GetPrincipal(); double GetInterestRate(); double GetPeriod(int &PeriodType, double &NumberOfPeriods);

int main() { double Principal, IntRate, Period, InterestAmount; int TypeOfPeriod;

double Periods; string PeriodName;

cout << "This program allows you to calculate the amount of money a " << "customer will owe at the end of the lifetime of a loan\n";

cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Principal IntRate Period = GetPrincipal(); = GetInterestRate(); = GetPeriod(TypeOfPeriod, Periods);

InterestAmount = Finance::InterestAmount(Principal, IntRate, Period);

if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, stop the program here cout << "Press any key to stop...";

return 0; }

if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; }

cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; cout << "\n=================================="; cout << "\nEstimate on loan"; cout << "\n----------------------------------"; cout << "\nPrincipal: $" << Principal; cout << "\nInterest: cout << "\nPeriod: " << IntRate << "%"; " << Periods << PeriodName;

cout << "\n--------------------------------"; cout << "\nInterest paid on Loan: $" << InterestAmount; cout << "\n==================================\n";

return 0; }

double GetPrincipal() { double P;

cout << "Enter the Principal: $"; cin >> P; return P; }

double GetInterestRate() { double r;

cout << "Enter the Interest Rate (%): "; cin >> r; return r; }

double GetPeriod(int &TypeOfPeriod, double &Periods) { cout << "How do you want to enter the length of time?"; cout << "\n1 - In Days"; cout << "\n2 - In Months"; cout << "\n3 - In Years"; cout << "\nYour Choice: "; cin >> TypeOfPeriod;

if( TypeOfPeriod == 1 ) {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "Enter the number of days: "; cin >> Periods; return Periods / 360; } else if( TypeOfPeriod == 2 ) { cout << "Enter the number of months: "; cin >> Periods; return Periods / 12; } else if( TypeOfPeriod == 3 ) { cout << "Enter the number of years: "; cin >> Periods; return Periods; } else { TypeOfPeriod = 0; // The user made an invalid selection. So, we will give up cout << "\nBad Selection\n"; return 0.00; } } 14. Test the program. Here is an example: This program allows you to calculate the amount of money a customer will owe at the end of the lifetime of a loan

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Loan Processing Enter the Principal: $650 Enter the Interest Rate (%): 10.25 How do you want to enter the length of time? 1 - In Days 2 - In Months 3 - In Years Your Choice: 1 Enter the number of days: 120 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

================================== Estimate on loan ---------------------------------Principal: $650 Interest: Period: 10.25% 120 Days

-------------------------------Interest paid on Loan: $22.2083 ==================================

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Press any key to continue... 15. Return to your programming environment

Declaring a Pointer to Function


A pointer to a function is a function that is declared as a pointer. Its name by itself is considered a variable. As such, and unlike a regular variable, the name of this function can be assigned a regular function. This allows the function to be passed as argument. The function itself is not implemented but its name is used as a programmer type-defined object. The reason a function can be passed as argument is because the name of a function is itself a constant pointer. The basic syntax to declare a pointer to a function is: DataType (*FunctionName)(); The DataType can be any of the data types we have used so far and objects we will learn in future lessons. The FunctionName must be a valid name for a function. The name of the function must be preceded by an asterisk operator. To actually make this declaration a pointer to a function, the asterisk and the name of the pointer must be included between parentheses. If you omit the parentheses, the compiler would think that you are declaring a function that would return a pointer, which changes everything. Because this is a pointer, you must use parentheses, required for every function declared. If this function will not take any argument, you can leave the parentheses empty or type void. Based on this, you can declare a pointer to a function as follows: #include <iostream> using namespace std;

int main() { void (*SomethingToDo)(void);

return 0; } After declaring a pointer to a function, keep in mind that this declaration only creates a pointer, not an actual function. In order to use it, you must define the actual function that would carry the assignment the function is supposed to perform. That function must have the same return type and the same (number of) argument(s), if any. For example, the above declared pointer to function is of type void and it does not take any argument. you can define a function as follows: void MovieQuote() { cout << "We went through a lot of trouble because of you\n"; cout << "You owe us\n"; cout << "\tFrom \"Disorganized Crime\"\n"; } With such an associated function defined, you can assign it to the name of the pointer to function as follows SomethingTodo = MovieQuote;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
This assignment gives life to the function declared as pointer. The function can then be called as if it had actually been defined. Here is an example: #include <iostream> using namespace std;

void MovieQuote() { cout << "We went through a lot of trouble because of you\n"; cout << "You owe us\n"; cout << " } From \"Disorganized Crime\"\n";

int main() { void (*SomethingToDo)();

// Assign the MovieQuote() function to the pointer to function SomethingToDo = MovieQuote;

// Call the pointer to function as if it had been defined already SomethingToDo();

return 0; } This would produce: We went through a lot of trouble because of you You owe us From "Disorganized Crime" You can also type the keyword between the return type and the opening parenthesis. You can also declare a pointer to function for a function that returns a value. Remember that both functions must return the same type of value (they must have the same signature). Here is an example: #include <iostream> using namespace std;

int Addition() { int a = 16, b = 442; return a + b; }

int main() { int (*SomeNumber)();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
// Assign the MovieQuote() function to the pointer to function SomeNumber = Addition;

// Call the pointer to function as if it had been defined already cout << "The number is " << SomeNumber();

return 0; } If you want to use a function that takes arguments, when declaring the pointer to function, provide the return type and an optional name for each argument. Here is an example: int (*SomeNumber)(int x, int y); When defining the associated function, besides returning the same type of value, make sure that the function takes the same number and type(s) of arguments. Here is an example: #include <iostream> using namespace std;

int Addition(int a, int b) { return a + b; }

int main() { int (*SomeNumber)(int x, int y); int x = 128, y = 5055;

// Assign the MovieQuote() function to the pointer to function SomeNumber = Addition;

// Call the pointer to function as if it had been defined already cout << x << " + " << y << " = " << SomeNumber(x, y);

return 0; } You can also create a programmer-defined type as a pointer to function. Here is the syntax to use: typedef (*TypeName)(Arguments); The typedef keyword must be used. The TypeName and its asterisk must be enclosed in parentheses. The name must follow the rules applied to objects so far. The TypeName must be followed by parentheses. If the pointer to function will take arguments, provide its type or their types between parentheses. Otherwise, you can leave the parentheses empty (but you must provide the parentheses). After creating such a custom type, the name of the type would be used as an alias to a pointer

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
to function. Consequently, it can be used to declare a pointer to function. Here is an example: #include <iostream> using namespace std;

int Addition(int a, int b) { return a + b; }

int main() { // Creating a programmer-defined type typedef int (*AddTwoIntegers)(int x, int y); // Now, the AddsTwoIntegers name is a pointer to function // that can take two integers. It can be used for a declaration

AddTwoIntegers TwoNumbers; int x = 128, y = 5055;

TwoNumbers = Addition;

// Call the pointer to function as if it had been defined already cout << x << " + " << y << " = " << TwoNumbers(x, y);

return 0; } This would produce: 128 + 5055 = 5183 Press any key to continue...

Practical Learning: Using a Pointer to Function


1. To declare and use a pointer to function, change the Main.cpp file as follows: #include <iostream> using namespace std;

#include "Loan.h"

double GetPrincipal(); double GetInterestRate(); double GetPeriod(int &PeriodType, double &NumberOfPeriods); double Addition(double Value1, double Value2) { return Value1 + Value2; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
int main() { double (*AddValues)(double R, double T);

double Principal, IntRate, Period, InterestAmount; int TypeOfPeriod;

double Periods; string PeriodName;

cout << "This program allows you to calculate the amount of money a " << "customer will owe at the end of the lifetime of a loan\n";

cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Principal IntRate Period AddValues = GetPrincipal(); = GetInterestRate(); = GetPeriod(TypeOfPeriod, Periods); = Addition;

InterestAmount = Finance::InterestAmount(Principal, IntRate, Period); double Amount = AddValues(Principal, InterestAmount);

if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, stop the program here cout << "Press any key to stop...";

return 0; }

if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; }

cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; cout << "\n==================================";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\nEstimate on loan"; cout << "\n----------------------------------"; cout << "\nPrincipal: $" << Principal; cout << "\nInterest: cout << "\nPeriod: " << IntRate << "%"; " << Periods << PeriodName;

cout << "\n--------------------------------"; cout << "\nInterest paid on Loan: $" << InterestAmount; cout << "\nTotal Amount Paid: $" << Amount;

cout << "\n==================================\n";

return 0; }

. . . No Change 2. Test the program. Here is an example: This program allows you to calculate the amount of money a customer will owe at the end of the lifetime of a loan

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Loan Processing Enter the Principal: $1500 Enter the Interest Rate (%): 12.55 How do you want to enter the length of time? 1 - In Days 2 - In Months 3 - In Years Your Choice: 3 Enter the number of years: 2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

================================== Estimate on loan ---------------------------------Principal: $1500 Interest: Period: 12.55% 2 Years

-------------------------------Interest paid on Loan: $376.5 Total Amount Paid: $1876.5

==================================

Press any key to continue... 3. Return to your programming environment 4. To create a programmer-define type based on the AddValues pointer to function name, click the Loan.h tab and create the type as follows:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#ifndef LoanH #define LoanH

namespace Finance { typedef double (*Add)(double R, double T);

double InterestAmount(double P, double r, double t); }

#endif 5. To declare and use a variable of the new defined type, change the Main.cpp file as follows:

#include <iostream>

using namespace std;

#include "Loan.h"

double GetPrincipal(); double GetInterestRate(); double GetPeriod(int &PeriodType, double &NumberOfPeriods); double Addition(double Value1, double Value2) { return Value1 + Value2; }

int main() { Finance::Add Plus; double Principal, IntRate, Period, InterestAmount; int TypeOfPeriod;

double Periods; string PeriodName;

cout << "This program allows you to calculate the amount of money a " << "customer will owe at the end of the lifetime of a loan\n";

cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Principal IntRate Period = GetPrincipal(); = GetInterestRate(); = GetPeriod(TypeOfPeriod, Periods);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Plus = TotalAmount; InterestAmount = Finance::InterestAmount(Principal, IntRate, Period); double Amount = Plus(Principal, InterestAmount);

if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, stop the program here cout << "Press any key to stop...";

return 0; }

. . . No Change

return 0; }

. . . 6. Test the application and return to your programming environment 7. To expand the Loan unit, we will add other types to perform all four arithmetic operations used to assist the functions that will be called to perform the calculations. In the Loan.h file, create the following programmer-defined types:

#ifndef LoanH #define LoanH

namespace Finance { typedef double (*Add)(double R, double T); typedef double (*Subtract)(double First, double Second); typedef double (*Multiply)(double First, double Second); typedef double (*Divide)(double First, double Second);

double InterestAmount(double P, double r, double t); }

#endif 8. Create a header file and save it as Main.h (make sure you include the .h extension) 9. To make the Main.cpp file less crowded, in the Main.h file, define the following accessory functions in their own namespace: #if !defined MainH #define MainH

#include <iostream>

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
using namespace std; namespace Accessories { // Accessory Functions

// This function adds two values double Addition(double Value1, double Value2) { return Value1 + Value2; }

// This function takes two arguments. // It subtracts the second from the first double Subtraction(double Value1, double Value2) { return Value1 - Value2; }

// This function multiplies two numbers double Multiplication(double Value1, double Value2) { return Value1 * Value2; }

// This function takes two arguments // If the second argument is 0, the function returns 0 // Otherwise, the first argument is divided by the second double Division(double Numerator, double Denominator) { if( Denominator == 0 ) return 0; // else is implied return Numerator / Denominator; } } // namespace Accessories

namespace LoanProcessing {

double GetPrincipal() { double P;

cout << "Enter the Principal: $"; cin >> P; return P; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
double GetInterestRate() { double r;

cout << "Enter the Interest Rate (%): "; cin >> r; return r; }

double GetPeriod(int &TypeOfPeriod, double &Periods) { cout << "How do you want to enter the length of time?"; cout << "\n1 - In Days"; cout << "\n2 - In Months"; cout << "\n3 - In Years"; cout << "\nYour Choice: "; cin >> TypeOfPeriod;

if( TypeOfPeriod == 1 ) { cout << "Enter the number of days: "; cin >> Periods; return static_cast<double>(Periods / 360); } else if( TypeOfPeriod == 2 ) { cout << "Enter the number of months: "; cin >> Periods; return static_cast<double>(Periods / 12); } else if( TypeOfPeriod == 3 ) { cout << "Enter the number of years: "; cin >> Periods; return static_cast<double>(Periods); } else { TypeOfPeriod = 0; // The user made an invalid selection. So, we will give up cout << "\nBad Selection\n"; return 0.00; } }

#endif

// MainH

10. To prepare a test for the new changes, change the Main.cpp file as follows:

#include <iostream>

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
using namespace std;

#include "Main.h" #include "Loan.h"

int main() { // Declare a variable of type Add, defined in the Finance namespace Finance::Add Plus;

double Principal, IntRate, Period, InterestAmount; int TypeOfPeriod;

double Periods; string PeriodName;

cout << "This program allows you to calculate the amount of money a " << "customer will owe at the end of the lifetime of a loan\n";

cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Principal IntRate Period Plus = LoanProcessing::GetPrincipal(); = LoanProcessing::GetInterestRate(); = LoanProcessing::GetPeriod(TypeOfPeriod, Periods); = Accessories::Addition;

InterestAmount = Finance::InterestAmount(Principal, IntRate, Period); double Amount = Plus(Principal, InterestAmount);

if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, stop the program here cout << "Press any key to stop...";

return 0; }

if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; } cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n";

cout << "\n=================================="; cout << "\nEstimate on loan"; cout << "\n----------------------------------"; cout << "\nPrincipal: $" << Principal; cout << "\nInterest: cout << "\nPeriod: " << IntRate << "%"; " << Periods << PeriodName;

cout << "\n--------------------------------"; cout << "\nInterest paid on Loan: $" << InterestAmount; cout << "\nTotal Amount Paid: $" << Amount;

cout << "\n==================================\n";

return 0; } 11. Test the application and return to your programming environment 12. Save All

A Pointer to a Function as Argument


your programming environmentUsing pointer to functions, a function can be passed as argument to another function. The function must be passed as a pointer. The argument is declared in a complete format as if you were declaring a function. Here is an example of a function that is passed a function as argument. double Circumference(double (*FDiam)(double R)) This Circumference() function takes one argument. The argument itself is a pointer to function. This argument itself takes a double-precision number as argument and it returns a doubleprecision value. The Circumference() function returns a double-precision number. It is important to know that the pointer to function that is passed as argument is declared completely, in this case as double (*FDiam)(double R) Although the FDiam declaration is accompanied by an argument, in this case R, this argument allows the compiler to know that FDiam takes an argument. This argument actually will not be processed by the Circumference() function when the Circumference() function is defined because the R argument does not belong to the Circumference() function. When calling the Circumference() function, you will use the FDiam argument as a variable in its own right, using its name, as in Circumference(Diameter) When defining the Circumference() function, you must process the pointer to function that it takes as argument. If this argument is an alias to a function that returns a value, you can call it and pass it the argument as we studied in the last section. If you want to involve the FDiam argument in any operation, you can declare a local variable to the Circumference() function. If the FDiam argument must be involved in an operation that involves a value external to the Circumference() function, you must pass that type of value as argument to the Circumference() function, unless you are using a global variable (we will study global variables when we review the issue of scopes). This means that, in most circumstances, the pointer to function passed as argument may be accompanied by at least one other argument. For example, if you want to use the FDiam as a diameter value to calculate the circumference (Circumference = Diameter * PI), you may have to declare it with an argument for the radius.

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
It would be declared as follows: double Circumference(double (*FDiam)(double R), double Rad); The function can then be implemented as follows: double Circumference(double (*FDiam)(double R), double Rad) { double Circf; const double PI = 3.14159; Circf = (*FDiam)(Rad);

return Circf * PI; }

Remember that, when declaring a function, the compiler does not care about the name(s) of the argument(s). If the function takes any, what the compiler cares about are the return type of the function, its name, and the type(s) of its argument(s), if any. Therefore, the above function could as well be declared as follows: double Circumference(double (*)(double R), double); This indicates that the Circumference() function takes two arguments whose names are not known. The first argument is a pointer to a function that takes one double-precision number as argument and returns a double. The second argument of the Circumference() function is also a double-precision number. The Circumference() function returns a double-precision number. This is what the program at this time would look like:

#include <iostream> using namespace std;

double Diameter(double); double Circumference(double (*D)(double R), double r);

int main() { double Radius;

Radius = 25.52;

cout << "Cylinder Summary"; cout << "\nRadius: " << Radius;

cout << "\nCircumference = " << Circumference(Diameter, Radius) << endl;

return 0; }

double Diameter(double Rad) { return Rad * 2;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
}

double Circumference(double (*FDiam)(double R), double Rad) { double Circf; const double PI = 3.14159; Circf = (*FDiam)(Rad);

return Circf * PI; } This would produce: Cylinder Summary Radius: 25.52

Circumference = 160.347

Press any key to continue... To simplify the declaration of a pointer to function, we saw that you can create a programmerdefined type using the typedef keyword. This can also help when passing a function as argument. Here is an example: typedef double (*FDiam)(double R); double Circumference(FDiam, double); When creating such a programmer-defined type, remember that you must give a name to the alias, in this case FDiam. After this creation, FDiam is an alias to a pointer to function of a double-precision type and which takes one double-precision number as argument. Remember, as we learned when studying functions that return a value, that the item on the right side of the return keyword can be a value or a complete expression. Therefore, you can simplify the implementation of the Circumference() function as follows:

double Circumference(double (*FDiam)(double R), double Rad) { const double PI = 3.14159; return (*FDiam)(Rad) * PI; }

Practical Learning: Passing a Function as Argument


1. To declare a function that takes another function as argument, in the Loan.h file, declare the following function: #ifndef LoanH #define LoanH namespace Finance { typedef double (*Add)(double R, double T); typedef double (*Subtract)(double First, double Second); typedef double (*Multiply)(double First, double Second); typedef double (*Divide)(double First, double Second); double InterestAmount(double P, double r, double t); double Rate(double (*AP)(double A, double P), double a, double p, double t); }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#endif 2. In the Loan.cpp, implement the function as follows: #include "Loan.h" #pragma package(smart_init) namespace Finance { // Interest = Principal * rate * time in years double InterestAmount(double P, double r, double t) { return P * (r / 100) * t; } double Rate(double (*AP)(double A, double P), double a, double p, double t) { double AMinusP = (*AP)(a, p); double Pt = p * t; return (AMinusP / Pt) * 100; } } 3. To provide a function used to get the future value of a loan, in the Main.h file, define a GetAmount() function as follows: #if !defined MainH #define MainH . . . No Change namespace LoanProcessing { double GetAmount() { double A; cout << "Enter the future value: $"; cin >> A; return A; } . . . No Change #endif // MainH

4. To call the new function, change the Main.cpp file as follows: #include <iostream> #include "Main.h" #include "Loan.h" using namespace std; using namespace Accessories; int main() { double int double string

Principal, Amount, IntRate, Period, InterestAmount; TypeOfPeriod; Periods; PeriodName;

cout << "This program allows you to perform estimations on loans\n"; cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Amount = LoanProcessing::GetAmount(); Principal = LoanProcessing::GetPrincipal(); Period = LoanProcessing::GetPeriod(TypeOfPeriod, Periods); IntRate = Finance::Rate(Subtraction, Amount, Principal, Period); if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, stop the program here cout << "Press any key to stop..."; return 0; } if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 )

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; } cout cout cout cout cout cout cout cout cout } 5. Test the application. Here is an example: This program allows you to perform estimations on loans %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Loan Processing Enter the future value: $4500 Enter the Principal: $3000 How do you want to enter the length of time? 1 - In Days 2 - In Months 3 - In Years Your Choice: 3 Enter the number of years: 3 ================================== Estimate on loan ---------------------------------Future Value: $4500 Principal: $3000 Period: 3 Years -------------------------------Interest on Loan: 16.6667% ================================== Press any key to continue... 6. To provide more options to the user and make the program more complete, you can create a menu, allowing the clerk to select the type of calculation. A customer may want to know how much time would be a better length of time to pay a loan. The customer may want to find the differences among the time (period), the rate of interest, the monthly payment the customer can afford, the length of time (the number of days, months or years the customer wants to pay the loan. To allow the user to select the type of calculation to perform, in the Main.h file, define the following functions: #if !defined MainH #define MainH << << << << << << << << << "\n=================================="; "\nEstimate on loan"; "\n----------------------------------"; "\nFuture Value: $" << Amount; "\nPrincipal: $" << Principal; "\nPeriod: " << Periods << PeriodName; "\n--------------------------------"; "\nInterest on Loan: " << IntRate << "%"; "\n==================================\n";

return 0;

#include <iostream>

#include "Loan.h"

using namespace std; namespace Accessories { // Accessory Functions

// This function adds two values double Addition(double Value1, double Value2) { return Value1 + Value2; }

// This function takes two arguments.

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
// It subtracts the second from the first double Subtraction(double Value1, double Value2) { return Value1 - Value2; }

// This function multiplies two numbers double Multiplication(double Value1, double Value2) { return Value1 * Value2; }

// This function takes two arguments // If the second argument is 0, the function returns 0 // Otherwise, the first argument is divided by the second double Division(double Numerator, double Denominator) { if( Denominator == 0 ) return 0; // else is implied return Numerator / Denominator; } } // namespace Accessories

namespace LoanProcessing {

double GetAmount() { double A;

cout << "Enter the future value: $"; cin >> A; return A; }

double GetPrincipal() { double P;

cout << "Enter the Principal: $"; cin >> P; return P; }

double GetInterestRate() { double r;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "Enter the Interest Rate (%): "; cin >> r; return r; }

double GetPeriod(int &TypeOfPeriod, double &Periods) { cout << "How do you want to enter the length of time?"; cout << "\n1 - In Days"; cout << "\n2 - In Months"; cout << "\n3 - In Years"; cout << "\nYour Choice: "; cin >> TypeOfPeriod;

if( TypeOfPeriod == 1 ) { cout << "Enter the number of days: "; cin >> Periods; return static_cast<double>(Periods / 360); } else if( TypeOfPeriod == 2 ) { cout << "Enter the number of months: "; cin >> Periods; return static_cast<double>(Periods / 12); } else if( TypeOfPeriod == 3 ) { cout << "Enter the number of years: "; cin >> Periods; return static_cast<double>(Periods); } else { TypeOfPeriod = 0; // The user made an invalid selection. So, we will give up cout << "\nBad Selection\n"; return 0.00; } }

int SelectCalculationType() { int Answer;

cout << "What kind of value do you want to estimate?"; cout << "\n1 - Calculate (only) the interest paid on the loan"; cout << "\n2 - Estimate the future value of the entire loan"; cout << "\nYour choice: "; cin >> Answer;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

return Answer; }

void ProcessInterestAmount() { double Principal, IntRate, Period, InterestAmount; int TypeOfPeriod;

double Periods; string PeriodName;

cout << "\nWe will calculate the interest amount payed on a loan\n"; cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Principal IntRate Period = LoanProcessing::GetPrincipal(); = LoanProcessing::GetInterestRate(); = LoanProcessing::GetPeriod(TypeOfPeriod, Periods);

InterestAmount = Finance::InterestAmount(Principal, IntRate, Period);

if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, stop the program here cout << "Press any key to stop...";

return; }

if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; } cout << "\n";

cout << "\n==================================";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\nEstimate on loan"; cout << "\n----------------------------------"; cout << "\nPrincipal: $" << Principal; cout << "\nInterest: cout << "\nPeriod: " << IntRate << "%"; " << Periods << PeriodName;

cout << "\n--------------------------------"; cout << "\nInterest paid on Loan: $" << InterestAmount; cout << "\n==================================\n"; }

void ProcessRateOfInterest() { double Principal, Amount, IntRate, Period; int TypeOfPeriod;

double Periods; string PeriodName;

cout << "\nWe will calculate the interest rate applied on a loan\n"; cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Amount = LoanProcessing::GetAmount();

Principal = LoanProcessing::GetPrincipal(); Period = LoanProcessing::GetPeriod(TypeOfPeriod, Periods);

IntRate = Finance::Rate(Accessories::Subtraction, Amount, Principal, Period);

if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, stop the program here cout << "Press any key to stop...";

return; }

if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 )

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ PeriodName = " Years"; }

cout << "\n=================================="; cout << "\nEstimate on loan"; cout << "\n----------------------------------"; cout << "\nFuture Value: $" << Amount; cout << "\nPrincipal: cout << "\nPeriod: $" << Principal; " << Periods << PeriodName;

cout << "\n--------------------------------"; cout << "\nInterest on Loan: " << IntRate << "%"; cout << "\n==================================\n"; }

#endif

// MainH

7. To test the new version of the program, change the Main.cpp file as follows: #include <iostream> #include "Main.h" #include "Loan.h" using namespace std; using namespace Accessories; using namespace LoanProcessing; int main() { int TypeOfCalculation; cout << "This program allows you to perform estimations on loans\n"; TypeOfCalculation = SelectCalculationType(); switch(TypeOfCalculation) { case 1: ProcessInterestAmount(); break; case 2: ProcessRateOfInterest(); break; default: cout << "\nInvalid Selection\n"; } return 0; } 8. Test the application and return to your programming environment 9. To allow the clerk to process other types of calculations, in the Loan.h file, declare the following functions: #ifndef LoanH #define LoanH namespace Finance { typedef double (*Add)(double R, double T); typedef double (*Subtract)(double First, double Second); typedef double (*Multiply)(double First, double Second); typedef double (*Divide)(double First, double Second); double InterestAmount(double P, double r, double t);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
double Rate(double (*AP)(double A, double P), double a, double p, double t); double TotalLoanAmount(double P, double r, double t); double PrincipalAmount(double (*RT)(double a, double b), double R, double T, double A); double Period(double (*AP)(double A, double P), double (*PR)(double P, double R), double a, double p, double r); double Period(double (*AP)(double A, double P), double a, double p, double r); } #endif 10. In the Loan.cpp file, implement the functions: #include "Loan.h" #pragma package(smart_init) namespace Finance { // Interest = Principal * rate * time in years double InterestAmount(double P, double r, double t) { return P * (r / 100) * t; } // Amount - Principal // Interest rate of a loan = -------------------// Principal * Period double Rate(double (*AP)(double A, double P), double a, double p, double t) { double AMinusP = (*AP)(a, p); double Pt = p * t; return (AMinusP / Pt) * 100; } // Amount = Principal(1 + Rate * Interest) double TotalLoanAmount(double P, double r, double t) { return P * (1 + ((r / 100) * t)); } // Amount // Principal = -----------------// 1 + Rate * Period double PrincipalAmount(double (*RT)(double a, double b), double R, double T, double A) { double RateOnTime = (*RT)(R/100, T); return A / (1 + RateOnTime); } // Amount - Principal // Interest rate of a loan = -------------------// Principal * Rate // The following function provides a very simplistic way to calculate the // length of time of a loan. In fact, there is no checking on the // periodic value (whether the value is in days, quarters, months, or // years, and there is no algorithm to check the value of the time double Period(double (*AP)(double A, double P), double (*PR)(double P, double R), double a, double p, double r) { double AMinusP = (*AP)(a, p); double PTimesR = (*PR)(p, r / 100); return AMinusP / PTimesR; } } 11. To expand the menu, change the Main.h file accordingly: #if !defined MainH #define MainH #include <iostream> #include "Loan.h" using namespace std;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
namespace Accessories { // Accessory Functions // This function adds two values double Addition(double Value1, double Value2) { return Value1 + Value2; } // This function takes two arguments. // It subtracts the second from the first double Subtraction(double Value1, double Value2) { return Value1 - Value2; } // This function multiplies two numbers double Multiplication(double Value1, double Value2) { return Value1 * Value2; } // This function takes two arguments // If the second argument is 0, the function returns 0 // Otherwise, the first argument is divided by the second double Division(double Numerator, double Denominator) { if( Denominator == 0 ) return 0; // else is implied return Numerator / Denominator; } // namespace Accessories

namespace LoanProcessing { double GetAmount() { double A; cout << "Enter the future value: $"; cin >> A; return A; } double GetPrincipal() { double P; cout << "Enter the Principal: $"; cin >> P; return P; } double GetInterestRate() { double r; cout << "Enter the Interest Rate (%): "; cin >> r; return r; } double GetPeriod(int &TypeOfPeriod, double &Periods) { cout << "How do you want to enter the length of time?"; cout << "\n1 - In Days"; cout << "\n2 - In Months"; cout << "\n3 - In Years"; cout << "\nYour Choice: "; cin >> TypeOfPeriod; if( TypeOfPeriod == 1 ) { cout << "Enter the number of days: "; cin >> Periods; return static_cast<double>(Periods / 360); } else if( TypeOfPeriod == 2 ) { cout << "Enter the number of months: "; cin >> Periods; return static_cast<double>(Periods / 12); } else if( TypeOfPeriod == 3 ) { cout << "Enter the number of years: "; cin >> Periods; return static_cast<double>(Periods); } else { TypeOfPeriod = 0; // The user made an invalid selection. So, we will give up cout << "\nBad Selection\n"; return 0.00;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} } int SelectCalculationType() { int Answer; cout << "What kind of value do you want to estimate?"; cout << "\n1 - Calculate (only) the interest paid on the loan"; cout << "\n2 - Calculate the total amount owed on a loan"; cout << "\n3 - Estimate the interest rate applied on a loan"; cout << "\n4 - Find the amount given as loan"; cout << "\n5 - Find the approximate length of time of a loan"; cout << "\nYour choice: "; cin >> Answer; return Answer; } void ProcessInterestAmount(bool GetTotalAmount = false) { double Principal, Amount, IntRate, Period, InterestAmount; int TypeOfPeriod; double Periods; string PeriodName; cout << "\n====================================================="; cout << "\nWe will calculate the interest amount payed on a loan\n"; cout << "\n====================================================="; cout << "\nLoan Processing\n"; Principal = LoanProcessing::GetPrincipal(); IntRate = LoanProcessing::GetInterestRate(); Period = LoanProcessing::GetPeriod(TypeOfPeriod, Periods); if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, get out of the function cout << "\nThe program will stop"; return; } InterestAmount = Finance::InterestAmount(Principal, IntRate, Period); Amount = Finance::TotalLoanAmount(Principal, IntRate, Period); if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; } cout << "\n"; cout << "\n=================================="; cout << "\nEstimate on loan"; cout << "\n----------------------------------"; cout << "\nPrincipal: $" << Principal; cout << "\nInterest: " << IntRate << "%"; cout << "\nPeriod: " << Periods << PeriodName; cout << "\n--------------------------------"; cout << "\nInterest paid on Loan: $" << InterestAmount; if( GetTotalAmount == true ) cout << "\nTotal Amount Paid: $" << Amount; cout << "\n==================================\n"; } void ProcessRateOfInterest() { double Principal, Amount, IntRate, Period; int TypeOfPeriod; double Periods; string PeriodName; cout << "\n====================================================="; cout << "\nWe will calculate the interest rate applied on a loan\n"; cout << "\n====================================================="; cout << "\nLoan Processing\n"; Amount = LoanProcessing::GetAmount(); Principal = LoanProcessing::GetPrincipal(); Period = LoanProcessing::GetPeriod(TypeOfPeriod, Periods); if( TypeOfPeriod == 0 ) {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
// Since the user made a bad selection, get out of the function cout << "\nThe program will stop"; return; } IntRate = Finance::Rate(Accessories::Subtraction, Amount, Principal, Period); if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; } cout cout cout cout cout cout cout cout cout } void ProcessPrincipal() { double Principal, Amount, IntRate, Period; int TypeOfPeriod; double Periods; string PeriodName; cout << cout << cout << cout << Amount IntRate Period "\n=================================================="; "\nWe will calculate the principal value of the loan"; "\n=================================================="; "\nLoan Processing\n"; = LoanProcessing::GetAmount(); = LoanProcessing::GetInterestRate(); = LoanProcessing::GetPeriod(TypeOfPeriod, Periods); << << << << << << << << << "\n=================================="; "\nEstimate on loan"; "\n----------------------------------"; "\nFuture Value: $" << Amount; "\nPrincipal: $" << Principal; "\nPeriod: " << Periods << PeriodName; "\n--------------------------------"; "\nInterest on Loan: " << IntRate << "%"; "\n==================================\n";

if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, get out of the function cout << "\nThe program will stop"; return; } Principal = Finance::PrincipalAmount(Accessories::Multiplication, IntRate, Period, Amount); if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; } cout cout cout cout cout cout cout cout cout } void ProcessPeriod() { double Principal, Amount, IntRate, TimeSpan; int TypeOfPeriod; double Periods; string PeriodName; cout << cout << cout << cout << Amount "\n====================================================="; "\nWe will calculate the amount of time to pay a loan\n"; "\n====================================================="; "\nLoan Processing\n"; = LoanProcessing::GetAmount(); << << << << << << << << << "\n=================================="; "\nEstimate on loan"; "\n----------------------------------"; "\nFuture Value: $" << Amount; "\nInterest on Loan: " << IntRate << "%"; "\nPeriod: " << Periods << PeriodName; "\n--------------------------------"; "\nPrincipal: $" << Principal; "\n==================================\n";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Principal = LoanProcessing::GetPrincipal(); IntRate = LoanProcessing::GetInterestRate(); TimeSpan = Finance::Period(Accessories::Subtraction, Accessories::Multiplication, Amount, Principal, IntRate); cout << "\n=================================="; cout << "\nEstimate on loan"; cout << "\n----------------------------------"; cout << "\nFuture Value: $" << Amount; cout << "\nPrincipal: $" << Principal; cout << "\nInterest on Loan: " << IntRate << "%"; cout << "\n--------------------------------"; cout << "\nPeriod: " << TimeSpan * 12 << " Months"; cout << "\n==================================\n"; } } #endif // MainH

12. To prepare for a test, in the Main.cpp, add the new options in the main() function: #include <iostream> #include "Main.h" #include "Loan.h" using namespace std; using namespace Accessories; using namespace LoanProcessing; int main() { int TypeOfCalculation; cout << "This program allows you to perform estimations on loans\n"; TypeOfCalculation = SelectCalculationType(); switch(TypeOfCalculation) { case 1: ProcessInterestAmount(); break; case 2: ProcessInterestAmount(true); break; case 3: ProcessRateOfInterest(); break; case 4: ProcessPrincipal(); break; case 5: ProcessPeriod(); break; default: cout << "\nInvalid Selection\n"; } return 0; } 13. Test the application. Here is an example: This program allows you to perform estimations on loans What kind of value do you want to estimate? 1 - Calculate (only) the interest paid on the loan 2 - Calculate the total amount owed on a loan 3 - Estimate the interest rate applied on a loan 4 - Find the amount given as loan 5 - Find the approximate length of time of a loan Your choice: 5 ===================================================== We will calculate the amount of time to pay a loan ===================================================== Loan Processing Enter the future value: $824 Enter the Principal: $800 Enter the Interest Rate (%): 9 ================================== Estimate on loan ---------------------------------Future Value: $824 Principal: $800

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Interest on Loan: 9% -------------------------------Period: 4 Months ================================== Press any key to continue... 14. Return to your programming environment and save everything

An Array of (Pointers to) Functions


To further refine the call to a group of functions that perform the same kind of task, you can declare an array of pointers to a type of function. Before creating an array of pointers to function, you must first know or have the functions you would be referring to. These functions must have a similar signature. This means that they must return the same type of value, they have the same type(s) of must have the same number of arguments and they must argument(s). Here are examples of such functions: double Diameter(double Radius) { return Radius * 2; } double Circumference(double Radius) { return Diameter(Radius) * PI; } double Area(double Radius) { return Radius * Radius * PI; } To declare an array of pointers to function, you can first define an alias to the variable. This is an example: typedef double (*Measure)(double R); After this definition, as we learned already, Measure is an alias to a function that takes a double type of variable and returns a double value. Using this name, you can declare an array of functions. The members of the array are names of the functions that would compose the array. Here is an example: Measure Calc[] = { Diameter, Circumference, Area }; You can initialize each member using its index and calling the corresponding function. This can be done as follows: #include <iostream> using namespace std; const double PI = 3.14159; double Diameter(double Radius) { return Radius * 2; } double Circumference(double Radius) { return Diameter(Radius) * PI; } double Area(double Radius) { return Radius * Radius * PI; } int main() { typedef double (*Measure)(double R); double R = 12.55; Measure Calc[] = { Diameter, Circumference, Area }; double D = Calc[0](R); double C = Calc[1](R); double A = Calc[2](R); cout cout cout cout << << << << "Circle Characteristics"; "\nDiameter: " << D; "\nCircumference: " << C; "\nArea: " << A << endl;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return 0; } This would produce: Circle Characteristics Diameter: 25.1 Circumference: 78.8539 Area: 494.808 Press any key to continue...

Practical Learning: Using an Array of Functions


1. Create a new project using the Console Wizard 2. To save the project, create a new folder called Multiple Choice1 3. Save the unit as Exercise and save the project as MCQ1 4. To experiment with an array of functions, change the Exercise.cpp file as follows: #include <iostream> using namespace std; typedef char (*Question)(); enum TMCQuestion { One, Two, Three, Four, Five }; char Sequence() { char Answer; cout << "Which sequence of numbers does not appear to follow " << "a recognizable order?"; cout << "\n(a) 3 9 27 33"; cout << "\n(b) 3 6 9 12"; cout << "\n(c) 2 4 6 8"; cout << "\n(d) 102 204 408 816"; cout << "\nAnswer: "; cin >> Answer; return Answer; } char Expression() { char Response; cout << "Select the best expression to complete the empty space"; cout << "\nWhen ... drugs to a business address, traffickers often " << "omit a recipient name"; cout << "\n(a) to send"; cout << "\n(b) senders"; cout << "\n(c) sending"; cout << "\n(d) dealing"; cout << "\nAnswer: "; cin >> Response; return Response; } char Sentence() { char Answer; cout << "Even ... there are 76,000 lawyers in that city, it is still " << "a small community"; cout << "\n(a) although"; cout << "\n(b) though"; cout << "\n(c) for"; cout << "\n(d) since"; cout << "\nAnswer: "; cin >> Answer; return Answer; } char WrongWord() { char Wrong; cout << "Select the wrong word that would complete the sentence"; cout << "\nFor this type of business, revenue gains are ..."; cout << "\n(a) limited"; cout << "\n(b) scarce"; cout << "\n(c) limitless"; cout << "\n(d) claiming"; cout << "\nAnswer: "; cin >> Wrong; return Wrong; } char Right() { char Sentence;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "Select the right sentence"; cout << "\n(a) The company is expecting to reducing inventory," << "\n control cost, and efficiency improvement."; cout << "\n(b) The company expects to reduce inventory," << "\n control cost, and improve efficiency."; cout << "\n(c) The company expects to reduce inventory," << "\n control cost, and improving efficiency."; cout << "\n(d) The company is expecting to reducing inventory," << "\n controlling cost, and efficiency improvement."; cout << "\nAnswer: "; cin >> Sentence; return Sentence; } void ValidateAnswer(const int QstNbr, const char Ans); int main() { const int NumberOfQuestions = 5; char ValidAnswer; char Answer[NumberOfQuestions]; Question MCQ[] = { Sequence, Expression, Sentence, WrongWord, Right}; for(int i = 0; i < NumberOfQuestions; i++) { cout << "Question " << i + 1 << endl; Answer[i] = MCQ[i](); ValidateAnswer(i+1, Answer[i]); cout << "\n\nPress any key to continue..."; clrscr(); } return 0; } void ValidateAnswer(const int QstNbr, const char Ans) { switch(QstNbr) { case 1: if(Ans == 'a' || Ans == 'A') cout << "Right Answer"; else { cout << "Wrong Answer - The right answer was 'a'"; cout << "\n(a) Starting at 3, 3*3=9 and 3*9=27"; cout << "\n There is no obvious way to determine 33"; } break; case 2: if(Ans == 'c' || Ans == 'C') cout << "Right answer"; else cout << "Wrong Answer - The right answer was 'c'"; break; case 3: if(Ans == 'b' || Ans == 'B') cout << "Right answer"; else cout << "Wrong Answer - The right answer was 'b'"; break; case 4: if(Ans == 'd' || Ans == 'D') cout << "Right answer"; else cout << "Wrong Answer - The right answer was 'd'"; break; case 5: if(Ans == 'b' || Ans == 'B') cout << "Right answer"; else cout << "Wrong Answer - The right answer was 'b'"; break; default: cout << "Invalid Answer"; } } 5. Test the application 6. Return to your programming environment and save all

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Previous Copyright 1998-2010 FunctionX, Inc. Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Strings
Arrays of Characters

Re-Introduction to Characters
In our second lesson, we had a brief introduction to arrays of characters and strings. So far, we have avoided using them whenever we did not have to. As it happens, strings are the most used items of computers. In fact, anything the user types is a string. It is up to you to convert it to another, appropriate, type of your choice. This is because calculations cannot be performed on strings. On the other hand, strings can be a little complex, which is why we wanted to first know how to use the other types and feel enough comfortable with them. Consider a name such as James. This is made of 5 letters, namely J, a, m, e, and s. Such letters, called characters, can be created and initialized as follows:
char L1 = 'J', L2 = 'a', L3 = 'm', L4 = 'e', L5 = 's';

To display these characters as a group, you can use the following:


cout << "The name is " << L1 << L2 << L3 << L4 << L5;

Here is such a program:


#include <iostream> using namespace std;

int main() { char L1 = 'J', L2 = 'a', L3 = 'm', L4 = 'e', L5 = 's';

cout << "The name is " << L1 << L2 << L3 << L4 << L5;

return 0; }

This would produce:


The name is James

Declaring and Initializing an Array of Characters


When studying arrays, we were listing the numeric members of the array between curly bracket.

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Here is an example:
int Number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

Because a character is initialized by including it in single-quotes, when creating an array of characters, to initialize it, you must also include each letter accordingly. A name such as James can be initialized as follows:
char Name[6] = { 'J', 'a', 'm', 'e', 's' };

As done with other arrays, each member of this array of characters can be accessed using its index. Here is an example:
#include <iostream> using namespace std;

int main() { char Name[6] = { 'J', 'a', 'm', 'e', 's' };

cout << "The name is " << Name[0] << Name[1] << Name[2] << Name[3] << Name[4];

return 0; }

The C/C++ provides another alternative. It allows you to declare and initialize the array as a whole. To do this, include the name in double-quotes. With this technique, the curly brackets that delimit an array are not necessary anymore. Here is an example:
char Name[12] = "James";

With this technique, the item between the double-quotes is called a string. It is also referred to as the value of the string or the value of the variable. When declaring and initializing an array of characters, the compiler does not need to know the number of characters of the string. In fact, you can let the compiler figure it out. Therefore, you can leave the square brackets empty:
char Name[] = "James";

After declaring such an array, the compiler would count the number of characters of the variable, add one more variable to it and allocate enough space for the variable. The character added is called the null-terminated character and it is represented as \0. Therefore, a string such as James would be stored as follows: J a m e s \0

This something you will need to remember regularly.


Color = Black Country = Swaziland

Streaming an Array of Characters


Like any other variable, before using a string, you must first declare it, which is done by type the char keyword, followed by the name of the variable, followed by square brackets. When declaring the variable, if/since you do not know the number of characters needed for the string, you must still provide an estimate number. You can provide a value large enough to

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
accommodate the maximum number of characters that would be necessary for the variable. For a person's name, this could be 20. For the title of a book or a web page, this could be longer. Here are examples:
char Name[20]; char BookTitle[40]; char WebReference[80]; char WeekDay[4];

To request the value of an array of characters, use the cin extractor just like you would proceed with any other variable, without the square bracket. Here is an example:
char WeekDay[12];

cout << "Enter today's name: "; cin >> WeekDay;

To display the value of an array of characters, use the cout extractor as we have used it with all other variables, without the square brackets. Here is an example:
#include <iostream> using namespace std;

int main() { char WeekDay[12]; char EndMe[] = "\n";

cout << "Enter today's name: "; cin >> WeekDay;

cout << "Today is " << WeekDay;

cout << EndMe;

return 0; }

Here is an example of running the program:


Enter today's name: Thursday Today is Thursday

Multidimensional Arrays of Characters


C/C++ treats arrays of characters differently than it does the other arrays. For example, we have learned to declare a two-dimensional array of integers as follows:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
int Number[2][6] = { { 31, 28, 31, 30, 31, 30 }, { 31, 31, 30, 31, 30, 31 } };

This variable is in fact two arrays and each array contains 6 integers. For a string, if you want to declare a two-dimension array of characters, the first dimension specifies the number of string in the variable. The second dimension specifies the number of characters that each string can hold. Here is an example:
char StudentName[4][10] = { "Hermine", "Paul", "Gertrude", "Leon" };

In this case, the StudentName variable is an array of 4 strings and each string can have a maximum of 9 characters (+1 for the null-terminated character). To locate a string on this variable, type the name of the array followed by its index, which is the index of the column. This means that the first string of the StudentName array can be accessed with StudentName[0]. The second would be StudentName[1], etc. This allows you to display each string on the cout extractor:
#include <iostream> using namespace std;

int main() { char StudentName[4][10] = { "Hermine", "Paul", "Gertrude", "Leon" };

cout << "Student Names"; cout << "\nStudent 1: " << StudentName[0]; cout << "\nStudent 2: " << StudentName[1]; cout << "\nStudent 3: " << StudentName[2]; cout << "\nStudent 4: " << StudentName[3];

return 0; }

This would produce:


Student Names Student 1: Hermine Student 2: Paul Student 3: Gertrude Student 4: Leon

When declaring and initializing such an array, the compiler does not need to know the number of strings in the array; it can figure it out on its own. Therefore, you can leave the first pair square brackets empty. If you are only declaring the array but cannot initialize, then you must specify both dimensions. To request the values of the array, once again, locate each member using its index. Here is an example:
Enther the first name of each player Student 1: Walter

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Student 2: Guy Student 3: Celestin Student 4: Maurand Student 5: Phillipe

Student Names Student 1: Walter Student 2: Guy Student 3: Celestin Student 4: Maurand Student 5: Phillipe

There are two alternatives to solve this problem: you can use the getline() function from the basic_string library or you can use the gets() function from the C language.

Pointers and Arrays of Characters

Declaring a Pointer to Characters


Earlier, we declared an array as follows:
char EndMe[] = "";

The name of the variable is a pointer to the beginning of the array. For this reason, the name of the reason is sufficient to locate its value. Since in this case we do not specify the number of characters in the array, we can also just use a pointer to the array as the beginning of the array. The array can therefore be declared as follows:
char *EndMe = "";

Once again, to display the value of such an array, simply call its name on the cout extractor:
#include <iostream> using namespace std;

int main() { char *EndMe = "";

cout << EndMe;

return 0; }

To request the value of an array of characters from the user, you can declare a pointer to char and initialize it with an estimate number of characters using the new operator. Here is an example:
#include <iostream>

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
using namespace std;

int main() { char *StudentName = new char[20];

cout << "Enter Sudent First Name: "; cin >> StudentName;

cout << "\nStudent First Name: " << StudentName;

return 0; }

Here is an example of running the program:


Enter Sudent First Name: Charlotte

Student First Name: Charlotte

Declaring and Initializing an Array of Characters


From our study and use of characters, we have seen that, to declare a character variable, we can use any C++ valid name. To initialize a character variable, type it between single-quotes. Here is an example:
char Answer = y;

To declare an array of characters, type the char keyword followed by the techniques we used to declare the other arrays. The syntax is:
char ArrayName[Dimension];

The char keyword lets the compiler know that you are declaring a variable of character type. The square brackets let the compiler know that you are declaring an array. The name of the array follows the same rules and suggestions we have used for the other variables. Once again, the dimension of the array could be an approximation of the number of characters you anticipate. To initialize an array of characters, you use the curly brackets. Each character must be enclosed in single-quotes. If you know the characters you will be using to initialize the array, you should omit specifying the dimension. Here is an example:
char Color[] = { 'B', 'l', 'a', 'c', 'k' };

Another technique used to initialize an array of characters is to type the group of characters between double-quotes. Since you know the array, let the compiler figure out its dimension. Here is an example:
char Country[] = "Swaziland";

Any of these two techniques would allow you to display the string using the cout operator. The compiler already knows the dimension and the contents of the array:
#include <iostream>

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
using namespace std;

int main() { char Color[] = { 'B', 'l', 'a', 'c', 'k' }; char Country[] = "Swaziland";

cout << "Color = " << Color << endl; cout << "Country = " << Country;

return 0; }

This would produce:


Color = Black Country = Swaziland

Requesting an Array of Characters


Instead of initializing an array, sometimes you will have to wait until the program is running, to assign a value to the array. First, you must declare the array, specifying an approximate dimension. To request the value of an array of characters, use the cin operator, specifying only the name of the array. Here is an example:
#include <iostream> using namespace std;

int main() { char FirstName[20]; char MI; char LastName[20];

cout << "The following pieces of information are need" << "to complete your application\n"; cout << "First Name: "; cin >> FirstName; cout << "Middle Initial: "; cin >> MI; cout << "Last Name: "; cin >> LastName;

cout << "\nMember Information";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\nFull Name: " << FirstName << " " << MI << ". " << LastName;

return 0; }

Here is an example of running the program:


The following pieces of information are need to complete your application

First Name: Michael Middle Initial: J Last Name: Callhoun

Member Information Full Name: Michael J. Callhoun

If you use the normal cin operator above, the compiler expects the user to type a one-word string from the keyboard. If you want the user to type text that includes space, you should use the cin::getline() function. The syntax of the getline() function is:
cin.getline(ArrayName, Dimension, Delimiter=\n);

The array name is the one you used when declaring the array. The dimension is the same value you set when declaring the variable. The delimiter is an optional character that the user would type to specify the end of the string. By default, the compiler expects the user to press Enter to end the string. Logically, the following program illustrates the use of the cin::getline() function to request text strings from the user:
#include <iostream> using namespace std;

int main() { char Author[40]; char Title[40]; char Publisher[50];

cout << "Book Collection\n"; cout << "Author: "; cin.getline(Author, 40); cout << "Title: "; cin.getline(Title, 40); cout << "Publisher: "; cin.getline(Publisher, 50); cout << "\nBook Information";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\nAuthor Name: " << Author << "\nBook Title: " << Title << "\nPublisher: " << Publisher;

return 0; }

Here is an example of running the program:


Book Collection Author: Elliot Mendelson Title: 3000 Solved Problems In Calculus Publisher: McGraw Hill

Book Information Author Name: Elliot Mendelson Book Title: 3000 Solved Problems In Calculus Publisher: McGraw Hill

Arrays of Characters and Pointers


Declaration of an Array of Characters
We have learned to declare an array of characters using the square brackets and to initialize it using the assignment operator. By not specifying the dimension of the array, we are relying on the compiler to find out how many items the array has. Here is an example:
#include <iostream> using namespace std;

int main() { char Country[] = "Republique d'Afrique du Sud";

cout << "Country Name: " << Country << "\n\n";

return 0; }

As you can see for this example, to display the value of the Country variable, although it is an array, all the compiler needs is the name. How come? As it happens, when you create an array of characters, such as the Country variable above, the name of the array is the same as Country[0]. In other words, it represents the beginning of the space memory occupied by the variable. As we saw when studying pointers, this beginning of the space occupied by a variable is referred to as its address. Because the compiler knows this and is able to figure it out, C++ provides another solution. Instead of declaring the array with empty square brackets, since we are in fact referring to the address of the variable, we can declare it a pointer to char.

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Therefore, the above program can be written as follows:
#include <iostream> using namespace std;

int main() { char *Country = "Republique d'Afrique du Sud";

cout << "Country Name: " << Country << "\n\n"; return 0; }

Both programs would produce the same result. There is something important to know about this new version. The asterisk on the name informs the compiler that it should consider the Country variable starting at its address and up. If you do not initialize the variable, the compiler would not complain as long it is now able to locate the variable. Based on this, you can initialize the variable when you are ready and not necessarily when you declare it. Keep in mind that this theory is valid only for an array of characters; for example the following program will not compile:
#include <iostream> using namespace std;

int main() { double *Value;

Value = 12.55;

cout << "Value = " << Value;

return 0; }

On the other hand, the following declaring of an array of characters and its later initialization is perfectly legal:
#include <iostream> using namespace std;

int main() { char *Country;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Country = "Republique d'Afrique du Sud";

cout << "Country Name: " << Country << "\n\n"; return 0; }

Dynamic Arrays of Characters


A dynamic object is one whose memory is requested and used only when needed. Such objects are created using the new operator. In the same way, to dynamically create an array, you use the new operator. To do this, the variable must be declared a pointer to char, as done above. Then assign the new char expression that followed by a pair of square brackets. In the square brackets, specify the desired dimension of the array. An example would be:
char *Country = new char[20];

After declaring such a variable, you can assign it any value you want. Here is an example:
#include <iostream> using namespace std;

int main() { char *Country = new char[20];

Country = "Equatorial Guinea"; cout << "Country Name: " << Country;

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

Passing an Array of Characters


Like other regular arrays, you can pass an array of characters to a function or you can return an array of characters from a function. To pass an array of characters to a function, when declaring and when defining the function, provide the name of the array followed by empty parentheses. When calling the function, provide only the name of the argument you are passing. Here is an example:
#include <iostream> using namespace std;

void ShowCountry(const char S[]) { cout << "Country Name: " << S << "\n\n"; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
int main() { char Country[] = "Republique d'Afrique du Sud";

ShowCountry(Country); return 0; }

Alternatively, as we have learned that you can also declare an array of characters using a pointer to char, when declaring and when defining the array, you can provide the argument as a pointer to char. When calling the function, provide the argument of the function by specifying only the name of the argument:
#include <iostream> using namespace std;

void ShowCountry(const char *S) { cout << "Country Name: " << S << "\n\n"; }

int main() { char *Country = "Republique d'Afrique du Sud";

ShowCountry(Country);

return 0; }

Returning an array of Characters


Just as you can pass an array of characters to a function, you can also return such an array from a function. To do this, the function must be declared and defined as a pointer to char. Here is an example:
char *GetFirstName();

When calling such a function, you are requesting its value and want to assign it to a variable, make sure that the variable is also declared as pointer to char. Here is an example:
#include <iostream> using namespace std;

char *GetFirstName()

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ char *FName = new char[20];

cout << "Enter First Name: "; gets(FName);

return FName; }

int main() { char *FirstName;

FirstName = GetFirstName(); cout << "First Name: " << FirstName << "\n\n"; return 0; }

Multidimensional Arrays of Characters


Double-Dimensional Arrays Declaration
Once again, an array of characters is different from an array of other regular data types. Imagine you want to create various lists of countries. You would declare such an array as follows: char Country[3][8]; Unlike other data types, it is important to know what each dimension represents. This array initiates 3 lists of countries. Each country can have up to 8 letters. In other words, the first dimension represents the number of items that make up the list. It is as if you had declared an array of flowing-point numbers as double Distance[5] which represents a series of 5 distances. The second dimension of an array of characters represents the maximum number of characters that each item can have. To initialize a 2-dimensional array, assign an opening and a closing curly brackets to it. Inside of the curly brackets, provide each item between double-quotes. Here is an example:
#include <iostream> using namespace std;

int main() { char Country[3][20] = { "Afrique du Sud", "Australie", "Zimbabwe" };

return 0; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Make sure that the number of items of your list is equal to or less than the first dimension. If this condition is not met, the compiler would display an error. For example, the following program will not compile because the declaration of the array specifies that the array is made of three items but is initialized with 6:
#include <iostream> using namespace std;

int main() { char Country[3][20] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" };

return 0; }

In the same way, make sure that each item of the array has a number of characters (or letters) that is equal to or less than the second dimension. The following program will not compile because two items of the array (the 1st and the last) have more than 10 letters after you had declared that the maximum number of letters of each item of the arrays would be 10 characters:
#include <iostream> using namespace std;

int main() { char Country[6][10] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" };

return 0; }

To access an item of the 2-dimensional array of characters, provide its name followed by its index. The index here is from the first dimension because the first dimension specifies the number of items of the array. For example, you can access the 3rd item of the above Country array with Country[4]. The compiler does not need the dimension of each item to display it. Here is an example:
#include <iostream> using namespace std;

int main() { char Country[6][15] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" };

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "Countries Names"; cout << "\nCountry 1: " << Country[0]; cout << "\nCountry 2: " << Country[1]; cout << "\nCountry 3: " << Country[2]; cout << "\nCountry 4: " << Country[3]; cout << "\nCountry 5: " << Country[4]; cout << "\nCountry 6: " << Country[5];

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

This would produce:


Countries Names Country 1: Afrique du Sud Country 2: Australia Country 3: Zimbabwe Country 4: Sri Lanka Country 5: Yemen Country 6: El Salvador

In the same way, you can use a for loop to scan the array, accessing each member by its position. Here is an example:
#include <iostream> using namespace std;

int main() { char Country[6][15] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" };

cout << "Countries Names"; for(int i = 0; i < 6; ++i) cout << "\nCountry " << i + 1 << ": " << Country[i];

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

When you declare a two-dimensional array, yo do not have to know how many items the array is made of but you must know the maximum number of characters that each item can be mad of. This property of arrays can be used to leave the first square brackets empty:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#include <iostream> using namespace std;

int main() { char Country[][15] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" };

cout << "Countries Names"; for(int i = 0; i < 6; ++i) cout << "\nCountry " << i + 1 << ": " << Country[i];

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

We saw earlier that, using a pointer to char, you do not have to specify the number of characters that composes an array. For a 2-dimensional array, you can let the compiler figure out how many items the array uses. To do this, when declaring the array, precede the name of the array with an asterisk. This will allow the compiler to locate the address of the first item and take over from there. Based on this, the above array can be declared as follows:
char *Country[15] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" };

We also saw earlier that the name of an represents the address of the variable. In the same way, you do not have to find the item that has the highest number of characters and specify it as the second dimension of the array. You can let the compiler figure out this by letting the square brackets empty. By your initializing the array, the compiler would figure out how much space each item needs. Therefore, the above array can be declared as follows:
#include <iostream> using namespace std;

int main() { char *Country[] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" };

cout << "Countries Names"; for(int i = 0; i < 6; ++i) cout << "\nCountry " << i + 1 << ": " << Country[i];

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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
}

Two-Dimensional Arrays of Characters and Functions


When declaring and when defining a function that takes as argument a 2-dimensional array, the argument is passed with two pairs of square brackets. The first square bracket should be left empty although you are allowed to specify its dimension. This first pair of square brackets lets the compiler know the argument represents a group of strings. The second pair of square brackets must have the maximum characters that each item of the array has. Such a function can be declared and defined as follows:
void ShowCountries(char S[][15]);

When calling such a function, provide only the name of the array. The compiler can figure out the rest by referring to the definition of the function (of course, this is still your responsibility). Here is an example:
#include <iostream> using namespace std;

void ShowCountries(char S[][15]) { cout << "Countries Names";

for(int i = 0; i < 3; ++i) cout << "\nCountry " << i + 1 << ": " << S[i]; }

int main() { char Country[][15] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" };

ShowCountries(Country);

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

If you expect the function to also process the (whole) array, you can pass a second argument that would hold the actual number of items that composes the array passed as argument. Here is an example:
#include <iostream> using namespace std;

void ShowCountries(char S[][15], const int n)

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ cout << "Countries Names";

for(int i = 0; i < n; ++i) cout << "\nCountry " << i + 1 << ": " << S[i]; }

int main() { char Country[][15] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" };

ShowCountries(Country, 6);

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

You can also pass the argument as a pointer to char after declaring the array as such. This, of course, allows the compiler to better manage memory because it can figure out how many items are in the array and how much space each item needs. To pass an array as a pointer to char, when declaring and when defining the function, precede the name of the argument with an asterisk and type an empty pair of square brackets on the right side of the name of the argument. You can call this function the same way we did above:
#include <iostream> using namespace std;

void ShowCountries(char *S[], const int n) { cout << "Countries Names";

for(int i = 0; i < n; ++i) cout << "\nCountry " << i + 1 << ": " << S[i]; }

int main() { char *Country[] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" };

ShowCountries(Country, 6);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\n\n"; return 0; }

Alternatively, when declaring and when defining the function, you can specify that the argument is a pointer to char:
#include <iostream> using namespace std;

void ShowCountries(char **S, const int n) { cout << "Countries Names";

for(int i = 0; i < n; ++i) cout << "\nCountry " << i + 1 << ": " << S[i]; }

int main() { char *Country[] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" };

ShowCountries(Country, 6);

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

Introduction to Strings

Defining a String
A string is an array of characters whose last character is \0. A typical string, such as Pacifique, is graphically represented as follows: P a c i f i q u e \0

The last character \0 is called the null-terminating character. For this reason, a string is said to be null-terminated. The string library ships with a lot of functions used to perform almost any type of operation on almost any kind of string. Used under different circumstances, the string functions also have different syntaxes. The strings that you can use in your program may be defined in various libraries depending on your compiler but most of the time, they are available once you include the string library that

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
is defined in the std namespace. For example, the functions we are about to review are part of the C language. The strings that are part of the (C++) Standard Template Library (STL) are defined in the string class of the std namespace. Based on this, most compilers make all these functions accessible once you include the string library and the std namespace in your program.

String Manipulation Functions


The C++ and its parent the C languages do not have a string data type. In C and C++, strings are created from arrays. Therefore, the C++ language relies on operations performed on the arrays of characters or pointers to char. The functions used for this purpose are numerous and you should know what they are used for. As a reminder, thanks to the features of arrays of characters and the friendship between arrays of characters and strings, there are two main ways you can declare and initialize a string:
char *Thing = Telephone; char Major[] = Computer Sciences;

The Length of a String


In many operations, you will want to know how many characters a string consists of. To find the number of characters of a string, use the strlen() function. Its syntax is:
int strlen(const char* Value);

The strlen() function takes one argument, which is the string you are considering. The function returns the number of characters of the string. Here is an example:
#include <iostream> using namespace std;

int main() { char *School = "Manchester United"; int Length = strlen(School);

cout << "The length of \"" << School << "\" is " << Length << " characters\n\n";

return 0; }

This would produce:


The length of "Manchester United" is 17 characters

The strcat() Function


If you have two strings, to append one to another, use the strcat() function. Its syntax is:
char *strcat(char *Destination, const char *Source);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
The strcat() function takes two arguments. The second argument, called the source string, is the string you want to add to the first string; this first string is referred to as the destination. Although the function takes two arguments. It really ends up changing the destination string by appending the second string at the end of the first string. This could be used to add two strings. Here is an example:
#include <iostream> using namespace std;

int main() { char *Make = "Ford "; char *Model = "Explorer";

cout << "Originally, Make = " << Make;

strcat(Make, Model);

cout << "\n\nAfter concatenating, Make = " << Make << endl; return 0; }

This would produce:


Originally, Make = Ford

After concatenating, Make = Ford Explorer

The strncat() Function


Like the strcat() function, the strncat() function is used to append one string to another. The difference is that, while the strcat() considers all characters of the source string, the strncat() function allows you to specify the number of characters from the source string that you want to append to the destination string. This means that, if the source string has 12 characters, you can decide to append only a set number of its characters. The syntax is:
char* strncat(char* Destination, const char* Source, int Number);

Besides the same arguments as the strcat() function, the Number argument sets the number of characters considered from Source. To perform the concatenation, the compiler would count characters from left to right on the source string. Here is an example:
#include <iostream> using namespace std;

int main() { char *Make = "Ford "; char *Model = "Explorer";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "Originally, Make = " << Make;

strncat(Make, Model, 3);

cout << "\n\nAfter concatenating, Make = " << Make; return 0; }

This would produce:


Originally, Make = Ford

After concatenating, Make = Ford Exp

Copying One String Into Another


The strcpy() function is used to copy one string into another string. In English, it is used to replace one string with another. The syntax of the strcpy() function is:
char* strcpy(char* Destination, const char* Source);

This function takes two arguments. The first argument is the string that you are trying to replace. The second argument is the new string that you want to replace. There are two main scenarios suitable for the strcpy() function: To replace an existing string or to initialize a string. The following would initialize a string:
char CarName[20];

strcpy(CarName, "Toyota Camry");

cout << "Car Name: " << CarName;

If you have two strings and copy one into another, both strings would hold the same value:
#include <iostream> using namespace std;

int main() { char carName1[] = "Ford Escort"; char carName2[] = "Toyota 4-Runner";

cout << "The String Copy Operation"; cout << "\nFirst Car: " << carName1; cout << "\nSecond Car: " << carName2;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
strcpy(carName2, carName1);

cout << "\n\nAfter using strcpy()..."; cout << "\nFirst Car: " << carName1; cout << "\nSecond Car: " << carName2 << endl;

return 0; }

This would produce:


The String Copy Operation First Car: Ford Escort Second Car: Toyota 4-Runner

After using strcpy()... First Car: Ford Escort Second Car: Ford Escort

The strncpy() Function


The strncpy() function works like the strcpy() function. As a difference, the strncpy() function allows you to specify the number of characters that the compiler would copy from the source string. Here is the syntax:
char* strncpy(char* Destination, const char* Source, int Number);

The Number argument specifies the number of characters that will be copied from the Source string. Here is an example:
#include <iostream> using namespace std;

int main() { char CarName1[] = "Ford Escort"; char CarName2[] = "Toyota 4-Runner";

cout << "The String Copy Operation"; cout << "\nFirst Car: " << CarName1; cout << "\nSecond Car: " << CarName2;

strncpy(CarName2, CarName1, 8);

cout << "\n\nAfter using strncpy() for 8 characters"; cout << "\nFirst Car: " << CarName1;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\nSecond Car: " << CarName2 << endl;

return 0; }

This would produce:


The String Copy Operation First Car: Ford Escort Second Car: Toyota 4-Runner

After using strncpy() for 8 characters First Car: Ford Escort Second Car: Ford Esc-Runner

The strdup() Function


The strdup() function is used to make a copy of create a duplicate of that string. Its syntax is:
char* strdup(const char *S);

This function takes as an argument the string you want to duplication and returns the duplicated string.
#include <iostream> using namespace std;

int main() { char *FirstName1 = "Charles"; char *FirstName2 = "Andy"; char *LastName1 = "Stanley"; char *LastName2;

LastName2 = strdup(LastName1);

cout << "Father: " << FirstName1 << ' ' << LastName1 << endl; cout << "Son: " << FirstName2 << ' ' << LastName2;

return 0; }

This would produce:


Father: Charles Stanley Son: Andy Stanley

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Comparing Strings
Various routines are available for strings comparison. The C-String library is equipped with functions that perform the comparisons by characters. Alternatively, some compilers like Borland C++ Buider ships with additional multiple functions to perform these comparisons on null-terminated strings.

The strcmp() Function


The strcmp() function compares two strings and returns an integer as a result of its comparison. Its syntax is:
int strcmp(const char* S1, const char* S2);

This function takes two strings, S1 and S2 and compares them. It returns A negative value if S1 is less than S2 0 if S1 and S2 are equal A positive value if S1 is greater than S2
#include <iostream> using namespace std;

int main() { char *FirstName1 = "Andy"; char *FirstName2 = "Charles"; char *LastName1 = "Stanley"; char *LastName2 = "Stanley";

int Value1 = strcmp(FirstName1, FirstName2); int Value2 = strcmp(FirstName2, FirstName1); int Value3 = strcmp(LastName1, LastName2);

cout << "The result of comparing " << FirstName1 << " and " << FirstName2 << " is\t" << Value1 << endl; cout << "The result of comparing " << FirstName2 << " and " << FirstName1 << " is\t" << Value2 << endl; cout << "The result of comparing " << LastName1 << " and " << LastName2 << " is\t" << Value3;

return 0; }

This would produce:


The result of comparing Andy and Charles is -2 The result of comparing Charles and Andy is 2

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
The result of comparing Stanley and Stanley is 0

The strncmp() Function


The strncmp() function compares two strings using a specified number of characters and returns an integer as a result of its findings. Its syntax is:
int strncmp(const char* S1, const char* S2, int Number);

This function takes three arguments. The first two arguments are the strings that need to be compared. The 3rd argument specifies the number of characters considered for the comparison. It returns A negative value if S1 is less than S2 0 if S1 and S2 are equal A positive value if S1 is greater than S2

The stricmp() Function


The stricmp() function compares two strings without regard to their case. In other words, this function does not take into consideration if there is a mix of uppercase and lowercase characters in the strings. The syntax of the function is:
int stricmp(const char* S1, const char* S2);

This function takes two strings, S1 and S2 and compares them. It returns A negative value if S1 is less than S2 0 if S1 and S2 are equal A positive value if S1 is greater than S2

The strnicmp() Function


The strnicmp() function compares two strings without regard to their case but considers only a specified number of characters. The syntax of the function is:
int strnicmp(const char* S1, const char* S2, int n);

This function takes two strings, S1 and S2 and compares them. It returns A negative value if S1 is less than S2 0 if S1 and S2 are equal A positive value if S1 is greater than S2

Working With Individual Characters


The strchr() Function
The strchr() function looks for the first occurrence of a certain character in a string. Its syntax is:
char* strchr(const char* S, char c);

This function takes two arguments. The second argument specifies what character to look for in the first argument which is a string. If the character c appears in the string S, the function would return a new string whose value starts at the first occurrence of c in S. If the character

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
c does not appear in the string S, then the function would return NULL.

The strrchr() Function


The strrchr() function examines a string starting at the end (right side) of the string and looks for the first occurrence of a certain character. Its syntax is:
char* strrchr(const char* S, char c);

The first argument is the string that needs to be examined. The function will scan the string S from right to left. Once it finds the first appearance of the character c in the string, it would return a new string whose value starts at that first occurrence. If the character c does not appear in the string S, then the function would return NULL.

Working With Sub-Strings


The strstr() Function
The strstr() function looks for the first occurrence of a sub-string in another string and returns a new string as the remaining string. Its syntax is:
char* strstr(const char* Main, const char *Sub);

The first argument of the function is the main string that would be examined. The function would look for the second argument, the Sub string appearance in the main string. If the Sub string is part of the Main string, then the function would return a string whose value starts at the first appearance of Sub and make it a new string. If Sub is not part of the Main string, the function would return a NULL value.

Working With Character Cases


The strlwr() Function
The strlwr() function is used to convert a string to lowercase. Its syntax is:
char *strlwr(const char *S);

This function takes, as argument, the string that needs to be converted. During conversion, if a Latin character were in uppercase, it would be converted to lowercase. Otherwise, it would stay as if. This means any symbol that is not a readable character would not be converted.
#include <iostream> using namespace std;

int main() { char CustomerAddress[] = "4812 LOCKWOOD Drive #F04";

cout << "Customer Address: " << CustomerAddress << endl;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
char *ShippingAddress = strlwr(CustomerAddress);

cout << "Shipping Address: " << ShippingAddress << endl;

return 0; }

This would produce:


Customer Address: 4812 LOCKWOOD Drive #F04 Shipping Address: 4812 lockwood drive #f04

The strupr() Function


The strupr() function is used to convert a string to uppercase. Its syntax is:
char *strupr(const char *S);

Each lowercase character in the functions argument, S, would be converted to uppercase. Any character or symbol that is not in lowercase would not be changed.
#include <iostream> using namespace std;

int main() { char Drink[] = "100% Apple Juice"; char *SayItLoud;

cout << "What is that drink? " << Drink << endl;

SayItLoud = strupr(Drink); cout << "Say it loud: " << SayItLoud << endl;

return 0; }

This would produce:


What is that drink? 100% Apple Juice Say it loud: 100% APPLE JUICE

Formatting Strings

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

The sprintf() Function


The sprintf() function is used to format data and specify how it should display. Its syntax is:
int sprintf(char* Buffer, const char* S, Arguments);

This function takes at least two arguments and could take more. The first argument is a nullterminated string that could display one or a few words and the formula to use when displaying the second or more argument. To display a value as part of the Buffer, type a double-quote followed by the string if any, followed by the % sign, follow by one of the following characters:

Character s c

Used to Display A string A character

Character f d

Used to Display Floating-point value An integer

Previous

Copyright 2000-2005 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Data Input/Output
Data Display
Introduction
The values and expressions used in C++ are displayed using the cout extractor. To make the displaying of data more realistic, the cout is configured to handle or format data to any desired result. While the cout (as a class) is defined in the iostream file, some other files provide other extensive techniques for displaying data to the console. The C language also is equipped with other formatting functions used for the same purpose. The ability to create a program made of mixed C and C++ language enhances these formatting possibilities.

General Display Techniques With cout


The ostream class (although we have not learned about classes yet, we can explore them without knowing what a class is) has allowed us so far to display items on the console screen. It is from the ios library and commands all techniques of data output to C++ console applications. The cout we have used so far is a child of the ostream library. Using it, we have found out that we can display almost any type of value. For example, it can be used to display:

A word or sentence, called a string: cout << "Major = South African History"; A character: cout << 'G'; A short integer: cout << -10540; An integer: cout << 242; A long integer: cout << 46300540; A floating number: cout << 126.50; Or a double-precision number: cout << 440005.55; Instead of displaying a value just using the cout extractor, you can first declare and initialize a variable before displaying its value. Like the ostream, the cout is also referred to as an object. Besides the cout and the extraction operator << used to display a character, the cout can be used to display a (one) character. To do this, type cout followed by a period and followed by the put() member function. The syntaxes of the put() function are: ostream& put(char); ostream& put(unsigned char); ostream& put(signed char); The character must be included between parentheses and single-quotes. Here is an example: //-------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop //-------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
-------#pragma argsused int main(int argc, char* argv[]) { cout.put('P'); cout << "\n\nPress any key to continue..."; getch(); return 0; } //-------------------------------------------------------------------------If the character is initialized from a variable, type the name of the variable between parentheses:

//-------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop //-------------------------------------------------------------------------#pragma argsused int main(int argc, char* argv[]) { char Category = 'T'; cout.put(Category); cout << "\n\nPress any key to continue..."; getch(); return 0; } //-------------------------------------------------------------------------The character can also come from a variable requested from the user.

The cout.write() Function


If you want to display a whole string, use the write() function. This function requires two arguments. First, you must specify the string that is used as the source. Second, the compiler needs to know how many characters from the source will be displayed (or considered). Here are two examples: //-------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop //-------------------------------------------------------------------------#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { char Peripheral[] = "Digital Camera"; // First example of using the write() member function of the cout class cout.write("The 5th Floor", 13); cout << endl; // Second example of using the write() function cout.write(Peripheral, 8); cout << "\n\nPress any key to continue..."; getch(); return 0; } //-------------------------------------------------------------------------Although the second argument is used to display a fixed number of characters, if you want to display the whole string, you must make sure the value of the second argument is greater than or equal to the length of the source string. Instead of visually counting the number of

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
characters, which could lead to a mistake, you can use the sizeof operator to get the length of the string: //-------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { char Peripheral[] = "Digital Camera"; int Count = sizeof(Peripheral) / sizeof(char);

cout.write(Peripheral, Count);

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

Data Display Functions: puts()


The C++ (Builder) compiler ships with other files that provide many other functions that can be used to control how data displays on the screen. One of these files is the stdio.h header. The puts() function is used to display a string on the console. Its syntaxes are: int puts(const char *Str);
The Str argument must be a regular string enclosed in double-quotes. Here is an example:

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

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { char Answer;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
puts("Do you consider yourself a hot-tempered individual? "); cin >> Answer;

cout << "\nYour answer was: " << Answer;

cout << "\n\nPress any key to continue..."; getch(); return 0; } //-------------------------------------------------------------------------The puts() function lacks the formatting possibilities of cout. It is destined to only display a single string. To display more complex strings, you can combine it with other operators or functions. Here is an example: //-------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { char Answer;

puts("Do you consider yourself a hot-tempered individual? "); cin >> Answer;

puts("\nYour answer was: "); cout.put(Answer);

cout << "\n\nPress any key to continue..."; getch(); return 0; } //-------------------------------------------------------------------------The string to display on a puts() function can also originate from a declared and initialized variable. In this case, you would provide the name of the variable as the argument to the function. Here is an example: //-------------------------------------------------------------------------#include <iostream> #include <conio>

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
using namespace std; #pragma hdrstop

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { char Question[] = "Do you consider yourself a hot-tempered individual? "; char Answer;

puts(Question); cin >> Answer;

puts("\nYour answer was: "); cout.put(Answer);

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

The cputs() Function


The puts() function positions the cursor of the subsequent line. If you find this annoying, you can use the cputs() function. The cputs() function is used to display a string on the console. Its syntax is: int cputs(const char *Str); To display a string using the cputs() function, pass a string as the argument. The cputs() function requires the conio header file. Here are two examples: //-------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { char Answer;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

cputs("Do you consider yourself a hot-tempered individual? "); cin >> Answer;

cputs("\nYour answer was: "); cout.put(Answer);

cout << "\n\nPress any key to continue..."; getch(); return 0; } //-------------------------------------------------------------------------If the string is from a variable, provide the name of the variable as argument.

The printf() Function


The printf() function is mostly used in the C language programs. By default, it is used to display a string on the console. Its simpler syntax is: int printf(const string); To display a string using the printf() function, simply enclose it between double-quotes, as the functions argument. Here is an example: //-------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { printf("Welcome to College Park Auto-Parts");

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

The cprintf() Function


While the printf() is a function of the stdio.h file, the conio.h library provides an alternative to display a string on the console. The function used is cprintf() and its basic syntax is: int cprintf(const string); This function behaves the same way as the stdio.hs printf() function.

Controlling and Formatting Data Output


Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

The Width of Data Display


The width() function is used to set the amount of space needed to display an item on the console. Its syntax is: int width(); int width(int Count); The first version of this function displays the intended value as is. The second version takes one integer as argument, Count. In order to display the intended value that could be an array of characters, an integer or a floating number, the compiler would count the number of characters (for a char or a string) or the number of digits (for an integer or a float, including the period for decimals). If the value of the argument you supplied, Count, is less than or equal to the number of characters or digits, the compiler would ignore your argument, Count, and display the intended value. If the value argument is greater than the number of characters or digits, the compiler would display the intended value using the total value of the argument, Count, but leaving empty spaces on the left of the intended value. The value to display comes after calling the width() function. If you are displaying only one value, the scenario above would apply straight forward. Here is an example: //-------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { int Value = 782;

cout.width(6); cout << Value;

cout << "\n\nPress any key to continue..."; getch(); return 0; } //-------------------------------------------------------------------------To display various values, you can call the width() function for each and they can use different width values as in the following example:

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

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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { double Value1 = 6.5, Value2 = 25.56, Value3 = 28478.12;

cout.width(8); cout << Value1 << endl; cout.width(14); cout << Value2 << endl; cout.width(10); cout << Value3 << endl;

cout << "\nPress any key to continue..."; getch(); return 0; } //-------------------------------------------------------------------------An alternative to using the width() function is to call the setw() function: int setw(int w); This function takes an integer argument that specifies the amount of space used to display the intended value. Like the width() function, the setw() function can be used to format one value at a time. Here is an example of using it:

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

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { double Value1 = 6.5, Value2 = 25.56, Value3 = 28478.12;

cout.width(16); cout << Value1 << endl; cout << setw(8) << Value2 << endl; cout << setw(12) << Value3 << endl;

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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//--------------------------------------------------------------------------

Filling the Empty Space


As we have seen already, the compiler leaves empty spaces on the left side of the displaying value if the width is greater than the needed space. If you do not want that space to be empty, you can fill it with any character you want. To do that, call the fill() function: char fill(); char fill(char c); The second fill() function takes one argument as the character that would be used in place of the empty spaces. The argument is a character that can be included between single-quotes. If no fill() function was called previously, the second version displays the intended value as is. If there was a previous call to the fill(char c) version that takes a character argument, the first version, fill(), immediately following would still keep the argument of the previous call to fill(), then empty it. In other words, if there is another call to the fill() version without argument, no character would be displayed, until a new call to the fill(char c) function. Here is an example:

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

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { double Value1 = 6.5, Value2 = 25.56, Value3 = 28478.12, Value4 = 10.05;

cout.width(12); cout << Value1 << endl; cout.width(12); cout.fill('#'); cout << Value2 << endl; cout.width(12); cout.fill(); cout << Value3 << endl; cout.fill(); cout << Value4 << endl;

cout << "\nPress any key to continue..."; getch(); return 0; } //-------------------------------------------------------------------------Like the fill() function, the iomanip library provides the setfill() function to fill out empty spaces on a line formatted with the setw() function. The syntax of the setfill() function is:

int setfill(char c);


This function takes one character as argument. This character would be used to fill out the empty spaces on the left of a value displayed on a subsequent cout. Here is an example:

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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
-------#include <iostream> #include <iomanip> #include <conio> using namespace std; #pragma hdrstop

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { double Value1 = 6.5, Value2 = 28478.12, Value3 = 35.25; string WebSite = ".functionx.com";

cout << setw(16) << setfill('%'); cout << Value1 << endl; cout << setw(8) << setfill('@') << Value2 << endl; cout << setw(12) << Value3 << endl; cout << setw(17) << setfill('w') << WebSite << endl;

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

The dec, hex, and oct Operators


The most usual way to show an integer number on the console is to display it as is. To display a variable that has been declared and initialized as int Value = 152; you would write: cout << Value; The compiler would take care of displaying it. If you have an integer in decimal format and would like to display its equivalent hexadecimal representation, use the hex operator as follows:

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

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[])

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ int Value = 242;

cout << "Value = " << Value << endl; cout << "Value = " << hex << Value << endl;

cout << "\nPress any key to continue..."; getch(); return 0; } //-------------------------------------------------------------------------If you have a hexadecimal integer and would like to display it in a decimal format, simply use the cout operator followed by the value. Here is an example:

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

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { cout << "Number = " << 0xFE28D;

cout << "\nPress any key to continue..."; getch(); return 0; } //-------------------------------------------------------------------------Although all integers are displayed in decimal format by default, you can explicitly ask the compiler to reinforce that notation. You can also display the same value in either format as follows:

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

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[])

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ int Variable = 28045;

cout << "Declared Variable: " << Variable << endl; cout << "In decimal: " << dec << Variable << endl; cout << "In hexadecimal: " << hex << Variable << endl;

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

Declared Variable: 28045 In decimal: 28045 In hexadecimal: 6d8d

Press any key to continue...


Although the hex and dec words are used as operators, they are indeed functions that each takes one argument. Such an argument is passed by reference, which means the argument retains the new value after being operated on. For example, if you pass a decimal integer to the hex function, the argument will be maintained as hexadecimal. That is what happens with the following example:

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

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { int Variable = 28045;

cout << "Declared Variable: " << Variable << endl; cout << "In decimal: " << dec << Variable << endl; cout << "In hexadecimal: " << hex << Variable << endl; cout << "Declared Variable: " << Variable << endl;

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

Declared Variable: 28045

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
In decimal: 28045 In hexadecimal: 6d8d Declared Variable: 6d8d

Press any key to continue...

The uppercase Attribute


As you have found out, the hex attribute is used to display the hexadecimal equivalent of a decimal number, but such a number displays in lowercase. To display the hexadecimal letters to uppercase, include the uppercase attribute. Here is an example:

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

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { int SayIt = 12;

cout << hex << uppercase << SayIt << endl;

cout << "\nPress any key to continue..."; getch(); return 0; } //-------------------------------------------------------------------------The uppercase attribute can precede or succeed the hex attribute, as illustrated by the following example:

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

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { long Value = 3874238;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << uppercase << hex << Value << endl;

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

The setiosflags() Function


The width() member function and the setw() functions are typically used to right-align the value(s) displayed that otherwise would be left aligned. If you want to explicitly left align a value, use the setioflags() function. This function takes only one argument as the type of flags used to display data. In order to use the setiosflags() function, you must qualify its flags using the library in which the flag is defined. The ios::left flag is used to left-align a value. Here is a simple example that displays an integer:

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

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { int Series = 2014;

cout << setiosflags(ios::left) << Series;

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

The resetiosflags() Function


After calling the setiosflags() function, any value displayed would follow the rule of that function. To remove the formatting set by the setiosflags(), use the resetiosflags() function, usually with the same argument:

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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { int Series = 2014; double Price = 12.95;

cout << setiosflags(ios::left) << Series << endl; cout << resetiosflags(ios::left) << setw(8) << Price;

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

Formatting Floating-Point Numbers


In most programs that use precise numbers, you need to be able to format your values to display appropriately. This is made possible with the use of the setprecision() function:

int setprecision(int p);


This function takes one argument as the number of decimal places displayed after the period of the floating number. In order to effectively use the setprecision() funciton, first call the setiosflags() function with the appropriate flag. The ios::fixed flag allows you to specify the exact number of decimal values used in the setprecision() function. Here is an example:

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

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { double Price = 0.5;

cout << setiosflags(ios::fixed) << setprecision(2) << Price << endl;

cout << "\n\nPress any key to continue..."; getch();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return 0; } //-------------------------------------------------------------------------Since the setiosflags() and the setprecision() functions apply their formatting to all values set after they have been called, you can use them once and format your other values. That is, until you call these functions again. This is used in the following example:

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

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { int Qty1 = 2, Qty2 = 5, Qty3 = 4, Qty4 = 1; double Price1 = 0.5, Price2 = 1.25, Price3 = 2.95, Price4 = 1.65; double Total1 = Qty1 * Price2, Total2 = Qty4 * Price3, Total3 = Qty2 * Price1, Total4 = Qty3 * Price4;

cout << setiosflags(ios::fixed) << setprecision(2); cout << "Total 1 = " << Total1 << endl; cout << "Total 2 = " << Total2 << endl; cout << "Total 3 = " << Total3 << endl; cout << "Total 4 = " << Total4 << endl;

cout << "\nPress any key to continue..."; getch(); return 0; } //-------------------------------------------------------------------------You can also display floating numbers using a scientific format. To do that, set the flag of the setiosflags() function to ios::scientific. Here is an example:

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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#pragma hdrstop

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { double Pop = 25.44059, Distance = 212.625, MaxExp = 709.78222656;

cout << setiosflags(ios::scientific) << setprecision(2); cout << "PI = " << Pop << endl; cout << "Distance = " << Distance << endl; cout << "Exponent = " << MaxExp << endl;

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

PI = 2.54e+01 Distance = 2.13e+02 Exponent = 7.10e+02

Press any key to continue...

C How to Display Data


The C language is the parent of C++. As such, C++ inherits what is available from its parent C. This flexibility also allows you to mix the way things are done in C and the features that are available in C++. Although C is C++ parent, you do not need to know (anything) about C in order to program in C++ (in fact, you should not know anything about C, at all). Nevertheless, we will review these features transparently and we will be concerned only with the reason we are here: how to program in C++. To format the display of data in C++, the cout operator (once again, it is a class) is complete. In some circumstances, and this will become common when writing applications using some of Borland classes (such as AnsiString), you will need to know how other objects format data. The most common function used to display data in C, and some legacy C++ code, is the printf() function. As flexible as it is, it does not use the type of syntax we are already getting used to in C++. From a C++ stand point, to display data using the functions, everything depends on how you want data to appear. Data types are divided in categories: characters, integers, floating-point numbers, and strings. To display a particular type, you type the percent operator %, followed by the category of data. An example would be %d. To display a character, use the %c format to represent a character variable. Here is an example:

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

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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { char Gender = 'M';

printf("Member Gender: %c", Gender);

cout << "\n\nPress any key to continue..."; getch(); return 0; } //-------------------------------------------------------------------------To display an integer, use the %operator with one of the following tags:

Tag d i o u x X
Here is an example:

Integer Type to Display signed decimal integer signed decimal integer unsigned octal integer unsigned decimal integer unsigned hexadecimal int (with a, b, c, d, e, f) unsigned hexadecimal int (with A, B, C, D, E, F)

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

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { int Number = 120;

printf("Number: %d", Number);

cout << "\n\nPress any key to continue..."; getch(); return 0; } //-------------------------------------------------------------------------To display a floating-point number, use the % operator with one of the following formats:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Tag f e To display signed value of the form [-]dddd.dddd signed value of the form [-]d.dddd or e[+/]ddd signed value in either e or f form, based on given value and precision. Trailing zeros and the decimal point are printed if necessary. Same as e; with E for exponent Same as g; with E for exponent if e format used

g E G
Here is an example:

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

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { double Distance = 272.44;

printf("Distance: %f", Distance);

cout << "\n\nPress any key to continue..."; getch(); return 0; } //-------------------------------------------------------------------------To set the number of decimal places after the period, type the % operator, followed by a period, followed by an integer for the number of decimal places desired, followed by the desired tag. Here is an example:

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

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { double Floater = 3255.01265;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

printf("Floater: %.3f", Floater);

cout << "\n\nPress any key to continue..."; getch(); return 0; } //-------------------------------------------------------------------------To display a string, use the %s format. Here is an example:

//-------------------------------------------------------------------------#include <iostream> #pragma hdrstop

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { char FIFA[] = "Federation Internationale de Football Association";

printf("World Cup Supervisor: %s", FIFA);

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

Data Input
Using cin
Data input in C++ is performed using the cin operator (cin also is a class). The cin is configured with so much flexibility (in C++, we consider that it is overloaded; in reality, it is the >> operator that is overloaded) that it can retrieve any type of declared regular variable. This includes integers, characters, floating-point numbers, or arrays of characters. Here are examples of variables that the cin can handle:

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

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

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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
-------int main(int argc, char* argv[]) { cout << "Enter a natural number: "; int Natural; // Retrieve an integer cin >> Natural;

cout << "Type a decimal number: "; float Floater; // Requesting a floating pointing number cin >> Floater;

cout << "Type another decimal number: "; double Precision; // Retrieving a double-precision number cin >> Precision;

cout << "Are you ready for C++ (y=Yes/n=No)? "; char Answer; // Requesting a character cin >> Answer;

cout << "I mean, are you really ready (Type Yes or No)? "; char Explicit[10]; // Retrieving a word cin >> Explicit;

cout << "\nHere is what we got from you"; cout << "\nNatural Number: " << Natural; cout << "\nFloating Number: " << Floater; cout << "\nDouble Precision: " << Precision;

if( Answer == 'y' || Answer == 'Y' ) cout << "\nYou are ready for C++"; else cout << "\nYou are still not committed to C++";

cout << "\nYour readiness for C++: " << Explicit;

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

The gets() Function


Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
The gets() function, as its name implies, is used to retrieve a string from the user. This function can receive a string of almost any length, depending on how you declare the string. To use the gets() function to request a string, include the stdio.h header file to your source. After declaring the string variable, provide it as argument to the gets() function. Here is an example:

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

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { char Answer[80];

puts("Are you ready to rumbleeeeee? "); gets(Answer);

cout << "\nThe audience response: " << Answer;

cout << "\n\nPress any key to continue..."; getch(); return 0; } //-------------------------------------------------------------------------Here is an example of running the program:

Are you ready to rumbleeeeee? yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy

The audience response: yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy

Press any key to continue...

C How to Input Data


To request data from the user, or to retrieve it somehow, you can use the scanf() function that is part of the stdio.h file. To use this function, you must provide two pieces of information. First the function needs to know the type of variable the function is expecting. Each data type is represented by a letter as follows:

Character c d e f g h i o s

Used for A single character An integer A floating-point number A floating-point number A floating-point number A short integer A decimal, a hexadecimal, or an octal integer An octal integer A string followed by a white space character

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
u x An unsigned decimal integer A hexadecimal integer

When calling the scanf() function to retrieve a specific value, the appropriate character must be preceded by an ampersand % and both must be included in double-quotes. For example, to request an integer, you would write %d. The second piece of information the function needs is the name of the declared variable. Because you are planning to change the value of the variable, it must be passed by reference. To use the scanf() function, you can include it in a C program. Here is an example:

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

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

#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { float Number;

printf("Type a number: "); scanf("%f", &Number); printf("\nYou typed: %f\n", Number);

cout << "\n\nPress any key to continue..."; getch(); return 0; } //-------------------------------------------------------------------------Here is an example of running the program:

Type a number: 145.50

You typed: 145.500000

Press any key to continue...


You can also mix C functions, such as printf() or scanf() in your C++ program as you see fit. For example, you can retrieve values using either cin or scanf() to retrieve any value. In the same way, you can use scanf(), cin, or gets() when requesting a string. Here is an example:

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

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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#pragma argsused //-------------------------------------------------------------------------int main(int argc, char* argv[]) { char FullName[32]; char Gender; int Books;

cout << "Type your full name: "; gets(FullName); cout << "Type your gender (m=Male/f=Female): "; cin >> Gender; cout << "How many books do you own? "; scanf("%d", &Books);

cout << "\nWell, " << FullName << ", with " << Books << " books, it looks like you read a lot! ";

if( Gender == 'm' || Gender == 'M' ) puts("You are the man"); else puts("You go, girl");

cout << "\n\nPress any key to continue..."; getch(); return 0; } //-------------------------------------------------------------------------Here is an example of running the program:

Type your full name: Jacob Desvarieux Type your gender (m=Male/f=Female): m How many books do you own? 84

Well, Jacob Desvarieux, with 84 books, it looks like you read a lot! You are the man

Press any key to continue...

Ending a Program
Exiting a Program
Many of the applications we have written so far stopped when the compiler found the return 0; line at the end of the main() function. In some circumstances it will be necessary to stop a program from a particular function if a bad or unexpected situation occurs. This is handled by the exit() function. Its syntax is:

void exit(int Status);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
When called from anywhere, the exit() function closes all other functions and stops the program. The argument you pass as an integer determines how successful the termination occurred. If the Status is passed as 0, the program terminated successfully. Any other value of Status indicates that there was an error during the termination. Here is an example:

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

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

#pragma argsused //-------------------------------------------------------------------------char __fastcall GetAnswer() { char Answer;

cout << "Do you consider yourself a hot-tempered individual(y=Yes/n=No)? "; cin >> Answer;

Answer = tolower(Answer);

if( Answer != 'y' && Answer != 'n' ) exit(0); else return Answer;

return 'n'; } //-------------------------------------------------------------------------int main(int argc, char* argv[]) { char Ans;

Ans = GetAnswer();

if( Ans == 'y' || Ans == 'Y' ) { cout << "\nThis job involves a high level of self-control."; cout << "\nWe will get back to you."; } else cout << "\nYou are hired!";

cout << "\n\nPress any key to continue...";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
getch(); return 0; } //-------------------------------------------------------------------------Alternatively, you can use the _exit() function to stop the program. Its syntax is:

void _exit(int Status);


As opposed to the exit() function that closes all functions upon exiting, the _exit() function stops the program without closing the other functions. The value of the Status argument determines how the program terminates. If the argument is passed with 0, the function would terminate successfully. Any other value indicates an error. Here is an example:

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

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

#pragma argsused //-------------------------------------------------------------------------int __fastcall NumberRequest() { int Number;

cout << "Type a number between 1 and 3 (included): "; cin >> Number;

if( Number >= 1 && Number <= 3 ) return Number; else _exit(0);

return 0; } //-------------------------------------------------------------------------int main(int argc, char* argv[]) { int Nbr;

Nbr = NumberRequest(); cout << "Your number was: " << Nbr;

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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Notice that the sentence in the main() function executes only if the other function did not exit because of a wrong return value.

Aborting a Program
Sometimes a program terminates with a message box sent by the operating system. An example would be when a user is asked to provide a floating-point number but types a string and the program is supposed to multiply the provided value by another number. The program would stop or hang and display a message of abnormal termination. You can also create your own abnormal termination using the abort() function. Its syntax is:

void abort(void);
When called, the abort() function terminates the program and sends an error message to the operating system. The OS uses different codes to identify these types of errors. Upon exiting, the abort() function terminates with an error code of 3. When the operating system receives it, it displays a message box. You can click one of the buttons. If you click Ignore, the operating system can let you know that there was an abnormal termination. Here is an example:

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

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

#pragma argsused void __fastcall ProcessAnswer() { char Sitting;

cout << "Are you sitting down now(y/n)? "; cin >> Sitting;

Sitting = toupper(Sitting);

if( Sitting == 'Y' ) cout << "\nWonderful!!!"; else if( Sitting == 'N' ) cout << "\nCould you please sit down for the next exercise?"; else abort(); } //-------------------------------------------------------------------------int main(int argc, char* argv[]) { cout << "For the next exercise, you need to be sitting down\n"; ProcessAnswer();

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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//--------------------------------------------------------------------------

Terminating a Program
If something bad happens in your program, the program is prepared to stop it. We will learn about some of these unusual but possible situations when studying exception handling. Nevertheless, if you suspect such a thing and would like to stop the program, you can use one of the exit(), _exit(), or abort() functions we have just seen. Alternatively, you can stop a program using the terminate function. Its syntax is:

void terminate();
You can call the terminate() function the same way we did with the exit() or abort() functions.

Accessory Functions
Borland C++ Builder ships with various types of functions to help you customize and improve your application and its behavior. Some of the functions are part of the C/C++ language. Some others were created by Borland. And some other functions are built in the operating system.

Clearing the Screen With system()


When an application is running (that is, a console application), for example while a user is performing data entry, the program processes one statement at a time in a top-down approach. When the user finishes, you will usually display the result on the screen. If the program is long, at one time it would fill out the screen and this could make the displayed result confusing with the data processing. There are two basic ways you can clear the screen in Borland C++ Builder console application. The simplest technique consists of calling the system() function with the string argument "cls". The syntax of the system() function is:

int system(const char *Argument);


Here is an example:

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

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

#pragma argsused int main(int argc, char* argv[]) { char FirstName[12], LastName[12];

cout << "Enter First Name: "; cin >> FirstName; cout << "Enter Last Name: "; cin >> LastName;

system("cls");

cout << "Full Name: " << FirstName << " " << LastName;

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

Borland's Function of Clearing the Screen


Another technique used to clear the screen consists of using a special function that a Borland created: the clrscr() function. The clrscr() function is part of the conio library. The clrscr() function is not part of the C++ Standard. The syntax of this function is as follows:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
void clrscr(void);
The clrscr() function does not take an argument and does not return a value. It is simply used to empty the screen. Here is an example of using it:

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

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

#pragma argsused int main(int argc, char* argv[]) { char FirstName[12], LastName[12];

cout << "Enter First Name: "; cin >> FirstName; cout << "Enter Last Name: "; cin >> LastName;

clrscr();

cout << "Full Name: " << FirstName << " " << LastName;

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

Previous

Copyright 2005 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Introduction to Exception Handling


Foundations of Exceptions
Introduction
During the execution of a program, the computer will face two types of situations: those it is prepared to deal with and those it doesnt like. Imagine you write a program that asks the user to supply two numbers to perform a calculation. Here is such a program: #include <iostream> using namespace std; int main() { double a, b, c; // Request two numbers from the user cout << "Please provide two numbers\n"; cout << "First Number: "; cin >> a; cout << "Second Number: "; cin >> b; // Multiply the numbers and display the result c = a * b; cout << "\n" << a << " * " << b << " = " << c << "\n\n"; return 0; } This is a classic easy program. When it comes up, the user is asked to simply type two numbers; the program would use them to perform a multiplication and display the result. Imagine that a user, thanks to his infinite creativity or because of just a mistake, decides to type the name of a country or somebodys telephone number as one of the requested values. Since a program such as this one is not prepared to multiply two strings or one number to a string (actually, using operator overloading, you can tell the compiler how to perform almost any type of operation on the values of your program), it would not know what to do. The only alternative the compiler would have is to send the problem to the operating system, hoping that the OS would know what to do. What actually happens is that, whenever the compiler is handed a task, it would try to perform the assignment. If it cant perform the assignment, for any reason it is not prepared for, it would throw an error. As a programmer, if you can anticipate the type of error that could occur in your program, you can catch the error yourself and deal with it by telling the compiler what to do when this type of error occurs.

Exceptional Behaviors
An exception is a situation that would be unusual for the program that is being processed. As a programmer, you should anticipate any abnormal behavior that could be caused by the user entering wrong information that could otherwise lead to unpredictable results. An error result or an unpredictable behavior on your program not caused by the operating system but that occurs in your program is called an exception. The ability to deal with a programs eventual abnormal behavior is called exception handling. C++ provides three keywords to handle an exception. 1. Trying the normal flow: To deal with the expected behavior of a program, use the try keyword as in the following syntax: try {Behavior} The try keyword is required. It lets the compiler know that you are anticipating an abnormal behavior and will try to deal with it. The actual behavior that needs to be evaluated is included between an opening curly bracket { and a closing curly bracket }. Inside of the brackets, implement the normal flow that the program should follow, at least for this section of the code.

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
2. Catching Errors: During the flow of the program as part of the try section, if an abnormal behavior occurs, instead of letting the program crash or instead of letting the compiler send the error to the operating system, you can transfer the flow of the program to another section that can deal with it. The syntax used by this section is: catch(Argument) {WhatToDo}
This section always follows the try section and there must not be any code between the trys closing bracket and the catch section. The catch keyword is required and follows the try section. The catch behaves a little like a function. It uses an argument that is passed by the previous try section. The argument can be a regular variable or a class. If there is no argument to pass, the catch must at least take a three-period argument as in catch(). The behavior of the catch clause starts with an opening curly bracket { and ends with a closing curly bracket }. The inside of the brackets is called the body of the catch clause. Therefore, use the body of the catch to deal with the error that was caused. Combined with the try block, the syntax of an exception would be:

try { // Try the program flow } catch(Argument) { // Catch the exception } 3. Throwing an error: There are two main ways an abnormal program behavior is transferred from the
try block to the catch clause. This transfer is actually carried by the throw keyword. Unlike the try and catch blocks, the throw keyword is independent of a formal syntax but still follows some rules.

Facing an Exception
An exception is a behavior that should not occur in your program but is likely to show up. The simplest exception looks like a conditional statement and here is an example:

#include <iostream> using namespace std; int main() { int StudentAge; cout << "Student Age: "; cin >> StudentAge; try { if(StudentAge < 0) throw; cout << "\nStudent Age: " << StudentAge << "\n\n"; } catch(...) { } cout << "\n"; return 0; } If you run this program and type a positive integer for the students age, the program would respond by displaying the student age. Thats a good outcome. If you run the program and type a letter or any character, the compiler would display the student age as 0. This is the first proof that the compilers are already configured to deal with some abnormal behavior of a program. When the throw keyword is written by itself, it is a way of asking the compiler to send the exception to another handler. In fact, if there is no other handler written by you, the processing would be handed to the operating system. In this case, if you run the program and type a negative integer, since the program is not prepared to handle the exception itself, because of the presence of a single throw, the operating system would take over and display its own message. This would be abnormal program termination on a Microsoft Windows operating system.

#include <iostream>

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
using namespace std; int main() { double Number1, Number2, Result; // Request two numbers from the user cout << "Please provide two numbers\n"; try { cout << "First Number: "; cin >> Number1; cout << "Second Number: "; cin >> Number2; if( Number2 == 0 ) throw; // Perform a division and display the result Result = Number1 / Number2; cout << "\n" << Number1 << " / " << Number2 << " = " << Result << "\n\n"; } catch(...) { } return 0; }

Test the program and supply two valid numbers such as 126.45 and 5.52
Return to your programming environment and test the program again. This time, type 0 for the second number.

Predicting Exceptions
Writing Local Exceptions
Imagine you write a program that requests a students age from the user. As we know, everybodys age is positive. Therefore, we need to figure out what to do if the user types a negative number. The expression that checks whether the number entered is positive can be written as:

if(StudentAge < 0) If the condition is true, the minimum you can do is to send the produced error away. This is done with the throw keyword: try { if(StudentAge < 0) throw; } Whenever an exception occurs, and whenever you use the try keyword to try an expression, you must transfer control to a catch block. This is where you should display your own message for the error. Here is an example: #include <iostream.h> int main() { int StudentAge; try { cout << "Student Age: "; cin >> StudentAge; if(StudentAge < 0) throw "Positive Number Required"; cout << "\nStudent Age: " << StudentAge << "\n\n"; } catch(const char* Message) { cout << "Error: " << Message;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} cout << "\n"; return 0; } This program starts with the try block that asks the user to enter a positive number. If the user enters an invalid value, the program examines the throw keyword. This throw appears to display a string. The compiler registers this string and since there was an exception, the program exits the try block (it gets out of the try block even if the rest of the try block is fine) and looks for the first catch block it can find. If it finds a catch that doesnt take an argument, it would still use the catch. Otherwise, you can use the catch block to display the error string that was sent by the throw keyword. In the example above, the catch uses a string as a pseudo-argument and displays it using a cout extractor. In the example above, the catch block is configured to display a string. Lets consider the classic division by zero operation. The division by zero is dealt with at different levels. The processor (Intel, AMD, etc) is configured not to allow it. The operating system is also prepared for it. Finally, the compiler has its own interpretation of this operation. Nevertheless, if you suspect it to occur in your program, you can take appropriate measures. When preparing to deal with division by zero, the main idea is to compare the denominator with 0. This comparison should be performed in a try block. If the comparison renders true, you should avoid the operation and hand the error (exception) to a catch. The catch is usually used to display a message as in the last code. Here is an example: #include <iostream> using namespace std; int main() { double Operand1, Operand2, Result; // Request two numbers from the user cout << "This program allows you to perform a division of two numbers\n"; cout << "To proceed, enter two numbers: "; try { cout << "First Number: "; cin >> Operand1; cout << "Second Number: "; cin >> Operand2; // Find out if the denominator is 0 if( Operand2 == 0 ) throw "Division by zero not allowed"; // Perform a division and display the result Result = Operand1 / Operand2; cout << "\n" << Operand1 << " / " << Operand2 << " = " << Result << "\n\n"; } catch(const char* Str) // Catch an exception { // Display a string message accordingly cout << "\nBad Operator: " << Str; } return 0; } The catch clause can use any type of variable as long as you configure it accordingly. Instead of a string as we have seen, you can send it an integer, then display an error depending on the integer that was sent.

#include <iostream.h> int main() { double Operand1, Operand2, Result; const char Operator = '/'; // Request two numbers from the user cout << "This program allows you to perform a division of two numbers\n"; cout << "To proceed, enter two numbers\n"; try { cout << "First Number: "; cin >> Operand1; cout << "Second Number: ";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cin >> Operand2; // Find out if the denominator is 0 if( Operand2 == 0 ) throw 0; // Perform a division and display the result Result = Operand1 / Operand2; cout << "\n" << Operand1 << " / " << Operand2 << " = " << Result << "\n\n"; } catch(const int n) // Catch an exception { // Display a string message accordingly cout << "\nBad Operator: Division by " << n << " not allowed\n\n"; } return 0; }

Catching Multiple Exceptions


The exceptions as we have seen so far dealt with a single exception in a program. Most of the time, a typical program will throw different types of errors. The C++ language allows you to include different catch blocks. Each catch block can face a specific error. The syntax used is: try { Code to Try } catch(Arg1) { One Exception } catch(Arg2) { Another Exception } The compiler would proceed in a top-down as follows: 1. Following the normal flow control of the program, the compiler enters the try block. 2. If no exception occurs in the try block, the rest of the try block is executed. If an exception occurs in the try block, the try displays a throw that specifies the type of error that happened. a. The compiler gets out of the try block and examines the first catch b. If the first catch doesnt match the thrown error, the compiler proceeds with the next catch. This continues until the compiler finds a catch that matches the thrown error. c. If one of the catches matches the thrown error, its body executes. If no catch matches the thrown error, you have (or the compiler has) two alternatives. If there is no catch that matches the error (which means that you didnt provide a matching catch), the compiler hands the program flow to the operating system (which calls the terminate() function). Another alternative is to include a catch whose argument is three periods: catch(). The catch() is used if no other catch, provided there was another, matches the thrown error. The catch(), if included as part of a catch clause, must always be the last catch, unless it is the only catch of the clause. Multiple catches are written if or when a try block is expected to throw different types of errors. Imagine a program that requests some numbers from the user and performs some operation on the numbers. Such a program can be written as follows:

#include <iostream.h> int main() { double Operand1, Operand2, Result; char Operator; cout << "This program allows you to perform an operation on two numbers\n"; cout << "To proceed, enter a number, an operator, and a number:\n"; cin >> Operand1 >> Operator >> Operand2; switch(Operator) {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
case '+': Result = Operand1 + Operand2; break; case '-': Result = Operand1 - Operand2; break; case '*': Result = Operand1 * Operand2; break; case '/': Result = Operand1 / Operand2; break; default: cout << "Bad Operation"; } cout << "\n" << Operand1 << " " << Operator << " " << Operand2 << " = " << Result; cout << "\n\n"; return 0; } This program works fine as long as the user types a valid sequence of values made of a number followed by a valid arithmetic operator, followed by a number. Anything else, such as an invalid number, an unexpected operator, or a wrong sequence (such as Number Number Operator), would produce an unpredictable outcome. Obviously various bad things could happen when this program is running. To handle the exceptions that this program could produce, you can start with the most likely problem that would occur. Trusting that a user is able to provide the two numbers that are requested, it is possible that she would type an invalid operator. For example, for this program we will perform only the addition (+), the subtraction(-), the multiplication(*), and the division(/). Therefore, we will first validate the operator. This can be done as follows: #include <iostream> #include <string> using namespace std; int main() { double Operand1, Operand2, Result; char Operator; cout << "This program allows you to perform an operation on two numbers\n"; try { cout << "To proceed, enter a number, an operator, and a number:\n"; cin >> Operand1 >> Operator >> Operand2; if(Operator != '+' && Operator != '-' && Operator != '*' && Operator != '/') throw Operator; switch(Operator) { case '+': Result = Operand1 + Operand2; break; case '-': Result = Operand1 - Operand2; break; case '*': Result = Operand1 * Operand2; break; case '/': Result = Operand1 / Operand2; break; } cout << "\n" << Operand1 << " " << Operator << " " << Operand2 << " = " << Result; } catch(const char n) { cout << "\nOperation Error: " << n << " is not a valid operator"; } cout << "\n\n"; return 0;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} When this program runs, if the user provides two valid numbers but a wrong operator, the program asks a throw to send a character (in fact the character that was typed as the operator) that represents the error. Then, when the compiler gets out of the try block, it looks for and finds a catch clause that receives a character value. Therefore, this catch is executed. Imagine that the user wants to perform a division. You need to tell the compiler what to do if the user enters the denominator as 0 (or 0.00). If this happens, the best option, and probably the only one you should consider, is to display a message and get out. To implement this behavior, we will add another catch block that displays a message:

#include <iostream.h> int main() { double Operand1, Operand2, Result; char Operator; // Request two numbers from the user cout << "This program allows you to perform a division of two numbers\n"; cout << "To proceed, enter two numbers\n"; try { cout << "First Number: "; cin >> Operand1; cout << "Operator: "; cin >> Operator; cout << "Second Number: "; cin >> Operand2; // Make sure the user typed a valid operator if(Operator != '+' && Operator != '-' && Operator != '*' && Operator != '/') throw Operator; // Find out if the denominator is 0 if(Operator == '/') if(Operand2 == 0) throw 0; // Perform an operation based on the user's choice switch(Operator) { case '+': Result = Operand1 + Operand2; break; case '-': Result = Operand1 - Operand2; break; case '*': Result = Operand1 * Operand2; break; case '/': Result = Operand1 / Operand2; break; } // Display the result of the operation cout << "\n" << Operand1 << " " << Operator << " " << Operand2 << " = " << Result << "\n\n"; } catch(const char n) { cout << "\nOperation Error: " << n << " is not a valid operator\n\n"; } catch(const int p) { cout << "\nBad Operation: Division by " << p << " not allowed\n\n"; } return 0; } When running this program, if the user types a wrong operator, the compiler considers the integer error, gets out f the try block, and looks for a catch that can use a character. The first catch can validate it and gets executed. If the user enters the right values (Number Operator Number), then the compiler finds out if the operator entered was a forward slash / used to perform a division. If the user wants to

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
perform a division, the compiler finds out if the second operand, the denominator, is 0. If it is, the program presents a throw that sends an integer. Based on this exception, the compiler gets out of the try block and starts looking for a catch block that can use an integer. The first catch cant, it uses a character. Therefore, the compiler looks at the next catch, if any. Our program provides a second catch that takes an integer as an argument. Therefore, this catch gets executed. Not all our problems are solved. Image the user types an invalid number. The first characteristic of an invalid number is one that contains anything else than a digit (a character between 0 and 9). Since our program performs its operations on decimal numbers, we need to allow the number to have a decimal portion. Instead of expecting numeric values from the user, we will request arrays of characters. We will use the isdigit() function to examine each character entered in order to find out whether any one of them is not a digit. Also, we will allow the user to type a period that separates the decimal part of a number. If any of the characters that the user entered is not a digit, we will throw a string error so a catch can deal with it. This means that we will add a catch that is different from the other already existing ones. So far, we were requesting two double-precision numbers from the user. In order to check each number and validate it, instead of decimals, we will ask the user to type two strings (arrays of characters): #include <iostream> #include <string> using namespace std; int main() { char Number1[40], Number2[40]; double Operand1, Operand2, Result; char Operator; // Request two numbers from the user cout << "This program allows you to perform a division of two numbers\n"; cout << "To proceed, enter two numbers\n"; try { cout << "First Number: "; cin >> Number1; cout << "Operator: "; cin >> Operator; cout << "Second Number: "; cin >> Number2; // Examine each character of the first operand // to find out if the user included a non-digit in the number for(int i = 0; i < strlen(Number1); i++) if( (!isdigit(Number1[i])) && (Number1[i] != '.') ) // Allow the period throw Number1;// Send the error as a string Operand1 = atof(Number1); // Do the same for the second number entered for(int j = 0; j < strlen(Number2); j++) if( (!isdigit(Number2[j])) && (Number2[j] != '.') ) // Allow the period throw Number2;// Send the error as a string Operand2 = atof(Number2); // Make sure the user typed a valid operator if(Operator != '+' && Operator != '-' && Operator != '*' && Operator != '/') throw Operator; // Find out if the denominator is 0 if(Operator == '/') if(Operand2 == 0) throw 0; // Perform an operation based on the user's choice switch(Operator) { case '+': Result = Operand1 + Operand2; break; case '-': Result = Operand1 - Operand2; break; case '*': Result = Operand1 * Operand2; break; case '/':

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Result = Operand1 / Operand2; break; } // Display the result of the operation cout << "\n" << Operand1 << " " << Operator << " " << Operand2 << " = " << Result << "\n\n"; } catch(const int n) { cout << "\nBad Operation: Division by " << n << " not allowed\n\n"; } catch(const char n) { cout << "\nOperation Error: " << n << " is not a valid operator\n\n"; } catch(const char *BadOperand) { cout << "\nError: " << BadOperand << " is not a valid number\n\n"; } return 0; }

Nesting Exceptions
The calculator simulator we have studied so far performs a division as one of its assignments. We learned that, in order to perform any operation. The compiler must first make sure that the user has entered a valid operator. Provided the operator is one of those we are expecting, we also asked the compiler to check that valid numbers were entered. Even if these two criteria are met, it was possible that the user enter 0 for the denominator. The block that is used to check for a non-zero denominator depends on the exception that validates the operators. In other words, before we check the value of the denominator, we have first made sure that a valid number (a string that contains only digits and a period) was entered for the denominator. For this reason, the exception that could result from a zero denominator depends on the user first entering a valid number for the denominator. C++ allows you to nest exceptions, using the same techniques we applied to nest conditional statements. This means that you can write an exception that depends on, and is subject to, another exception. To nest an exception, write a try block in the body of the parent exception. The nested try block must be followed by its own catch(es). To effectively handle the exception, make sure you include an appropriate throw in the try block. Here is an exception: #include <iostream> #include <string> using namespace std; int main() { char Number1[40], Number2[40]; double Operand1, Operand2, Result; char Operator; cout << "This program allows you to perform an operation on two numbers\n"; try { cout cout cout cout << << << << "To proceed, enter\n"; "First Number: "; cin >> Number1; "An Operator: "; cin >> Operator; "Second Number: "; cin >> Number2;

// Examine each character of the first operand // to find out if the user included a non-digit in the number for(int i = 0; i < strlen(Number1); i++) if( (!isdigit(Number1[i])) && (Number1[i] != '.') ) // Allow the period throw Number1; // Send the error as a character Operand1 = atof(Number1); // Do the same for the second number entered for(int j = 0; j < strlen(Number2); j++) if( (!isdigit(Number2[j])) && (Number2[j] != '.') ) // Allow the period throw Number2;//[j]; // Send the error as a character Operand2 = atof(Number2); if(Operator != '+' && Operator != '-' && Operator != '*' && Operator != '/') throw Operator; switch(Operator) { case '+': Result = Operand1 + Operand2;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\n" << Operand1 << " + " << Operand2 << " = " << Result; break; case '-': Result = Operand1 - Operand2; cout << "\n" << Operand1 << " - " << Operand2 << " = " << Result; break; case '*': Result = Operand1 * Operand2; cout << "\n" << Operand1 << " * " << Operand2 << " = " << Result; break; case '/': // The following exception is nested in the previous try try { if(Operand2 == 0) throw "Division by 0 not allowed"; Result = Operand1 / Operand2; cout << "\n" << Operand1 << " / " << Operand2 << " = " << Result; } catch(const char * Str) { cout << "\nBad Operation: " << Str; } break; } } catch(const char n) { cout << "\nOperation Error: " << n << " is not a valid operator"; } catch(const char *BadOperand) { cout << "\nError: " << BadOperand << " is not a valid number"; } cout << "\n\n"; return 0; }

Exceptions and Functions


One of the most effective techniques used to deal with code is to isolate assignments. We have learned this when studying functions. For example, the switch statement that was performing the operations in the normal version of our program can be written as follows: #include <iostream> using namespace std; int main() { double Operand1, Operand2, Result; char Operator; double Calculator(const double N1, const double N2, const char p); cout << "This program allows you to perform a division of two numbers\n"; cout << "To proceed, enter a number, an operator, and a number:\n"; cin >> Operand1 >> Operator >> Operand2; Result = Calculator(Operand1, Operand2, Operator); cout << "\n" << Operand1 << " " << Operator << " " << Operand2 << " = " << Result; cout << "\n\n"; return 0; } double Calculator(const double Oper1, const double Oper2, const char Symbol) { double Value; switch(Symbol) { case '+': Value = Oper1 + Oper2; break; case '-':

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Value = Oper1 - Oper2; break; case '*': Value = Oper1 * Oper2; break; case '/': Value = Oper1 / Oper2; break; } return Value; } You can still use regular functions along with functions that handle exceptions. Here is an example: #include <iostream> #include <string> using namespace std; double Calculator(const double N1, const double N2, const char p); int main() { char Number1[40], Number2[40]; double Operand1, Operand2, Result; char Operator; cout << "This program allows you to perform an operation on two numbers\n"; try { cout cout cout cout << << << << "To proceed, enter\n"; "First Number: "; cin >> Number1; "An Operator: "; cin >> Operator; "Second Number: "; cin >> Number2;

// Examine each character of the first operand // to find out if the user included a non-digit in the number for(int i = 0; i < strlen(Number1); i++) if( (!isdigit(Number1[i])) && (Number1[i] != '.') ) // Allow the period throw Number1; // Send the error as a character Operand1 = atof(Number1); // Do the same for the second number entered for(int j = 0; j < strlen(Number2); j++) if( (!isdigit(Number2[j])) && (Number2[j] != '.') ) // Allow the period throw Number2;//[j]; // Send the error as a character Operand2 = atof(Number2); if(Operator != '+' && Operator != '-' && Operator != '*' && Operator != '/') throw Operator; if(Operator == '/') if(Operand2 == 0) throw 0; Result = Calculator(Operand1, Operand2, Operator); cout << "\n" << Operand1 << " " << Operator << " " << Operand2 << " = " << Result; } catch(const int n) { cout << "\nBad Operation: Division by " << n << " not allowed"; } catch(const char n) { cout << "\nOperation Error: " << n << " is not a valid operator"; } catch(const char *BadOperand) { cout << "\nError: " << BadOperand << " is not a valid number"; } cout << "\n\n"; return 0; } double Calculator(const double Oper1, const double Oper2, const char Symbol) { double Value; switch(Symbol) { case '+':

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Value = Oper1 + Oper2; break; case '-': Value = Oper1 - Oper2; break; case '*': Value = Oper1 * Oper2; break; case '/': Value = Oper1 / Oper2; break; } return Value; } As done in the main() function, any member function of a program can take care of its own exceptions that would occur in its body. Here is an example of an exception handled in a function: #include <iostream> #include <string> using namespace std; int main() { char Number1[40], Number2[40]; double Operand1, Operand2, Result; char Operator; void Calculator(const double N1, const double N2, const char p); cout << "This program allows you to perform an operation on two numbers\n"; try { cout cout cout cout << << << << "To proceed, enter\n"; "First Number: "; cin >> Number1; "An Operator: "; cin >> Operator; "Second Number: "; cin >> Number2;

// Examine each character of the first operand // to find out if the user included a non-digit in the number for(int i = 0; i < strlen(Number1); i++) if( (!isdigit(Number1[i])) && (Number1[i] != '.') ) // Allow the period throw Number1; // Send the error as a character Operand1 = atof(Number1); // Do the same for the second number entered for(int j = 0; j < strlen(Number2); j++) if( (!isdigit(Number2[j])) && (Number2[j] != '.') ) // Allow the period throw Number2; // Send the error as a character Operand2 = atof(Number2); if(Operator != '+' && Operator != '-' && Operator != '*' && Operator != '/') throw Operator; Calculator(Operand1, Operand2, Operator); } catch(const char n) { cout << "\nOperation Error: " << n << " is not a valid operator"; } catch(const char *BadOperand) { cout << "\nError: " << BadOperand << " is not a valid number"; } cout << "\n\n"; return 0; } void Calculator(const double Oper1, const double Oper2, const char Symbol) { double Value; switch(Symbol) { case '+': Value = Oper1 + Oper2; cout << "\n" << Oper1 << " + " << Oper2 << " = " << Value; break;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
case '-': Value = Oper1 - Oper2; cout << "\n" << Oper1 << " - " << Oper2 << " = " << Value; break; case '*': Value = Oper1 * Oper2; cout << "\n" << Oper1 << " * " << Oper2 << " = " << Value; break; case '/': // The following try exception is nested in the previous try try { if(Oper2 == 0) throw "Division by 0 not allowed"; Value = Oper1 / Oper2; cout << "\n" << Oper1 << " / " << Oper2 << " = " << Value; } catch(const char * Str) { cout << "\nBad Operation: " << Str; } break; } } Isolating assignments and handing them to functions is a complete and important matter in the area of application programming. Consider a program that handles a simple exception such as this one:

#include <iostream> using namespace std; int main() { double Operand1, Operand2, Result; char Operator = '/'; cout << "This program allows you to perform a division of two numbers\n"; try { cout << "To proceed, enter two numbers: "; cin >> Operand1 >> Operand2; if( Operand2 == 0 ) throw "Division by zero not allowed"; Result = Operand1 / Operand2; cout << "\n" << Operand1 << " / " << Operand2 << " = " << Result; } catch(const char* Str) { cout << "\nBad Operator: " << Str; } cout << "\n\n"; return 0; } One of the ways you can use functions in exception routines is to have a central function that receives variables, sends them to an external function. The external function tests the value of a variable. If an exception occurs, the external function displays or sends a throw. This throw can be picked up by the function that sent the variable. If the throw carries a value such as an integer or a string, the function that originated the try can hand it to a catch or one of its catches to handle the exception. Observe the following example that implements this scenario: #include <iostream> using namespace std; void Division(const double a, const double b); int main() { double Operand1, Operand2; cout << "This program allows you to perform a division of two numbers\n"; // Start an exception

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
try { cout << "To proceed, enter two numbers: "; cin >> Operand1 >> Operand2; // Pass the new values to a function that will analyze them Division(Operand1, Operand2); } catch(const char* Str) { cout << "\nBad Operator: " << Str; } cout << "\n\n"; return 0; } void Division(const double a, const double b) { double Result; // If an exception occurred, if( b == 0 ) // then throw a string to the function caller throw "Division by zero not allowed"; Result = a / b; cout << "\n" << a << " / " << b << " = " << Result; } In this program, the Division function receives two values that it is asked to perform and division with. The Division function analyzes the second argument that represents the denominator. If this argument is zero, an exception is fund and the Division functions throws a string back to the function that sent the arguments. C++ (as described in the C++ Standards), allows you to specify that a function is an exception carrier. If you write a function that carries an exception, you can type the throw keyword followed by parentheses on the right side of the function. Here is an example: #include <iostream> using namespace std; void Division(const double a, const double b) throw(); int main() { double Operand1, Operand2; cout << "This program allows you to perform a division of two numbers\n"; // Start an exception try { cout << "To proceed, enter two numbers: "; cin >> Operand1 >> Operand2; // Pass the new values to a function that will analyze them Division(Operand1, Operand2); } catch(const char* Str) { cout << "\nBad Operator: " << Str; } cout << "\n\n"; return 0; } void Division(const double a, const double b) throw() { double Result; // If an exception occurred, if( b == 0 ) // then throw a string to the function caller throw; Result = a / b; cout << "\n" << a << " / " << b << " = " << Result; } As if it were a function, the throw keyword used like this must have parentheses. If it doesnt take any argument, the parentheses must be left empty as in the last example. If the function that is called from a try block will throw a specific type of exception, you can specify this in the parentheses of the throw. Here is an example:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#include <iostream> #include <string> using namespace std; void Calculator(const double N1, const double N2, const char p) throw(const char*); int main() { char Number1[40], Number2[40]; double Operand1, Operand2; char Operator; cout << "This program allows you to perform an operation on two numbers\n"; try { cout cout cout cout << << << << "To proceed, enter\n"; "First Number: "; cin >> Number1; "An Operator: "; cin >> Operator; "Second Number: "; cin >> Number2;

for(int i = 0; i < strlen(Number1); i++) if( (!isdigit(Number1[i])) && (Number1[i] != '.') ) throw Number1; Operand1 = atof(Number1); for(int j = 0; j < strlen(Number2); j++) if( (!isdigit(Number2[j])) && (Number2[j] != '.') ) throw Number2; Operand2 = atof(Number2); if(Operator != '+' && Operator != '-' && Operator != '*' && Operator != '/') throw Operator; try { Calculator(Operand1, Operand2, Operator); } catch(const char * Str) { cout << "\nBad Operation: " << Str; } } catch(const char n) { cout << "\nOperation Error: " << n << " is not a valid operator"; } catch(const char *BadOperand) { cout << "\nError: " << BadOperand << " is not a valid number"; } cout << "\n\n"; return 0; } void Calculator(const double Oper1, const double Oper2, const char Symbol) throw(const char*) { double Value; switch(Symbol) { case '+': Value = Oper1 + Oper2; cout << "\n" << Oper1 << " + " << Oper2 << " = " << Value; break; case '-': Value = Oper1 - Oper2; cout << "\n" << Oper1 << " - " << Oper2 << " = " << Value; break; case '*': Value = Oper1 * Oper2; cout << "\n" << Oper1 << " * " << Oper2 << " = " << Value; break; case '/': if(Oper2 == 0) throw "Division by 0 not allowed"; Value = Oper1 / Oper2;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\n" << Oper1 << " / " << Oper2 << " = " << Value; break; } } A function can also be called to perform more than one test to eventually throw more than one exception. Such a function can (and should) be programmed to throw different types of exceptions. Here is an eample of such a function: double Calculator(const double Oper1, const double Oper2, const char Symbol) { double Value; if(Symbol != '+' && Symbol != '-' && Symbol != '*' && Symbol != '/') throw Symbol; switch(Symbol) { case '+': Value = Oper1 + Oper2; cout << "\n" << Oper1 << " + " << Oper2 << " = " << Value; break; case '-': Value = Oper1 - Oper2; cout << "\n" << Oper1 << " - " << Oper2 << " = " << Value; break; case '*': Value = Oper1 * Oper2; cout << "\n" << Oper1 << " * " << Oper2 << " = " << Value; break; case '/': if(Oper2 == 0) throw "Division by 0 not allowed"; Value = Oper1 / Oper2; cout << "\n" << Oper1 << " / " << Oper2 << " = " << Value; break; } return Value; } As you can see, this function throws two different types of exceptions: a character and a string. When writing such a function that throws, but doesnt handle, different exceptions, you should make sure this function throws different types of exceptions. Here is the reason. When a function throws an exception, it only sometimes specifies the type of exception. It doesnt specify where the exception is going. When the function that called this function receives the thrown type, it must figure out what block must catch the throw. If this function (the function that was called) throws various exceptions of the same type, the calling function would send all of them to the same catch. On the other hand, if the called function throws different types of exceptions, the calling function, when it receives the throws, can send each to the appropriate type that would handle it. When a function throws an exception, we learned that we can use the throw keyword on the right side of the function as if it were a function. We also learned to pass an argument to the throw to specify the type of exception that the called function would deal with. If a function is programmed to throw different types of exceptions, you can specify this in the arguments of the throw that is appended to the function. Here are examples: #include <iostream> #include <string> using namespace std; void Calculator(const double N1, const double N2, const char p) throw(const char*, const char); double Validate(const char *N) throw(const char*); int main() { char Number1[40], Number2[40]; double Operand1, Operand2; char Operator;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "This program allows you to perform an operation on two numbers\n"; try { cout cout cout cout << << << << "To proceed, enter\n"; "First Number: "; cin >> Number1; "An Operator: "; cin >> Operator; "Second Number: "; cin >> Number2;

Operand1 = Validate(Number1); Operand2 = Validate(Number2); try { Calculator(Operand1, Operand2, Operator); } catch(const char * Str) { cout << "\nBad Operation: " << Str; } } catch(const char n) { cout << "\nOperation Error: " << n << " is not a valid operator"; } catch(const char *BadOperand) { cout << "\nError: " << BadOperand << " is not a valid number"; } cout << "\n\n"; return 0; } void Calculator(const double Oper1, const double Oper2, const char Symbol) throw(const char*, const char) { double Value; if(Symbol != '+' && Symbol != '-' && Symbol != '*' && Symbol != '/') throw Symbol; switch(Symbol) { case '+': Value = Oper1 + Oper2; cout << "\n" << Oper1 << " + " << Oper2 << " = " << Value; break; case '-': Value = Oper1 - Oper2; cout << "\n" << Oper1 << " - " << Oper2 << " = " << Value; break; case '*': Value = Oper1 * Oper2; cout << "\n" << Oper1 << " * " << Oper2 << " = " << Value; break; case '/': if(Oper2 == 0) throw "Division by 0 not allowed"; Value = Oper1 / Oper2; cout << "\n" << Oper1 << " / " << Oper2 << " = " << Value; break; } } double Validate(const char* N) throw(const char*) { double Valid; for(int i = 0; i < strlen(N); i++) if( (!isdigit(N[i])) && (N[i] != '.') ) throw N; Valid = atof(N); return Valid; }

Previous

Copyright 2000-2010 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

User-Defined Types
Data Type Redefinitions
Introduction
The data types we used in the previous lessons for our variables were directly recognized by the C++ compiler. For this reason they are referred to as built-in types. Those data types are convenient in most scenarios. Sometimes you will need to expand on these types. The C++ language provides you great flexibility on re-defining these existing types or re-defining new ones.

The Type Definition


In the previous lessons, we used some of C++ keywords to identify the data types. Examples were int, short, double, unsigned int, or char. The C++ language allows you to create a new name for a data type without changing the meaning of that data type. This allows you to name a data type with a name that is easier for you. This technique doesn't change anything about the data type, it only gives it a new name you can use in your program. To re-define the name of an existing data type, you use the typedef keyword. The formula to follow is: typedef KnownDataType NewName; The typedef keyword is required to let the compiler know that you are redefining an existing data type. The DataType is any of those we have learned so far. It could be an int, an unsigned int, a char, a double, etc. While a data type can be made of one word (such as short) or more than one word (such as unsigned int), the new name you are creating for the data type must be in one word. An example of renaming a data type is: typedef int NumberOfStudents; In this case, NumberOfStudents is just a new name for an int. It can be used as a new data type exactly as if you were using an int. Here is an example that redefines an int data type and uses it in a program: #include <iostream> using namespace std; int main() { typedef int NumberOfStudents; NumberOfStudents Grade1, Grade2; cout << "Enter the number of students.\n"; cout << "Grade 1: "; cin >> Grade1; cout << "Grade 2: "; cin >> Grade2; cout << "\nNumber of students:"; cout << "\n1st Grade: " << Grade1; cout << "\n2nd Grade: " << Grade2 << "\n\n"; return 0; } Here are examples of creating new names of existing data types using typedef: typedef unsigned int UINT; typedef unsigned char UCHAR; typedef unsigned long ULONG; typedef long double LONGDOUBLE;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Constant Values
Introduction
A constant is a value that does not change. There are various categories of constants you will be using in your programs. For example, the algebraic numbers you are aware of are constants because they never change. Examples of constant numbers are 12, 0, 1505, or 88146. Therefore, any number you can think of is a constant. Every letter of the alphabet is a constant and is always the same. Examples of constant letters are d, n, c. Some characters on your keyboard represent symbols that are neither letters nor digits. These are constants too. Examples are #, &, |, !. Some values would be constant by default, but their constancy sometimes depends on the programmer. For example, one programmer can define a constant PI as 3.14. Another programmer can decide that the constant PI would be 3.14159. Therefore, you will be defining your own constant values as you see fit for the goal you are trying to achieve. There are two main techniques you use a constant value in C++. To simply display it using the cout << extractor, you can type its value on the right side of the << symbols. You can also define it first using an appropriate name, and then using that name to display the constant. Here are two examples #include <iostream> using namespace std;

int main() { cout << 28;

cout << "\nStudent Age: " << 14; cout << "\n\n";

return 0; } To create your own constant value, you can give it a name. This allows you to manage it from one standpoint. Imagine you want to use 3.14 in various sections of the program. If you decide to change the number from 3.14 to 3.14159 or another value, you would have to find every mention of 3.14; this can lead to a programming error. The alternative is to declare a variable and assign it the desired value. The new and defined value is called a constant.

Macro Definition of a Constant


There are two main techniques used to create constant values. The old way, which was used with the C language, widely used in documentation and help files consists of using the define keyword. The syntax of creating a constant using the define keyword is: #define ConstantName ConstantValue The # symbol and the define keyword are required; they inform the compiler that the following name represents a constant. The ConstantName represents a valid name for the desired constant. The name follows the same rules we learned for defining names in C++. The ConstantValue can be a character, an integer, a floating-point value, or an expression. If the constant value is an integer or a floating-point value, you can type it. If the value is a character, include it between single-quotes. If the value is a word or a sentence, include it in double-quotes. Because #define is referred to as a macro, the definition doesn't end with a semi-colon. Here are examples:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#define AGE 12 // AGE represents the constant integer 12 #define ANSWER y #define MAXSTUDENTS 35 #define PI 3.14159 // PI represents 3.14159 After defining the macro, the last value can be used in a program as a constant. For example, you can display it using cout. Here is an example: #include <iostream> using namespace std;

#define EmploymentStatus "Full Time"

int main() { cout << "Status: " << EmploymentStatus << endl;

return 0; } This would produce: Status: Full Time

User-Defined Constants
Another technique of creating a constant consists of using the const keyword. The formula used with the const keyword is: const ConstantName = ConstantValue; Or const DataType ConstantName = Value; The const keyword is required to inform the compiler that you are creating a constant. The ConstantName specifies the name of the constant value; it follows the rules we have applied for the names of variables. The DataType, although optional, is used to let the compiler know the kind of value the constant is. If you don't specify a data type, the compiler would assume that the constant is an integer. Therefore, make it a habit to always specify the data type when creating a constant using the const keyword. The data type can be any of those we have used so far. Use the assignment operator to assign the desired constant to the name. Examples of creating constants with the const keyword are: const float PI = 3.14159; const unsigned int MaxStudents = 42; const string Country = New Zealand; const double Distance = 1678212; After creating the constant, you can use its name in the program to access its value. As we will learn in the next lesson, you can involve it in an operation. You can also display its value using cout. Here is an example: #include <iostream> using namespace std;

int main()

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ const double PI = 3.14159;

cout << "PI = " << PI << endl;

return 0; } This would produce: PI = 3.14159

Built-In Constants
To assist you with constants, the C++ language ships with many of them so you can use them directly in you code. Those constants have names they can be recognized with. For example, the minimum value of the short integer is called SHRT_MIN. In the same way, the maximum short integer is identified by SHRT_MAX. You can use either of these constants as follows: #include <iostream> #include <climits> using namespace std;

int main() { cout << "The minimum signed character: " << SCHAR_MIN << "\n"; cout << "The maximum signed character: " << SCHAR_MAX << "\n"; cout << "The minimum short integer is: " << SHRT_MIN << "\n"; cout << "The maximum short integer is: " << SHRT_MAX << "\n\n";

return 0; } This would produce: The minimum signed character: -128 The maximum signed character: 127 The minimum short integer is: -32768 The maximum short integer is: 32767 According to the C++ Standard, the integral constants are defined in the climits library but they can be defined as one compiler chooses to. For example, in Borland C++ Builder, they are in the _lim.h library. In the KDevelop and Microsoft C++ compilers they are in the limits.h file. The integer constants defined in the climits library are: CHAR_BIT CHAR_MAX CHAR_MIN INT_MAX LONG_MAX SCHAR_MAX SHRT_MAX INT_MIN LONG_MIN SCHAR_MIN SHRT_MIN UINT_MAX ULONG_MAX UCHAR_MAX USHRT_MAX MB_LEN_MAX

In the same way, C++ provides constant double-precision numbers in the cfloat library. These constants are: DBL_DIG FLT_DIG LDBL_DIG

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
DBL_EPSILON DBL_MANT_DIG DBL_MAX DBL_MAX_10_EXP DBL_MAX_EXP DBL_MIN DBL_MIN_10_EXP DBL_MIN_EXP FLT_EPSILON FLT _MANT_DIG FLT _MAX FLT_MAX_10_EXP FLT _MAX_EXP FLT _MIN FLT_MIN_10_EXP FLT _MIN_EXP FLT_RADIX LDBL_EPSILON LDBL_MANT_DIG LDBL_MAX LDBL_MAX_10_EXP LDBL_MAX_EXP LDBL_MIN LDBL_MIN_10_EXP LDBL_MIN_EXP

The C++ Standard also defines a constant as NULL. This constant is used to designate that a pointer does not hold a valid value. The NULL constant is defined in the cstddef library.

Previous

Copyright 1998-2005 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Introduction to Classes
Composite Types
Introduction
Whether using C++ built-in data types or redefinitions, so far all of our variables were declared with simple data types, also called primitive types. This made is easy to recognize that, for example, the number of fingers of a hand could be represented with a simple natural number, or that a simple word made of a group of alphabetical characters could be used to name a hand. If some cases, you may want a group of values to be considered as one entity to represent an object. For example, you may want to use a single data type to represent a hand. C++ allows you to use one or more data types, group them as one, to create a new data type as you see fit. This technique of grouping different values is referred to as a class. C++ offers three techniques of defining a new data type: a structure, a class, and a union. These are also referred to as composite data types.

Structures
A structure is one or a group of variables considered as a (custom) data type. To create a structure, use the struct keyword, followed by a name for the object, at least followed by a semi-colon. Therefore, fundamentally, a structure can be created as: struct SomeName; The struct keyword is required. The name of the structure follows the same rules we reviewed for C++ names. A structure created using the above formula is referred to as an empty structure. Here is an example of a program that contains a structure: #include <iostream> using namespace std;

struct Hand;

int main() { return 0; } We mentioned that the idea of having a composite type is to use at least one known data type to create a new type. To do this, before the semi-colon of the structure, type an opening curly bracket "{" and a closing curly bracket "}". This would be done as follows: #include <iostream> using namespace std;

struct Hand{ };

int main() { return 0; } The section between the curly brackets is referred to as the body of the structure. Inside of this body, you can declare at least one variable that would be used to define the structure. The

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
variable must be declared complete with a known data type, a name and the ending semi-colon. Here is an example: #include <iostream> using namespace std;

struct Hand{ int numberOfFingers; };

int main() { return 0; } Any variable you declare within the body of the structure is referred to as a member of that structure. For example, a variable such as NumberOfStudents is referred to as a member variable of the Hand structure. The body of the structure doesn't have to be written on the same line with a structure. In fact, to make your code easier to read, you can spread the body of the structure and its members on different lines. Based on this, the above code could have been written as: #include <iostream> using namespace std;

struct Hand{ int numberOfFingers; };

int main() { return 0; } or as: #include <iostream> using namespace std;

struct Hand { int numberOfFingers; };

int main() { return 0; }

Classes
Besides the structure, C++ provides a second way to create a custom data type. This is done using the exact same techniques as the structure except that you use the class keyword. Based on this, the above program can also be written as follows: #include <iostream> using namespace std;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
class Hand { int numberOfFingers; };

int main() { return 0; } Just as you can have an empty structure, you can also have an empty class: #include <iostream> using namespace std;

class Hand;

int main() { return 0; } In fact, every rule we reviewed for the structure (C++ naming rules, the body, the member variables, the curly brackets) also applies to the class. In the next sections, we will see that there is only one detail that sets the structure and the class apart. From now on, we will use the word "class" (non-bold) interchangeably to refer to either the structure or the class. When we explicitly mean a structure, we will write struct (bold) and when we explicitly designate a class, we will write class (bold).

Object Creation and Access


Introduction
After creating a class, you can use it in your program as a normal data type. Just as done for built-in C++ data types, you can first declare a variable of the class. Here is an example: #include <iostream> using namespace std;

struct Hand { int numberOfFingers; };

int main() { Hand human; return 0; } When you declare a variable of a class, you are said to create an Instance of the class. This means that the variable you declare is an instance of the class. In the same way, a variable

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
you declare is called an object. It is important to understand the difference between a class and an object: A class is the list of characteristics that can be used to describe an object. An object is the result of describing something using the characteristics defined in a class. As seen above, you can declare a variable using a class. You can also declare a variable using any of the data types we have used in the previous lessons. In fact, in Lesson 3, we saw that you could declare a global variable outside of any function. Here is an example: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

class Hand { int numberOfFingers; };

int Hand;

int main( int argc, char * argv[] ) { Hand human;

return 0; } With this example, our program has two variables with the name of one variable being the same as the name of a class. When you declare a Hand variable in main(), as done above, and if you try compiling the program, the compiler would not know what Hand is being accessed in main() and thus would produce an error. If you declare a variable that holds a name similar to that of an existing class, when creating an instance of the class, you must specify to the compiler that the new variable is based on the class and has nothing to do with the other variable. To specify this, start the class' declaration with the class or struct keyword. Here is an example: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

struct Hand { int numberOfFingers; };

int Hand;

int main( int argc, char * argv[] ) {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
struct Hand human; return 0; } This time, the program will compile fine.

Global Objects
Just as reviewed for variables of primitive types, if you create an object inside of a function, which is referred to as a local declaration, the object can be accessed only from that function. If you want an object to be accessible to more than one function, you can declare it outside of any function. This is a global declaration. To proceed, you would use the same approach as the global declaration of a primitive type. Here is an example: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

struct Foot { int numberOfToes; };

Foot animal;

int main( int argc, char * argv[] ) { struct Foot human; return 0; } Once again, it is important to know that the compiler works from top-down. If you declare a variable globally, it can be "seen" only by functions under it. Based on this, in the above example, you can access the animal variable from main(). Consider the following: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

struct Foot { int numberOfFingers; };

Foot animal;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
int main( int argc, char * argv[] ) { struct Foot human; return 0; }

Foot bird; In this case, you can access animal from main() but you cannot access bird from main().

Access to a Member of a Class


After declaring a variable based on a class, you can access its member variables, outside of the class, either to change their value or to retrieve the values they hold. To access the member of a class outside of the class, after declaring it, type the name of the variable, followed by a period, and followed by the name of the member you want to access. For example, to access the NumberOfFingers member variable of a class called Hand using its object instance called human, you would write: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

struct Hand { int numberOfFingers; };

int Hand;

int main( int argc, char * argv[] ) { struct Hand human ;

human.numberOfFingers;

return 0; } It is important to know that you cannot access a member variable while declaring a variable of the class. For example, the following code will not work: Hand human.NumberOfFingers; You must first declare the variable followed by its semi-colon. Then access the member variable. After accessing a member of a class, one of the operations you can perform would consist of assigning it a variable, which is referred to as initializing it. In C++, a member of a class cannot be initialized inside of the class. The member would be initialized outside of the class. Here is an example that assigns a value to a member variable of a class: #ifdef __BORLANDC__ #pragma argsused #endif

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

#include <iostream> using namespace std;

struct Hand { int numberOfFingers; };

int Hand;

int main( int argc, char * argv[] ) { struct Hand human ;

human.NumberOfFingers = 5;

return 0; } In the same way, you can use the period operator to access the member variable of a class and retrieve its value. Here is an example: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

struct Hand { int numberOfFingers; };

int Hand;

int main( int argc, char * argv[] ) { struct Hand human ;

Hand = 4; human.numberOfFingers = 5;

cout << "Hand

= " << Hand << endl;

cout << "Fingers = " << human.numberOfFingers;

return 0;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} Just as done for variables of built-in types, you can declare as many variables as you see fit in your program. Here is an example: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

class Foot { int NumberOfToes; };

int main( int argc, char * argv[] ) { Foot human; Foot animal;

return 0; } You can also declare various variables on the same line, separated by commas. Here are examples: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream>

using namespace std;

class Foot { int NumberOfToes; };

int main( int argc, char * argv[] ) { Foot human, duck, dog, hen;

return 0; }

Type-Defining a Class
Just as you can type-define the name of a built-in data type, you can do the same for any class. As reviewed for primitive types, when doing this, remember that you are not creating a

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
new type: you are only providing a pseudo-name for an existing class. Here is an example: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

class Hand { int numberOfFingers; };

int main( int argc, char * argv[] ) { typedef Hand BodyMember;

return 0; } After type-defining a class, you can use the new name to declare a variable as if you were using the actual name of the class. Here is an example: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

class Hand { int numberOfFingers; };

int main( int argc, char * argv[] ) { typedef Hand BodyMember;

BodyMember human; return 0; } Remember that you can also type-define a class' name globally, that is, outside of any function, and use it in the other functions that would need the new name: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream>

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
using namespace std;

class Hand { int numberOfFingers; };

typedef Hand BodyMember;

int main( int argc, char * argv[] ) { BodyMember human; return 0; }

Class Forward Definition


Sometimes when creating a class, you may already know the member(s) you want it to have. In some cases, you may want to first communicate the name of the class but you are not ready to list its members. C++ allows you to perform what is referred to a forward definition. In this case, you specify only the type (struct or class) and the name of the class. This allows you to do some tasks that don't require the members of the class. Here is an example: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

class Hand; typedef Hand BodyMember;

// Do anything here

int main( int argc, char * argv[] ) { return 0; } Once you are ready, you can then complete the class as you see fit. Here is an example: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

class Hand; typedef Hand BodyMember;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

// Do anything here

class Hand { int numberOfFingers; };

int main( int argc, char * argv[] ) { BodyMember human;

return 0; } If you use this technique, you still must define the class before you are able to use it. Consider the following code: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

class Hand; typedef Hand BodyMember;

// Do anything here

int main( int argc, char * argv[] ) { BodyMember human;

return 0; }

class Hand { int numberOfFingers; }; This code will not compile because, at the time the class is instantiated in main(), its definition is not known, only its emptiness, which is not enough.

The Access Levels of a Class


So far, to make our learning process easier, we declared only one member variable in a class. The primary reason for using a class as opposed to a built-in data type is to be able to group different characteristics used to describe the class and make it as complete as possible. This means that a class is meant to have as many members as you judge necessary. To apply this, in the body of the class, declare the necessary variables, each with a data type and a name,

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
and each declaration ending with a semi-colon. Here is an example: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

struct Car { int Year;

unsigned NumberOfDoors; long char }; Mileage; DrivingCondition;

int main( int argc, char * argv[] ) { return 0; } Once again, to access its members outside of the class, you can first declare a variable based on the class. To access a member variable, you type the class' variable name, followed by the period operator. Here is an example: #include <iostream> using namespace std;

struct Car { int Year;

unsigned NumberOfDoors; long char }; Mileage; DrivingCondition;

int main() { Car vehicle;

vehicle.Mileage = 42580;

cout << "Car Characteristics\n"; cout << "Mileage: " << vehicle.Mileage << endl;

return 0; } This would produce: Car Characteristics

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Mileage: 42580

A common object in real life is visibly made of two categories of parts: those you can see or touch and those you do not have access to. The parts you can see or touch are considered visible or accessible. In C++, such parts are referred to as public. Those you cannot see or touch are considered hidden. In C++, such parts are referred to as private. Like objects in real life, a class is made of sections that the other parts or other objects cannot see and those the other objects can access. The other objects of of the program are sometimes referred to as the clients of the object. The parts the client of an object can touch in a class are considered public and the others are private. When creating a class, you will define which items are public and which ones are private. The items that are public are created in a section that starts with the public keyword followed by a semi-colon. Here is an example: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

struct Car { public: int Year;

unsigned NumberOfDoors; long char }; Mileage; DrivingCondition;

int main( int argc, char * argv[] ) { Car vehicle;

vehicle.Mileage = 42580; cout << "Car Characteristics\n"; cout << "Mileage: " << vehicle.Mileage;

return 0; } In the same way, the hidden parts are in a section that starts with the private keyword followed by a semi-colon. If you don't specify these sections, all of the members of a class are considered private. The difference between a class and a structure is that, by default, all of the members of a class are private and, by default, all of the members of a structure are public. That is how it works if you don't create your own public and private sections. For example, the following program will not compile: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream>

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
using namespace std;

class Car { int Year;

unsigned NumberOfDoors; long char }; Mileage; DrivingCondition;

int main( int argc, char * argv[] ) { Car vehicle;

vehicle.Mileage = 42580; cout << "Car Characteristics\n"; cout << "Mileage: " << vehicle.Mileage;

return 0; } The reason is that the Mileage member variable that belongs to a class type is private and therefore cannot be accessed from main(). To resume, when creating your class, you can specify the necessary access levels using the public: and private: sections. Here is an example: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

struct Car { public: int Year;

unsigned NumberOfDoors; bool private: char short char public: long }; Mileage; DrivingCondition; TypeOfTransmission; Color; HasAirCondition;

int main( int argc, char * argv[] ) {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Car vehicle;

vehicle.Mileage = 42580; cout << "Car Characteristics\n"; cout << "Mileage: " << vehicle.Mileage;

return 0; } As you can see from this class, there are no rules as to the number of public or private sections you can have in a class. There are no rules on the order of the access levels: you can create a public or a private section anywhere in the class, just remember that any member under an access level follows the rules of that access. The fact that you use different public sections does not by any means provide different public levels to the variables. A variable declared as public in one public section has the same public level of access as any other variable that is declared in another public section.

Object Initialization
Initializing Each Member of a Class
Just as variables of primitive types, an object declared from a class can also be initialized. There are various techniques you can use: initializing individual members or initializing the class as a whole. To initialize a member of a class, access it and assign it an appropriate value using the rules of C++: If the member is a numeric type, assign it a number of your choice If the member is a char type, assign it a symbol or character in single-quotes If the member is of type bool, assign it true or false If the member is a string type, assign it a value in double-quotes If the member is an array of character, use the strcpy() function to copy a value into it Here are examples: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

struct Car { char char int Make[40]; Model[40]; Year;

unsigned NumberOfDoors; bool long }; HasAirCondition; Mileage;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
int main( int argc, char * argv[] ) { Car vehicle;

vehicle.Mileage = 42885; strcpy(vehicle.Model, "Escort"); vehicle.NumberOfDoors = 4; strcpy(vehicle.Make, "Ford"); vehicle.HasAirCondition = true; vehicle.Year = 2000;

cout << "Car Auctions - Vehicle Characteristics"; cout << "\nYear: " << vehicle.Year;

cout << "\nMileage: " << vehicle.Mileage; cout << "\nMake: cout << "\nModel: cout << "\nDoors: " << vehicle.Make; " << vehicle.Model; " << vehicle.NumberOfDoors;

cout << "\nHas A/C: " << vehicle.HasAirCondition;

return 0; } This would produce: Car Auctions - Vehicle Characteristics Year: 2000

Mileage: 42885 Make: Model: Doors: Ford Escort 4

Has A/C: 0

Initializing an Object as a Whole


You can also initialize an object as a variable. This time, type the name of the variable followed by the assignment operator, followed by the desired values of the variables listed between an opening and a closing curly brackets. Here are the rules you must follow: The list of values must follow the order of the declared member variables of the class The values are separated with commas None of the members of the class can be another class. For example, no member variable should have been declared as string Here is an example:

#ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
struct Car { char char int Make[40]; Model[40]; Year;

unsigned NumberOfDoors; bool long }; HasAirCondition; Mileage;

int main( int argc, char * argv[] ) { Car SUV = { "Toyota", "4-Runner", 1998, 5, true, 57922 };

cout << "Car Auctions - Vehicle Characteristics"; cout << "\nYear: " << SUV.Year;

cout << "\nMileage: " << SUV.Mileage; cout << "\nMake: cout << "\nModel: cout << "\nDoors: " << SUV.Make; " << SUV.Model; " << SUV.NumberOfDoors;

cout << "\nHas A/C: " << SUV.HasAirCondition;

return 0; } This would produce: Car Auctions - Vehicle Characteristics Year: 1998

Mileage: 57922 Make: Model: Doors: Toyota 4-Runner 5

Has A/C: 1

Static Member Variables


A class can have static member variables. To declare such a variable, precede it with the static keyword. Here is an example: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

struct Car

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ string string int Make; Model; Year;

unsigned NumberOfDoors; long Mileage;

static int CarsCount; };

int main( int argc, char * argv[] ) { Car vehicle;

vehicle.Year

= 1998;

vehicle.Mileage = 57922; vehicle.Make = "Toyota";

vehicle.Model = "4-Runner"; vehicle.NumberOfDoors = 5;

cout << "Car Auctions - Vehicle Characteristics"; cout << "\nYear: " << vehicle.Year;

cout << "\nMileage: " << vehicle.Mileage; cout << "\nMake: cout << "\nModel: cout << "\nDoors: " << vehicle.Make; " << vehicle.Model; " << vehicle.NumberOfDoors;

return 0; } When you declare a member variable as static and when the application starts, the compiler creates a copy of that member. This member would be maintained by the compiler while the program is running. If you declare an instance of a class, like the above vehicle variable, the static member is not part of the (vehicle) object: the compiler creates and maintains the CarsCount member, whether you use it or not, whether you declare a Car variable or not. After creating a class that contains a static member variable, if you intend to use that member, you should (in fact must) first initialize it with the value you want it to hold. Because a static member variable doesn't belong to an object, it must be initialized at file cope, by the class itself and not one of its instances. To initialize a static member variable, outside of the class, enter its data type, followed by the name of the class, followed by the access operator "::", followed by the name of the member variable, followed by the assignment operator, and followed by a value. Like any other member variable, you can assign any appropriate value to a static member: you decide what value you want it to have. Here is an example: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

struct Car

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ string string int Make; Model; Year;

unsigned NumberOfDoors; long Mileage;

static int CarsCount; };

int Car::CarsCount = 0;

int main( int argc, char * argv[] ) { Car vehicle;

return 0; } After creating and initializing a static member variable, to access it outside of the class, you must qualify it with the name of the class itself and not a variable of that class. Here are two examples: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

struct Car { string string int Make; Model; Year;

unsigned NumberOfDoors; long Mileage;

static int CarsCount; static string ApplicationTitle; };

int Car::CarsCount = 1; string Car::ApplicationTitle = "Four-Corner Car Auctions";

int main( int argc, char * argv[] ) { Car vehicle;

vehicle.Year

= 1998;

vehicle.Mileage = 57922;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
vehicle.Make = "Toyota";

vehicle.Model = "4-Runner"; vehicle.NumberOfDoors = 5;

cout << Car::ApplicationTitle; cout << "\n - Vehicle Characteristics -"; cout << "\nYear: " << vehicle.Year;

cout << "\nMileage: " << vehicle.Mileage; cout << "\nMake: cout << "\nModel: cout << "\nDoors: cout << "\nCount: " << vehicle.Make; " << vehicle.Model; " << vehicle.NumberOfDoors; " << Car::CarsCount;

return 0; } This would produce: Four-Corner Car Auctions - Vehicle Characteristics Year: 1998

Mileage: 57922 Make: Model: Doors: Count: Toyota 4-Runner 5 1

Always remember that a static member doesn't belong to a particular object, in this case vehicle. Therefore, to access it, you use the name of the class with the "::" operator. With this rule in mind, you can assign the value of a static member to a variable of the program. Here is an example: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

struct Car { string string int Make; Model; Year;

unsigned NumberOfDoors; long Mileage;

static int CarsCount; static string ApplicationTitle; };

int Car::CarsCount = 1;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
string Car::ApplicationTitle = " Four-Corner Car Auctions";

int main( int argc, char * argv[] ) { Car vehicle;

vehicle.Year

= 1998;

vehicle.Mileage = 57922; vehicle.Make = "Toyota";

vehicle.Model = "4-Runner"; vehicle.NumberOfDoors = 5;

int numberOfCars = Car::CarsCount;

cout << Car::ApplicationTitle; cout << "\n - Vehicle Characteristics -"; cout << "\nYear: " << vehicle.Year;

cout << "\nMileage: " << vehicle.Mileage; cout << "\nMake: cout << "\nModel: cout << "\nDoors: cout << "\nCount: " << vehicle.Make; " << vehicle.Model; " << vehicle.NumberOfDoors; " << numberOfCars << endl;

return 0; } You can decrement or increment it as you wish: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

struct Car { string string int Make; Model; Year;

unsigned NumberOfDoors; long Mileage;

static int CarsCount; static string ApplicationTitle; };

int Car::CarsCount = 1; string Car::ApplicationTitle = " Four-Corner Car Auctions";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

int main( int argc, char * argv[] ) { Car vehicle;

vehicle.Year

= 1998;

vehicle.Mileage = 57922; vehicle.Make = "Toyota";

vehicle.Model = "4-Runner"; vehicle.NumberOfDoors = 5;

cout << Car::ApplicationTitle; cout << "\n - Vehicle Characteristics -"; cout << "\nYear: " << vehicle.Year;

cout << "\nMileage: " << vehicle.Mileage; cout << "\nMake: cout << "\nModel: cout << "\nDoors: cout << "\nCount: " << vehicle.Make; " << vehicle.Model; " << vehicle.NumberOfDoors; " << Car::CarsCount << endl;

Car family;

family.Mileage = 42885; family.Model = "Escort"; family.NumberOfDoors = 4; family.Make = "Ford"; family.Year = 2000; Car::CarsCount++;

cout << "\n - Vehicle Characteristics -"; cout << "\nYear: " << family.Year;

cout << "\nMileage: " << family.Mileage; cout << "\nMake: cout << "\nModel: cout << "\nDoors: cout << "\nCount: " << family.Make; " << family.Model; " << family.NumberOfDoors; " << Car::CarsCount << endl;

return 0; } This would produce: Four-Corner Car Auctions - Vehicle Characteristics Year: 1998

Mileage: 57922 Make: Model: Toyota 4-Runner

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Doors: Count: 5 1

- Vehicle Characteristics Year: 2000

Mileage: 42885 Make: Model: Doors: Count: Ford Escort 4 2

Other Techniques of Creating an Object


Classic C Styles
So far, to declare a variable of a class, we did this in the main() function. C++ supports another technique. You can declare a class when creating it. To do this, type the name of the class' variable between the closing curly bracket and the semi-colon. Here is an example: #include <iostream> using namespace std;

struct Car { int Year;

unsigned NumberOfDoors; long char }vehicle; Mileage; DrivingCondition;

int main() { vehicle.Mileage = 42580; vehicle.NumberOfDoors = 4; vehicle.DrivingCondition = 'G'; vehicle.Year = 2000;

cout << "Car Characteristics\n"; cout << "Year: " << vehicle.Year << endl;

cout << "Condition: " << vehicle.DrivingCondition << endl; cout << "Mileage: cout << "Doors: " << vehicle.Mileage << endl; " << vehicle.NumberOfDoors << endl;

return 0; } Just like you would declare more than one variable of a class, you can declare many class instances using this technique, separating them with commas. Here are examples: #include <iostream>

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
using namespace std;

struct Car { int Year;

unsigned NumberOfDoors; long char }Sport, SUV, Bus; Mileage; DrivingCondition;

int main() { SUV.Mileage = 28446; SUV.NumberOfDoors = 5; SUV.DrivingCondition = 'D'; SUV.Year = 2002;

Sport.Mileage = 68208; Sport.NumberOfDoors = 2; Sport.DrivingCondition = 'E'; Sport.Year = 1998;

cout << "First Car Characteristics\n"; cout << "Year: " << SUV.Year << endl;

cout << "Condition: " << SUV.DrivingCondition << endl; cout << "Mileage: cout << "Doors: " << SUV.Mileage << endl; " << SUV.NumberOfDoors << endl;

cout << "\nSecond Car Characteristics\n"; cout << "Year: " << Sport.Year << endl;

cout << "Condition: " << Sport.DrivingCondition << endl; cout << "Mileage: cout << "Doors: " << Sport.Mileage << endl; " << Sport.NumberOfDoors << endl;

return 0; } This would produce: First Car Characteristics Year: 2002

Condition: D Mileage: Doors: 28446 5

Second Car Characteristics Year: 1998

Condition: E

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Mileage: Doors: 68208 2

C programmers use another technique of creating classes. It consists of using the typedef keyword, which means you would define a type but set the actual name of the class between the closing curly bracket and the semi-colon. Here is an example of using that technique: #include <iostream> using namespace std;

typedef struct MobileEngine { int Year;

unsigned NumberOfDoors; long char }Car; Mileage; DrivingCondition;

int main() { return 0; } Optionally, you can type a pseudo-name for the class on the first line. Here is an example: #include <iostream> using namespace std;

typedef struct _car { int Year;

unsigned NumberOfDoors; long char } Car; Mileage; DrivingCondition;

int main() {

return 0; } After creating the class, the Car name is a class, not a variable. Therefore, when you want to use the object, you must and can declare an instance of the class using either the _car or the Car name. Here are examples: #include <iostream> using namespace std;

typedef class _car { int Year;

unsigned NumberOfDoors;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
long char } Car; Mileage; DrivingCondition;

int main() { _car vehicle; Car mobile;

return 0; }

References
As done for variables of primitive types, you can create a reference to a class using a declared variable. The same rule applies: the object that is used as a reference must have previously been initialized. Here is an example: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

class Car { public: char char int Make[40]; Model[40]; Year;

unsigned NumberOfDoors; bool long }; HasAirCondition; Mileage;

int main( int argc, char * argv[] ) { Car vehicle = { "Toyota", "4-Runner", 1998, 5, true, 57922 }; Car &SUV = vehicle;

cout << "Car Auctions - Vehicle Characteristics"; cout << "\nYear: " << SUV.Year;

cout << "\nMileage: " << SUV.Mileage; cout << "\nMake: cout << "\nModel: cout << "\nDoors: " << SUV.Make; " << SUV.Model; " << SUV.NumberOfDoors;

cout << "\nHas A/C: " << SUV.HasAirCondition;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return 0; }

Constant Objects
Just as you can create a constant of a built-in data type, you can also create a constant using a composite type. Always remember that the constant refers to a value that doesn't change and the constant value must be initialized with a known or already defined value. Here is an example: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

class Car { public: int Year;

unsigned NumberOfDoors; bool private: char short char public: long }; Mileage; DrivingCondition; TypeOfTransmission; Color; HasAirCondition;

int main( int argc, char * argv[] ) { Car vehicle, sportCar;

vehicle.Mileage = 28446; vehicle.NumberOfDoors = 5; vehicle.Year = 2002;

cout << "Vehicle Characteristics\n"; cout << "Year: cout << "Mileage: cout << "Doors: " << vehicle.Year << endl; " << vehicle.Mileage << endl; " << vehicle.NumberOfDoors << endl;

sportCar.Mileage = 28446; sportCar.Year = 2002;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
const Car mobile = vehicle;

cout << "\nSport Car Characteristics\n"; cout << "Year: cout << "Mileage: " << sportCar.Year << endl; " << sportCar.Mileage << endl;

cout << "\nMobile Characteristics\n"; cout << "Year: cout << "Mileage: cout << "Doors: " << mobile.Year << endl; " << mobile.Mileage << endl; " << mobile.NumberOfDoors << endl;

return 0; } This would produce: Vehicle Characteristics Year: Mileage: Doors: 2002 28446 5

Sport Car Characteristics Year: Mileage: 2002 28446

Mobile Characteristics Year: Mileage: Doors: 2002 28446 5

Unions
Introduction
Like a structure, a union is created from combining other variables. To create a union, use the union keyword following the same syntax applied for a class, like this: union SomeName {}; Like a structure, the members of a union are listed in its body. For example, to create a union that represents a student, you would type: union Student { char FullName[32]; int Age; float AvgGrade; }; Once the union is defined, you can declare it and use its members: #include <iostream> using namespace std;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
union Student { int Age; double AvgGrade; };

int main() { Student Std;

Std.Age = 12; cout << "Student Age = " << Std.Age;

return 0; } This would produce: Student Age = 12

Using a Union
When creating a struct or a class, each variable, treated as its own entity, occupies its assigned amount of space in memory. This is different with unions. All of the members of a union share the same memory space. After declaring a union object, instead of allocating memory for each member variable, the compiler assigns an amount of memory equal to the largest variable. Therefore, if you define a union that would represent a Student object as the above, the compiler would assign the same memory space to all members; and the compiler would find out which member needs the largest space, in this case that would be the double variable because a double variable occupies 8 Bytes. Consequently, a union can store only the value of only (excuse the repetition) one of its members at a time: you cannot simultaneously access the values of all members, at the same time (another repetition). If you initialize all of the members of a union at the same time, the result is unreliable; since all members are using the same memory space, that space cannot accommodate all member values at the same time. The following version of our program produces such an unreliable result: #include <iostream> using namespace std;

union Student { char Gender; int Age; float AvgGrade; double GradeSum; };

int main() { Student Std;

Std.Gender = 'F';

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Std.Age = 14; Std.AvgGrade = 14.50; Std.GradeSum = 210;

cout << "Characteristics of this student"; cout << "\n\tGender = " << Std.Gender; cout << "\n\tAge = " << Std.Age; cout << "\n\tAverage = " << Std.AvgGrade; cout << "\n\tTotal = " << Std.GradeSum;

return 0; } This would produce: Characteristics of this student Gender = Age = 0 Average = 0 Total = 210 As you can see, you should not substitute unions and structures. You should use a union when you can/must store any kind of variable in the same location, when variables sharing the same memory location is not an issue (or a danger). Avoid using unions in highly accessed and intensive value exchanges, such as calculations or data records. A union is usually created inside of another object. Because all members of a union share the same memory location, a union is sometimes used to identify one value to use among many. Consider the following example: #include <iostream> using namespace std;

union HighSchool { int RegistrationStatus;

double Salary; };

int main() { return 0; } In this case, two different, obviously unrelated variables are declared. The idea here is that only one of them would be used in the program, but which one. Imagine that you are starting a program for a high school. If the person whose information is being entered in the application is a student, then you need to specify his or her registration status, the eventual values would specify Registered, Pending, or Excluded. On the other hand, if the person whose information is being entered is a staff member such as a teacher, then the registration status is irrelevant but you may want to enter his or her salary, a piece of information that is irrelevant for a student. This example shows that, for one particular record being created, only one of these two values would be considered and the other would not apply.

Previous

Copyright 1998-2005 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

The Methods of a Class


Member Functions
Introduction
The primary motivation of using classes in a program is to create objects as complete as possible. An object must be able to handle its own business so that the other objects of the program or of another program would only need to know which object can take care of a particular need they have. A regular variable, as a member of an object, cannot handle assignments. This job is handled by particular functions declared as members of a class. A function as a member of a class is also called a Method. On this site, the words method and function, when associated with a class, will refer to the same thing: a member function of the class.

Declaring Member Functions


A member function, also called a method, is declared like any of the functions we have used so far: it could or could not return a value. Here are two examples: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

class Rectangle { public: double Length; double Height;

public: double Perimeter(); double Area(); };

int main( int argc, char * argv[]) { Rectangle rect = { 48.35, 36.94 };

cout << "Rectangle Characteristics"; cout << "\nLength: cout << "\nHeight: " << rect.Length; " << rect.Height;

return 0; } This would produce:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Rectangle Characteristics Length: Height: 48.35 36.94

When using methods on a class, the variables are used to hold or store values, called data, of the object, while member functions are used to perform assignments as related to the class. One way you can control the data held by variables is to hide data from the "external world". To achieve this, you should declare the member variables in a private section. After doing this, use the methods in the public section(s) to help the class interact with the other objects or functions of the program. There are at least two techniques you can use to implement a method member.

Method Implementation
Local Implementation
To implement a method in the class where it is declared, use the same techniques we used to define regular functions. Here is an example: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

struct Integer { int int int { int length; Max; Min; Size()

length = sizeof(int); return length; } bool IsPositive(); bool IsNegative(); };

int main( int argc, char * argv[]) { Integer number;

cout << "Size = " << number.Size() << " bytes"; return 0; } When a method is a class' member, it has access to the member variables of the same class. This means that you don't need to pass the variables as arguments: you can just use any of them as if it were supplied. Here is an example:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

class Rectangle { public: double Length; double Height;

public: double Perimeter() { double p;

p = (Length + Height) * 2; return p; } double Area(); };

int main( int argc, char * argv[] ) { Rectangle rect = { 48.35, 36.94 };

cout << "Rectangle Characteristics"; cout << "\nLength: cout << "\nHeight: " << rect.Length; " << rect.Height;

cout << "\nPerimeter: " << rect.Perimeter();

return 0; } This would produce: Rectangle Characteristics Length: Height: 48.35 36.94

Perimeter: 170.58

Global Implementation
An alternative to local implementation of a method consists of defining it outside of the object. To access a method of a class when implementing it, instead of the member access operator ., you will use the scope resolution operator " ::".

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
To implement a method outside of the class, type the return value of the method, followed by the class' name, followed by the scope resolution operator ::, followed by the method's name, followed by the arguments, if any, between parentheses, and finally define what the function should do, in its body. Here is an example:

#ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

class Rectangle { public: double Length; double Height;

public: double Perimeter() { double p;

p = (Length + Height) * 2; return p; } double Area(); };

double Rectangle::Area() { double a = Height * Length; return a; }

int main( int argc, char * argv[] ) { Rectangle rect = { 48.35, 36.94 };

cout << "Rectangle Characteristics"; cout << "\nLength: cout << "\nHeight: " << rect.Length; " << rect.Height;

cout << "\nPerimeter: " << rect.Perimeter(); cout << "\nArea: " << rect.Area();

return 0; } This would produce:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Rectangle Characteristics Length: Height: 48.35 36.94

Perimeter: 170.58 Area: 1786.05

Inline Methods
When studying functions, we learned that an assignment could be carried where it is being called. Such a function was referred to as inline. The same process can apply to a class member. To declare a class method as inline, precede its name with the inline keyword when declaring the method in the class. Here are examples:

#ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

class Rectangle { public: double Length; double Height;

public: double Perimeter() { double p;

p = (Length + Height) * 2; return p; } inline double Area(); };

inline double Rectangle::Area() { double a = Height * Length; return a; }

int main( int argc, char * argv[] ) { Rectangle rect = { 48.35, 36.94 };

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "Rectangle Characteristics"; cout << "\nLength: cout << "\nHeight: " << rect.Length; " << rect.Height;

cout << "\nPerimeter: " << rect.Perimeter(); cout << "\nArea: " << rect.Area();

return 0; } You can choose which method(s) would be inline and which one(s) would not. When implementing the method, you can precede the method with the inline keyword. You can also omit the inline keyword in the class but use it when defining the method. For example, the following code will work just fine: class Rectangle { public: double Length; double Height;

public: double Perimeter() { double p;

p = (Length + Height) * 2; return p; } double Area(); };

inline double Rectangle::Area() { double a = Height * Length; return a; } If you decide to implement a method locally (in the class), you have the option of implementing it as inline. You can precede it with, or omit, the inline keyword:

class Box { public: inline double CalcVolume() { return Length * Width * Height; } double CalcShoeSize() { return Length - 0.35;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} void Display();

private: double Length; double Width; double Height; string Color; }; On the other hand, if you omit the inline keyword, the C++ compiler would take care of it. Normally, any function implemented in the body of the class is considered inline. Regardless of how the member methods of an object are implemented, any method can call another without using an access operator. This allows an objects methods to exchange information among themselves easily. Furthermore, unlike regular functions where a function must be declared prior to another function calling it, the methods of a class don't follow that rule: one method can call another method before or after the other has been implemented, as long as it is defined somewhere in the program. Consider the following Show() method:

#ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

class Rectangle { public: void Show() { Height = 36.94; Length = 48.35;

cout << "Rectangle Characteristics"; cout << "\nLength: cout << "\nHeight: " << Length; " << Height;

cout << "\nPerimeter: " << Perimeter(); cout << "\nArea: } public: double Length; double Height; " << Area();

public: double Perimeter() { double p;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

p = (Length + Height) * 2; return p; } double Area(); };

inline double Rectangle::Area() { double a = Height * Length; return a; }

int main( int argc, char * argv[] ) { Rectangle rect;

rect.Show(); return 0; }

Static Methods
Besides regular member functions, a class can also have static methods. To create a static method, type the static keyword to its left. Here is an example: class Car { public: string string int Make; Model; Year;

unsigned NumberOfDoors; long public: static int CarsCount; static string ApplicationTitle; static void Show(); }; As mentioned for static member variables, a static method doesn't belong to a particular instance of the class. This means that you don't need to declare a variable of a class in order to access a static method. A static method stands on its own so much that, if you want to access another member of the class, you must declare an instance of that class inside the static method. In other words, the other members of the same class are not automatically accessible from within the static method. Based on this, the above Show() method could be implemented as follows: #ifdef __BORLANDC__ #pragma argsused #endif Mileage;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#include <iostream> using namespace std;

class Car { public: string string int Make; Model; Year;

unsigned NumberOfDoors; long public: static int CarsCount; static string ApplicationTitle; static void Show() { Car vehicle; Mileage;

vehicle.Year

= 2004;

vehicle.Mileage = 24012; vehicle.Make = "Ford";

vehicle.Model = "Crown Victoria"; vehicle.NumberOfDoors = 4;

cout << "\nYear:

" << vehicle.Year;

cout << "\nMileage: " << vehicle.Mileage; cout << "\nMake: cout << "\nModel: cout << "\nDoors: } }; " << vehicle.Make; " << vehicle.Model; " << vehicle.NumberOfDoors;

int Car::CarsCount = 1; string Car::ApplicationTitle = " Four-Corner Car Auctions";

int main( int argc, char * argv[] ) {

cout << Car::ApplicationTitle; cout << "\n - Vehicle Characteristics -"; Car::Show(); cout << "\nCount: " << Car::CarsCount << endl;

return 0; } This would produce:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Four-Corner Car Auctions - Vehicle Characteristics Year: 2004

Mileage: 24012 Make: Model: Doors: Count: Ford Crown Victoria 4 1

Notice that, inside of main(), you don't need a Car object (an instance of the Car class) in order to access the Show() method. Also, as mentioned already, you cannot implicitly access the non-static regular members of the class inside of the static method. For example, the following code will not work: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

class Car { public: string string int Make; Model; Year;

unsigned NumberOfDoors; long public: static int CarsCount; static string ApplicationTitle; static void Show() { cout << "\nYear: " << Year; Mileage;

cout << "\nMileage: " << Mileage; cout << "\nMake: cout << "\nModel: cout << "\nDoors: } }; " << Make; " << Model; " << NumberOfDoors;

int Car::CarsCount = 1; string Car::ApplicationTitle = " Four-Corner Car Auctions";

int main( int argc, char * argv[] ) {

cout << Car::ApplicationTitle; cout << "\n - Vehicle Characteristics -";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Car::Show(); cout << "\nCount: " << Car::CarsCount << endl;

return 0; } As done with the other methods, you can implement a static method outside of the class. If you decide to do this, you must omit the static keyword. Here is an example: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

class Car { public: string string int Make; Model; Year;

unsigned NumberOfDoors; long public: static int CarsCount; static string ApplicationTitle; static void Show(); }; Mileage;

int Car::CarsCount = 1; string Car::ApplicationTitle = " Four-Corner Car Auctions";

void Car::Show() { Car vehicle;

vehicle.Year

= 2004;

vehicle.Mileage = 24012; vehicle.Make = "Ford";

vehicle.Model = "Crown Victoria"; vehicle.NumberOfDoors = 4;

cout << "\nYear:

" << vehicle.Year;

cout << "\nMileage: " << vehicle.Mileage; cout << "\nMake: cout << "\nModel: cout << "\nDoors: " << vehicle.Make; " << vehicle.Model; " << vehicle.NumberOfDoors;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
}

int main( int argc, char * argv[] ) {

cout << Car::ApplicationTitle; cout << "\n - Vehicle Characteristics -"; Car::Show(); cout << "\nCount: " << Car::CarsCount << endl;

return 0; } To access a static member from a static method, you don't have to qualify it: its name would be enough. Consider the following example: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

class Car { public: string string int Make; Model; Year;

unsigned NumberOfDoors; long public: static int CarsCount; static string ApplicationTitle; static void Show(); }; Mileage;

int Car::CarsCount = 1; string Car::ApplicationTitle = " Four-Corner Car Auctions";

void Car::Show() { Car vehicle;

vehicle.Year

= 2004;

vehicle.Mileage = 24012; vehicle.Make = "Ford";

vehicle.Model = "Crown Victoria"; vehicle.NumberOfDoors = 4;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

cout << ApplicationTitle; cout << "\n - Vehicle Characteristics -"; cout << "\nYear: " << vehicle.Year;

cout << "\nMileage: " << vehicle.Mileage; cout << "\nMake: cout << "\nModel: cout << "\nDoors: cout << "\nCount: } " << vehicle.Make; " << vehicle.Model; " << vehicle.NumberOfDoors; " << CarsCount << endl;

int main( int argc, char * argv[] ) { Car::Show();

return 0; } Notice that the only members that are accessed in the static method without being qualified are the static member variables of the same class.

Methods and Arguments


Constant Arguments
In previous lessons, we learned that when a function received an argument that it didn't modify, the argument should be declared as constant. This allows the compiler to make sure that the argument would not be modified. The same technique applies to an argument used by a method of a class. To declare an argument of an objects method as constant, type the const keyword on the left of the arguments data type. Consider a Box object as follows:

We would like to know the area of each side because different things will be displayed on each side and we need to know how much space is available. If we were dealing with a rectangle, we would just declare an area method as follows: double FaceArea(); On a box (rectangular parallelepiped), we have three rectangle types that represent the six faces. We can declare one method that takes any two sides and calculates their area. Such a method would be declared as follows:

double FaceArea(double side1, double side2);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
We can define it as follows:

class Box { public: double FaceArea(double length, double height) { double area = length * height; return area; } }; Notice that the method doesn't modify the values of the arguments it uses. Therefore, they should be declared as constants. To declare each as constant, you would change the declaration of the method as follows: double Area(const double side1, const double side2); Here is an example of a class with methods that take constant arguments:

#ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

class Box { public: double FaceArea(double length, double height) { double area = length * height; return area; } double TopArea(double length, double width) { return length * width; }

double RightArea(double height, double width) { return height * width; } };

int main( int argc, char * argv[] ) { Box sampleBox; const double L = 35.85;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
const double H = 28.46; const double W = 22.08;

cout << " -=- Box Areas -=-"; cout << "\nTop: cout << "\nFace: " << sampleBox.TopArea(L, W); " << sampleBox.FaceArea(L, H);

cout << "\nRight: " << sampleBox.RightArea(H, W);

return 0; } This would produce:

-=- Box Areas -=Top: Face: 791.568 1020.29

Right: 628.397

Constant Methods
Some of the methods of an object, though using member variables of the same object, don't modify them. Consider the following program: #ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

class Box { public: double Length; double Width; double Height; public: double FaceArea() { return Length * Height; } double TopArea() { return Length * Width; }

double RightArea() {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return Height * Width; } };

int main( int argc, char * argv[] ) { Box sampleBox; sampleBox.Length = 35.85; sampleBox.Height = 28.46; sampleBox.Width = 22.08;

cout << " -=- Box Characteristics -=-"; cout << "\nLength: cout << "\nWidth: cout << "\nHeight: cout << "\nTop Area: cout << "\nFace Area: " << sampleBox.Length; " << sampleBox.Width; " << sampleBox.Height; " << sampleBox.TopArea(); " << sampleBox.FaceArea();

cout << "\nRight Area: " << sampleBox.RightArea();

return 0; } Notice that the methods that calculate the areas don't modify the values of the member variables they are using. If a method doesn't modify the member variables of its class, the method should be declared and implemented as constant. To declare a method as a constant, add the const keyword to the right side of the method when declaring and when implementing it. Here are examples:

#ifdef __BORLANDC__ #pragma argsused #endif

#include <iostream> using namespace std;

class Box { public: double Length; double Width; double Height; public: double FaceArea() const; double TopArea() const { return Length * Width; }

double RightArea() const

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ return Height * Width; } };

double Box::FaceArea() const { return Length * Height; }

int main( int argc, char * argv[] ) { Box sampleBox; sampleBox.Length = 35.85; sampleBox.Height = 28.46; sampleBox.Width = 22.08;

cout << " -=- Box Characteristics -=-"; cout << "\nLength: cout << "\nWidth: cout << "\nHeight: cout << "\nTop Area: cout << "\nFace Area: " << sampleBox.Length; " << sampleBox.Width; " << sampleBox.Height; " << sampleBox.TopArea(); " << sampleBox.FaceArea();

cout << "\nRight Area: " << sampleBox.RightArea();

return 0; } If you decide to define constant methods locally (inline), the only difference is to remove the semi-colon of the end of the declaration and define the method normally. You can also reinforce the constancy of the methods by starting them with the const keyword. The program would still produce the same result.

Private Methods
At this time, we know that one of the responsibilities of a member method of an object is to carry assignments. Another job performed by methods is to communicate with the clients of an object. As you might have found out, some of the methods of an object are exclusively used to carry assignments. The external functions or other objects don't call such methods and don't communicate with them. If you create a class and know that a particular method is not used to transfer data to the client methods, you can declare such a method as private, just like you would do with a member variable. To declare a method as private, include it in the private section of the object. To implement it, follow the same rules we have learned about implementing the methods of an object. The biggest difference you must keep in mind (which will also be very important when we learn about inheritance) is that this function method is not available to the outside world. Here is an example:

#ifdef __BORLANDC__ #pragma argsused

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#endif

#include <iostream> using namespace std;

class Box { public: double Length; double Width; double Height; private: const double FaceArea() const; const double TopArea() const { return Length * Width; }

const double RightArea() const { return Height * Width; }

public: void Show() { cout << "\nLength: cout << "\nWidth: cout << "\nHeight: cout << "\nTop Area: cout << "\nFace Area: " << Length; " << Width; " << Height; " << TopArea(); " << FaceArea();

cout << "\nRight Area: " << RightArea(); } };

const double Box::FaceArea() const { return Length * Height; }

int main( int argc, char * argv[] ) { Box sampleBox; sampleBox.Length = 35.85; sampleBox.Height = 28.46; sampleBox.Width = 22.08;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << " -=- Box Characteristics -=-"; sampleBox.Show();

return 0; }

C++ Project Files and Classes


Introduction
An object is made of the material that composes it and the actual structure of the object, which defines how the object is built and used. This means that a class is made of two parts: its building block and its definition. These two parts of a class can be kept in different files that have access to each other.

Class' Header File


The building block or foundation of an class is made of the class' creation, listing all of its members. This foundation can be created in a file called a header file, similar to the one we learned when studying functions. The name of the file follows the naming rules we have applied so far. The header file has an extension of .h. You create an objects header file the same we did when studying functions. To create the header file, you can just define the class as an object. If some of the members are defined in files outsde of the object, include their header file(s). Here is what our Box header file would look like:

//--------------------------------------------------------------------------// Box.h //--------------------------------------------------------------------------#if !defined(Box_H) #define Box_H

class Box { public: double Length; double Width; double Height; private: const double FaceArea() const; const double TopArea() const; const double RightArea() const;

public: void Show(); };

#endif // Box_H

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Class Source Code


The file used to implement the class is called a source file. It can be used to define the assignments of the class. A source file should at least start with a line that specifies the name of the header file that it is implementing. Since this file is usually created in the same project, it is specified with an include line that encloses the file name with double-quotes. An example would be: #include "Book.h" The main area of the file is made of the class' implementation. Here is what the source file of our Box would look like:

//--------------------------------------------------------------------------// Unit1.cpp //---------------------------------------------------------------------------

#include <iostream> #include "box.h"

using namespace std;

const double Box::FaceArea() const { return Length * Height; }

const double Box::TopArea() const { return Length * Width; }

const double Box::RightArea() const { return Height * Width; }

void Box::Show() { cout << "\nLength: cout << "\nWidth: cout << "\nHeight: cout << "\nTop Area: cout << "\nFace Area: " << Length; " << Width; " << Height; " << TopArea(); " << FaceArea();

cout << "\nRight Area: " << RightArea(); } The main() function of our box project is reduced to simply calling the appropriate Box method member:

#ifdef __BORLANDC__

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#pragma argsused #endif

#include <iostream> #include "box.h"

using namespace std;

int main( int argc, char * argv[] ) { Box sampleBox; sampleBox.Length = 35.85; sampleBox.Height = 28.46; sampleBox.Width = 22.08;

cout << " -=- Box Characteristics -=-"; sampleBox.Show();

return 0; }

Previous

Copyright 2000-2005 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Object Construction and Destruction


Constructors
Method Initializer
In order to further customize the behavior of an object, you should make sure that it completely controls its member variables. An object should "know" what kind of values its variables hold and what values are not acceptable. As a starting point, when calling an object from another function, you should know what value a particular member is holding, before performing any operation. To solve this problem, one solution is to provide a special function that would initialize the member variables.
A method that initializes can return any value but it is preferable to return a void because its primary purpose is to reset the values. Since this method would give a starting value to all member variables that need to be initialized, it should have an equivalent argument for each of the member variables that it would initialize. Consider an object used to handle a brick; a rectangular parallelepiped is recognized by its length, height, and width. A method used to initialize its dimensions would look like this:

//-------------------------------------------------------------------------#include <iostream> using namespace std; struct TBrick { public: void Initializer(double l, double h, double w); double Volume() const; void Properties() const; private: double Length; double Height; double Width; }; //-------------------------------------------------------------------------void TBrick::Initializer(double l, double h, double w) { Length = l; Height = h; Width = w; } //-------------------------------------------------------------------------double TBrick::Volume() const { return Length * Height * Width; } //-------------------------------------------------------------------------void { cout << "Red Brick Properties"; cout << setiosflags(ios::fixed) << setprecision(2); TBrick::Properties() const

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\nLength = " << Length; cout << "\nHeight = " << Height; cout << "\nThickness = " << Width; cout << "\nVolume = " << Volume() << "\n"; } //-------------------------------------------------------------------------int main() { TBrick RedBrick;

RedBrick.Initializer(124.45, 56.25, 32.55); RedBrick.Properties();

return 0; } //-------------------------------------------------------------------------This would produce:

Red Brick Properties Length = 124.45 Height = 56.25 Thickness = 32.55 Volume = 227860.17

Press any key to continue...


Once declared and implemented, a method initializer can be used as the "entry point" to the object; for example, it can be used to pass values from the external world to the member variables of an object. In the following example, the user supplies the dimensions of the brick. Since the dimensions are held by private members, their values will be carried from the outside by the method used to initialize:

//-------------------------------------------------------------------------int main() { double length, height, width; TBrick GoneSand;

cout << "Before building this brick, provide its dimensions\n"; cout << "Length: "; cin >> length; cout << "Height: "; cin >> height; cout << "Width: cin >> width; cout << endl; ";

GoneSand.Initializer(length, height, width); GoneSand.Properties();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return 0; } //-------------------------------------------------------------------------An example of running the program would produce:

Before building this brick, provide its dimensions Length: 8.95 Height: 6.85 Width: 6.25

Red Brick Properties Length Height = 8.95 = 6.85

Thickness = 6.25 Volume = 383.17

Press any key to continue...

Initializing an Object
1. To create a new project, on the main menu, click File -> New or File -> New -> Other... 2. On the New Items dialog box, double-click Console Wizard. 3. On the Console Wizard dialog box, make sure the C++ radio button is selected. In the right section, click only the Console Application check box and click OK. 4. To save the project, on the Standard toolbar, click the Save All button. 5. Click the Create New Folder button, type Students2 and press Enter twice to put the new folder name in the Save In combo box. 6. Change the File Name content to Main and press Enter. 7. For the name of the project, type Student and press Enter. 8. To add a new unit, on the main menu, click File -> New or File -> New -> Other... 9. In the New Items dialog box, double-click Unit. 10. To save the unit, on the Standard toolbar, click the Save button. 11. Type Students as the unit name and press Enter. 12. Click the Students.h tab and change its content as follows: //-------------------------------------------------------------------------#ifndef StudentsH #define StudentsH #include <string> using namespace std; //-------------------------------------------------------------------------class TStudent { public: void InitialValues(string fn, string ln, int DOB, int MOB, int YOB); void private: string FirstName; string LastName; Display();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
int DayOfBirth; int MonthOfBirth; int YearOfBirth; }; //-------------------------------------------------------------------------#endif 13. Click the Students.cpp file and change it as follows: //-------------------------------------------------------------------------#include <iostream> using namespace std;

#include "Students.h" //--------------------------------------------------------------------------

void

TStudent::InitialValues(string fn, string ln, int DOB, int MOB, int YOB)

{ FirstName LastName DayOfBirth = fn; = ln; = DOB;

MonthOfBirth = MOB; YearOfBirth } //-------------------------------------------------------------------------void { // Display the characteristics of the student cout << "Characteristics of this student"; cout << "\nFull Name: " << FirstName << " " << LastName; cout << "\nDate of Birth: " << DayOfBirth << "/" << MonthOfBirth << "/" << YearOfBirth << "\n"; } //-------------------------------------------------------------------------14. Click the Main.cpp file and change it as follows: //-------------------------------------------------------------------------#include <iostream> using namespace std; #include "Students.h" //-------------------------------------------------------------------------TStudent::Display() = YOB;

void {

Exit()

cout << "\n\nPress any key to continue...";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} //-------------------------------------------------------------------------int main() { TStudent FirstGrade;

FirstGrade.InitialValues("Jules", "Senga", 1, 1, 1990); FirstGrade.Display();

Exit(); return 0; } //-------------------------------------------------------------------------15. Press F9 to test the program.

Default Constructor
As we have already seen, an object combines methods and variables grouped to accomplish a particular purpose. A constructor is a special method that is created when the object is created or defined. This particular method holds the same name as that of the object and it initializes the instance of the object whenever that object is created. The constructor also usually holds the initializations of the different declared member variables of its object. Unlike some of the other methods, the constructor does not return a value, not even void. When you create an object, if you do not declare a constructor, the compiler would create one for your program; this is useful because it lets all other objects and functions of the program know that this object exists. This compiler created constructor is called the default constructor. If you want to declare your own constructor, simply add a method with the same name as the object in the public section of the object. When you declare an instance of an object, whether you use that object or not, a constructor for the object is created and signals itself. A constructor is declared without a return value, that also excludes void. Therefore, when implemented, do not return a value:

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

struct TBook { public: TBook(); }; //-------------------------------------------------------------------------TBook::TBook() { cout << "I see a book...\n"; } //-------------------------------------------------------------------------int main() { TBook B; // Constructor

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return 0; } //-------------------------------------------------------------------------This would produce: I see a book... This book constructor is a programmer created constructor and is empty. You might find it sometimes convenient to create your own constructor because, whether you create an empty constructor or not, this does not negatively impact your program but makes it more lively and allows other parts of the program to conveniently call the object using its constructor. A constructor is easily implemented once you have created one: There are various categories of bricks used in the construction industry. For this exercise, we will consider a simple one used in constructing domestic building foundations. It has a total length, here called Length; it also has a height, referred here to as Height; and it has a thickness that will be called Thickness. For resistance and static reasons, our brick will have two holes. Since we are more interested in the amount of cement used to create the brick, we will subtract the volume of the hole from the total volume. The dimensions we use are for simplicity. We will consider that the small wall of the brick has a thickness of 0.25; also, the static wall in the middle length has a thickness of 0.25. Listing - Brick Unit - Header File: Bricks.h

//-------------------------------------------------------------------------#ifndef BricksH #define BricksH

//-------------------------------------------------------------------------struct TBrick { public: TBrick(); // Empty Constructor void void double void private: double Length; double Height; double Thickness; }; //-------------------------------------------------------------------------#endif
Brick Unit - Source File: Bricks.cpp

setDimensions(double l, double h, double t); Initializer(double l, double h, double w); CementVolume(); ShowProperties();

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

#include "Bricks.h"

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

//-------------------------------------------------------------------------TBrick::TBrick()

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ //TODO: Add your source code here } //-------------------------------------------------------------------------void { Length = l; Height = h; Thickness = t; } //-------------------------------------------------------------------------double { double Enclosure = 0.50; // This includes both walls of the brick itself double HoleLength = Length - 0.75; // Including both holes double HoleThickness = Thickness - Enclosure; double HoleVolume = HoleLength * HoleThickness * Height; double TotalVolume = Length * Height * Thickness; double ValidVolume = TotalVolume - HoleVolume; TBrick::CementVolume() TBrick::setDimensions(double l, double h, double t)

return ValidVolume; } //-------------------------------------------------------------------------void { cout << "Foundation Brick Properties"; cout << setiosflags(ios::fixed) << setprecision(2); cout << "\nLength << "\nHeight = " << Length; cout = " << Height; TBrick::ShowProperties()

cout << "\nThickness = " << Thickness; cout << "\nCement Volume = " << CementVolume() << "\n"; }//-------------------------------------------------------------------------Main File: Main.cpp

//-------------------------------------------------------------------------#include <iostream> using namespace std; #include "Bricks.h" //--------------------------------------------------------------------------

//-------------------------------------------------------------------------int main() { TBrick Foundation;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Foundation.setDimensions(4.24, 3.55, 3.45); Foundation.ShowProperties();

return 0; } //-------------------------------------------------------------------------This program would produce:

Foundation Brick Properties Length Height = 4.24 = 3.55

Thickness = 3.45 Cement Volume = 15.38

Press any key to continue...

Using the Default Constructor


1. Access the Students.h file and change it as follows: //-------------------------------------------------------------------------#ifndef StudentsH #define StudentsH #include <string> using namespace std; //-------------------------------------------------------------------------class TStudent { public: TStudent(); void InitialValues(string fn, string ln, int DOB, int MOB, int YOB); void private: string FirstName; string LastName; int DayOfBirth; int MonthOfBirth; int YearOfBirth; }; //-------------------------------------------------------------------------#endif 2. Change the Students.cpp file accordingly: //-------------------------------------------------------------------------#include <iostream> Display();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
using namespace std;

#include "Students.h" //--------------------------------------------------------------------------

//-------------------------------------------------------------------------TStudent::STudent() { } //-------------------------------------------------------------------------void TStudent::InitialValues(string fn, string ln, int DOB, int MOB, int YOB) { FirstName LastName DayOfBirth = fn; = ln; = DOB;

MonthOfBirth = MOB; YearOfBirth } //-------------------------------------------------------------------------void { // Display the characteristics of the student cout << "Characteristics of this student"; cout << "\nFull Name: " << FirstName << " " << LastName; cout << "\nDate of Birth: " << DayOfBirth << "/" << MonthOfBirth << "/" << YearOfBirth << "\n"; } //-------------------------------------------------------------------------3. Press F9 to test the program. TStudent::Display() = YOB;

The Constructor Initializer


A constructor does not exist simply for cosmetic reasons. It can be used to initialize the member variables of an object. Therefore, a constructor provides a valuable alternative to a method initializer, the type of method we saw earlier. To use a constructor to initialize the member variables of an object, provide as arguments the necessary variables that you intend to initialize. You do not have to initialize all member variables in the constructor, only those that need to be initialized. In fact, you should initialize only those members that you think the other objects or functions would need to provide when calling this object; this means that your object may have member variables that, either the external objects or functions do not need to modify (or access) or the member variable will be initialized later when called from the needed object or function. To initialize the members of our Brick object, its method constructor would be declared as in the following file: Listing - Brick Unit - Header File: Bricks.h

//-------------------------------------------------------------------------#ifndef BricksH #define BricksH

//-------------------------------------------------------------------------struct TBrick

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ public: TBrick(); // Default Constructor

TBrick(double l, double h, double t); double void private: double Length; double Height; double Thickness; }; //-------------------------------------------------------------------------#endif
Listing - Brick Unit - Source File: Bricks.cpp

CementVolume(); ShowProperties();

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

#include "Bricks.h"

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

//-------------------------------------------------------------------------TBrick::TBrick() { //TODO: Add your source code here } //-------------------------------------------------------------------------TBrick::TBrick(double l, double h, double t) { Length = l; Height = h; Thickness = t; } //-------------------------------------------------------------------------double { double Enclosure = 0.50; // This includes both walls of the brick itself double HoleLength = Length - 0.75; // Including both holes double HoleThickness = Thickness - Enclosure; double HoleVolume = HoleLength * HoleThickness * Height; double TotalVolume = Length * Height * Thickness; double ValidVolume = TotalVolume - HoleVolume; TBrick::CementVolume()

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

return ValidVolume; } //-------------------------------------------------------------------------void { cout << "Foundation Brick Properties"; cout << setiosflags(ios::fixed) << setprecision(2); cout << "\nLength << "\nHeight = " << Length; cout = " << Height; TBrick::ShowProperties()

cout << "\nThickness = " << Thickness; cout << "\nCement Volume = " << CementVolume() << "\n"; } //-------------------------------------------------------------------------Main File: Main.cpp

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

#include <iostream> using namespace std; #include "Bricks.h" //--------------------------------------------------------------------------

//-------------------------------------------------------------------------int main() { TBrick Solid(4.15, 3.35, 3.05); Solid.ShowProperties();

return 0; } //-------------------------------------------------------------------------This would produce the following result:

Foundation Brick Properties Length Height = 4.15 = 3.35

Thickness = 3.05 Cement Volume = 13.36

Press any key to continue...


To safeguard and protect the member variables of an object, we have learned to use set and get methods. If you use set methods to protect the variables of an object, you can conveniently call these methods from the constructor to initialize those member variables. Therefore, a constructor can also be used to call methods that hold the initial values of member variables. At this time, we have learned that a constructor is mainly used to set the initial values of necessary member variables. When using set methods, our Brick object would be changed as follows: Brick Unit - Header File: Bricks.h

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//-------------------------------------------------------------------------#ifndef BricksH #define BricksH

//-------------------------------------------------------------------------struct TBrick { public: TBrick(); // Default Constructor

TBrick(double l, double h, double t); void void void double void private: double Length; double Height; double Thickness; }; //-------------------------------------------------------------------------#endif
Brick Unit - Source File: Brick.cpp

setLength(double l); setHeight(double h); setThickness(double t); CementVolume(); ShowProperties();

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

#include "Bricks.h"

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

//-------------------------------------------------------------------------TBrick::TBrick() { //TODO: Add your source code here } //-------------------------------------------------------------------------TBrick::TBrick(double l, double h, double t) { setLength(l); setHeight(h); setThickness(t); }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//-------------------------------------------------------------------------void { Length = l; } //-------------------------------------------------------------------------void { Height = h; } //-------------------------------------------------------------------------void { Thickness = t; } //-------------------------------------------------------------------------double { double Enclosure = 0.50; // This includes both walls of the brick itself double HoleLength = Length - 0.75; // Including both holes double HoleThickness = Thickness - Enclosure; double HoleVolume = HoleLength * HoleThickness * Height; double TotalVolume = Length * Height * Thickness; double ValidVolume = TotalVolume - HoleVolume; TBrick::CementVolume() TBrick::setThickness(double t) TBrick::setHeight(double h) TBrick::setLength(double l)

return ValidVolume; } //-------------------------------------------------------------------------void { cout << "Foundation Brick Properties"; cout << setiosflags(ios::fixed) << setprecision(2); cout << "\nLength << "\nHeight = " << Length; cout = " << Height; TBrick::ShowProperties()

cout << "\nThickness = " << Thickness; cout << "\nCement Volume = " << CementVolume() << "\n"; } //-------------------------------------------------------------------------Main File: Main.cpp

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

#include <iostream> using namespace std;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#include "Bricks.h" //--------------------------------------------------------------------------

//-------------------------------------------------------------------------int main() { TBrick Solid(4.15, 3.35, 3.05); Solid.ShowProperties();

return 0; } //-------------------------------------------------------------------------This would produce:

Foundation Brick Properties Length Height = 4.15 = 3.35

Thickness = 3.05 Cement Volume = 13.36

Press any key to continue...

Initializing With the Constructor


1. Add a constructor to the Students object as follows: //-------------------------------------------------------------------------#ifndef StudentsH #define StudentsH #include <iostream> //-------------------------------------------------------------------------class TStudent { public: TStudent(string fn, string ln, int DOB, int MOB, int YOB); void private: string FirstName; string LastName; int DayOfBirth; int MonthOfBirth; int YearOfBirth; }; //-------------------------------------------------------------------------#endif Display();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
2. Change the Students.cpp file: //--------------------------------------------------------------------------

using namespace std;

#include "Students.h" //--------------------------------------------------------------------------

//-------------------------------------------------------------------------TStudent::TStudent(string fn, string ln, int DOB, int MOB, int YOB) { FirstName LastName DayOfBirth = fn; = ln; = DOB;

MonthOfBirth = MOB; YearOfBirth } //-------------------------------------------------------------------------void { // Display the characteristics of the student cout << "Characteristics of this student"; cout << "\nFull Name: " << FirstName << " " << LastName; cout << "\nDate of Birth: " << DayOfBirth << "/" << MonthOfBirth << "/" << YearOfBirth << "\n"; } //-------------------------------------------------------------------------3. Finally, change the main(): //-------------------------------------------------------------------------#include <iostream> using namespace std; #include "Students.h" //-------------------------------------------------------------------------TStudent::Display() = YOB;

void {

Exit()

cout << "\n\nPress any key to continue...";

} //-------------------------------------------------------------------------int main() {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
TStudent SecondGrade("Paul", "Waller", 12, 10, 1988); SecondGrade.Display();

Exit(); return 0; } //-------------------------------------------------------------------------4. Press F9 to test the program: Characteristics of this student Full Name: John Doe Date of Birth: 1/1/1990Press any key to continue... 5. Return to your programming environment.

Constructor Overloading
Like an ordinary method, a construction can be overloaded. This means that you can have different constructors following the rules of overloading a function. Since we saw that a constructor can be used to initialize the member variables of its object, you can use multiple constructors to apply different initializations. If you declare a constructor as TBrick Foundation; you can use it to call other method members of the same object. The problem is that if you just try to call a method that displays the values of the member variables, you will get bizarre and unpredictable results. Consider the TBrick object created as

//-------------------------------------------------------------------------struct TBrick { public: TBrick(); double void private: double Length; double Height; double Thickness; }; //-------------------------------------------------------------------------And implemented as

CementVolume(); ShowProperties();

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

#include "Bricks.h" //--------------------------------------------------------------------------

TBrick::TBrick() { //TODO: Add your source code here } //-------------------------------------------------------------------------double TBrick::CementVolume()

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ double Enclosure = 0.50; // This includes both walls of the brick itself double HoleLength = Length - 0.75; // Including both holes double double HoleThickness = Thickness - Enclosure; double HoleVolume = HoleLength * HoleThickness * Height; double TotalVolume = Length * Height * Thickness; double ValidVolume = TotalVolume - HoleVolume;

return ValidVolume; } //-------------------------------------------------------------------------void { cout << "Foundation Brick Properties"; cout << "\nLength = " << Length; cout << "\nHeight = " << Height; cout << "\nThickness = " << Thickness; cout << "\nCement Volume = " << CementVolume() << "\n"; } //-------------------------------------------------------------------------If you declare the TBrick object using the default constructor, and decide to call a method that displays the variables values, you could write it like this:

TBrick::ShowProperties()

//-------------------------------------------------------------------------#include <iostream> using namespace std; #include "Bricks.h" //--------------------------------------------------------------------------

int main() { TBrick Mango;

Mango.ShowProperties();

return 0; } //-------------------------------------------------------------------------This would produce the following result:

Foundation Brick Properties Length = nan Height = 2.53988e-314 Thickness = 2.122e-314 Cement Volume = nan

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Press any key to continue...
As you can see, these values do not make sense to us. To make sure that a calling function does not have to supply values for the member variables, you can also use the empty constructor to supply default values to these variables. If you simply use the default constructor to get the values of the member variables, the object would use the values given in the empty constructor and perform all necessary operations:

TBrick::TBrick() { Length = 4.15; Height = 3.55; Thickness = 3.75; }


This time, the same program would produce a sound result:

Foundation Brick Properties Length = 4.15 Height = 3.55 Thickness = 3.75 Cement Volume = 16.0194

Press any key to continue...


This technique of using the default constructor allows you to conveniently supply default values for the member variables. As flexible as this is, you can use a certain constructor to initialize just one of the member variables and supply default values for the others. When constructing a brick, one of the dimensions would be of primary importance because it influences what the brick is used for. On this exercise, let's allow a calling function to supply the length of the brick while we control the other two dimensions. We can declare more than one constructor in the header file: Brick Unit - Header File: Brick.h

//-------------------------------------------------------------------------#ifndef BricksH #define BricksH

//-------------------------------------------------------------------------class TBrick { public: TBrick(); TBrick(double L); double void private: double Length; double Height; double Thickness; }; //-------------------------------------------------------------------------#endif
Brick Unit - Source File: Brick.cpp

CementVolume(); ShowProperties();

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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#include "Bricks.h" //--------------------------------------------------------------------------

TBrick::TBrick() { Length = 4.15; Height = 3.55; Thickness = 3.75; } //-------------------------------------------------------------------------TBrick::TBrick(double L) { Length = L; Height = 5.25; Thickness = 4.55; } //-------------------------------------------------------------------------double { ... } //-------------------------------------------------------------------------void { ... } //-------------------------------------------------------------------------Since this constructor takes one argument, when declaring an object that would use this constructor, assign only one value to the argument variable. Such a value is provided in the parentheses allocated to the instance of the object. Here is an example: Main File: Main.cpp

TBrick::CementVolume()

TBrick::ShowProperties()

//-------------------------------------------------------------------------#include <iostream> using namespace std; #include "Bricks.h" //--------------------------------------------------------------------------

int main() { // Brick with default dimensions TBrick Mather; Mather.ShowProperties(); cout << endl;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
// Brick with a supplied length TBrick BedTimer(5.55); BedTimer.ShowProperties();

return 0; } //-------------------------------------------------------------------------This would produce the following result:

Foundation Brick Properties Length = 4.15 Height = 3.55 Thickness = 3.75 Cement Volume = 16.0194

Foundation Brick Properties Length = 5.55 Height = 5.25 Thickness = 4.55 Cement Volume = 30.5156

Press any key to continue...


If you declare different constructors with different arguments to initialize (remember the rules of function overloading), when declaring these objects, make sure you initialize each instance with the right number of arguments; otherwise, the compiler would complain. Here is our program that makes use of three constructors, each with different arguments: Brick Unit - Header File: Brick.h

//-------------------------------------------------------------------------#ifndef BricksH #define BricksH

//-------------------------------------------------------------------------class TBrick { public: TBrick(); TBrick(double L); TBrick(double L, double h, double t); double void private: double Length; double Height; double Thickness; }; //-------------------------------------------------------------------------CementVolume(); ShowProperties();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#endif
The new constructor can be implemented as follows:

//-------------------------------------------------------------------------TBrick::TBrick(double L, double h, double t) { Length = L; Height = h; Thickness = t; }//-------------------------------------------------------------------------Main File: Main.cpp

//-------------------------------------------------------------------------#include <iostream> using namespace std; #include "Bricks.h" //--------------------------------------------------------------------------

int main() { // Brick with default dimensions TBrick GrayMatte; GrayMatte.ShowProperties(); cout << endl;

// Brick with a supplied length TBrick OldTimer(5.55); OldTimer.ShowProperties(); cout << endl;

// A Brick with set dimensions TBrick Fantasma(3.25, 3.05, 3.25); Fantasma.ShowProperties();

return 0; } //-------------------------------------------------------------------------This would produce:

Foundation Brick Properties Length = 4.15 Height = 3.55 Thickness = 3.75 Cement Volume = 16.0194

Foundation Brick Properties Length = 5.55

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Height = 5.25 Thickness = 4.55 Cement Volume = 30.5156

Foundation Brick Properties Length = 3.25 Height = 3.05 Thickness = 3.25 Cement Volume = 11.2469

Press any key to continue...


If you create an object and create it with only one constructor, if you create this constructor with at least one argument, the default constructor would not be available anymore. For example if you create a TBrick object as follows:

//-------------------------------------------------------------------------#ifndef BricksH #define BricksH

//-------------------------------------------------------------------------class TBrick { public: TBrick(double L, double h, double t); double void private: double Length; double Height; double Thickness; }; //-------------------------------------------------------------------------#endif
and implement the TBrick(double L, double h, double t) constructor as we saw above, the following main() function would halt the program:

CementVolume(); ShowProperties();

//-------------------------------------------------------------------------#include <iostream> using namespace std; #include "Bricks.h" //--------------------------------------------------------------------------

int main() { // The following (default) constructor is not available TBrick GrayMatte; GrayMatte.ShowProperties(); cout << endl;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
// A Brick with set dimensions TBrick Fantasma(3.25, 3.05, 3.25); Fantasma.ShowProperties();

return 0; } //-------------------------------------------------------------------------Therefore, if you want to access a default constructor of an object, you have two alternatives:

If you don't create any constructor at all on an object, the default constructor would always be available whenever you invoke that object. If you create at least one constructor on an object and supply at least one argument to that constructor, you must explicitly create a default constructor for your object.
Based on what we have learned already, here is our complete program with set and get methods. Brick Unit - Header File: Brick.h

//-------------------------------------------------------------------------#ifndef BricksH #define BricksH

//-------------------------------------------------------------------------class TBrick { public: TBrick(); TBrick(double L); TBrick(double L, double h, double t); double void double void double void double void private: double Length; double Height; double Thickness; }; //-------------------------------------------------------------------------#endif
Brick Unit - Source File: Brick.cpp

getLength() const; setLength(const double l); getHeight() const; setHeight(const double h); getThickness() const; setThickness(const double t); CementVolume(); ShowProperties();

//-------------------------------------------------------------------------#include <iostream> #include <iomanip>

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
using namespace std;

#include "Bricks.h" //--------------------------------------------------------------------------

TBrick::TBrick() { Length = 4.15; Height = 3.55; Thickness = 3.75; } //-------------------------------------------------------------------------TBrick::TBrick(double L) { Length = L; Height = 5.25; Thickness = 4.55; } //-------------------------------------------------------------------------TBrick::TBrick(double L, double h, double t) { Length = L; Height = h; Thickness = t; } //-------------------------------------------------------------------------double { return Length; } //-------------------------------------------------------------------------void { Length = l; } //-------------------------------------------------------------------------double { return Height; } //-------------------------------------------------------------------------void { Height = h; TBrick::setHeight(const double h) TBrick::getHeight() const TBrick::setLength(const double l) TBrick::getLength() const

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} //-------------------------------------------------------------------------double { return Thickness; } //-------------------------------------------------------------------------void { Thickness = t; } //-------------------------------------------------------------------------double { double Enclosure = 0.50; // This includes both walls of the brick itself double HoleLength = Length - 0.75; // Including both holes double double HoleThickness = Thickness - Enclosure; double HoleVolume = HoleLength * HoleThickness * Height; double TotalVolume = Length * Height * Thickness; double ValidVolume = TotalVolume - HoleVolume; TBrick::CementVolume() TBrick::setThickness(const double t) TBrick::getThickness() const

return ValidVolume; } //-------------------------------------------------------------------------void { cout << "Foundation Brick Properties"; cout << setiosflags(ios::fixed) << setprecision(2); cout << "\nLength = " << Length; cout << "\nHeight = " << Height; cout << "\nThickness = " << Thickness; cout << "\nCement Volume = " << CementVolume() << "\n"; } //-------------------------------------------------------------------------Main File: Main.cpp

TBrick::ShowProperties()

//-------------------------------------------------------------------------#include <iostream> using namespace std; #include "Bricks.h" //--------------------------------------------------------------------------

int main() {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
// Brick with default dimensions TBrick GrayMatte; GrayMatte.ShowProperties(); cout << endl;

// Brick with a supplied length TBrick OldTimer(5.55); OldTimer.ShowProperties(); cout << endl;

// A Brick with user supplied dimensions double len, hgt, thk; cout << "\nEnter the dimensions of the brick\n"; cout << "Length: "; cin >> len; cout << "Height: "; cin >> hgt; cout << "Thickness: "; cin >> thk; cout << endl; TBrick Fantasma(len, hgt, thk); Fantasma.ShowProperties();

return 0; } //-------------------------------------------------------------------------Here is an example of running the program:

Foundation Brick Properties Length = 4.15 Height = 3.55 Thickness = 3.75 Cement Volume = 16.02

Foundation Brick Properties Length = 5.55 Height = 5.25 Thickness = 4.55 Cement Volume = 30.52

Enter the dimensions of the brick Length: 6.25 Height: 5.85 Thickness: 4.55

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Foundation Brick Properties Length = 6.25 Height = 5.85 Thickness = 4.55 Cement Volume = 36.05

Press any key to continue...

Overloading the Constructor


1. To use an empty constructor that initializes the member variables, change the Students.h file as follows: //-------------------------------------------------------------------------#ifndef StudentsH #define StudentsH #include <iostream> //-------------------------------------------------------------------------class TStudent { public: TStudent(); TStudent(string fn, string ln, int DOB, int MOB, int YOB); void private: string FirstName; string LastName; int DayOfBirth; int MonthOfBirth; int YearOfBirth; }; //-------------------------------------------------------------------------#endif 2. Implement the new constructor in the Student.cpp file as follows: //-------------------------------------------------------------------------_fastcall TStudent::TStudent() { FirstName LastName DayOfBirth = "Paul"; = "Kamus"; = 28; Display();

MonthOfBirth = 5; YearOfBirth } //-------------------------------------------------------------------------3. To test both constructors, change the main() function as follows: = 1986;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//-------------------------------------------------------------------------#include <iostream> using namespace std; #include "Students.h" //--------------------------------------------------------------------------

void {

Exit()

cout << "\n\nPress any key to continue...";

} //-------------------------------------------------------------------------int main() { TStudent SampleStudent; SampleStudent.Display(); cout << endl;

TStudent Complete("Alexander", "Biyidi", 30, 4, 1988); Complete.Display();

Exit(); return 0; } //-------------------------------------------------------------------------4. To test the program, press F9: Characteristics of this student Full Name: Paul Kamus Date of Birth: 28/5/1986

Characteristics of this student Full Name: Alexander Biyidi Date of Birth: 30/4/1988

Press any key to continue... 5. Return to your programming environment. 6. Now, we will use two more constructors. One of the constructors will initialize only the name of the student. Another constructor will set default values for the date of birth. Both constructors use the same technique but accomplish different purposes. Therefore, change the TStudent class as follows: //-------------------------------------------------------------------------#ifndef StudentsH #define StudentsH #include <iostream> //-------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
-------class TStudent { public: TStudent(); // Default Constructor

TStudent(string F, string L); // Name Initializer TStudent(int DOB, int MOB, int YOB); // Initial Date of birth TStudent(string fn, string ln, int DOB, int MOB, int YOB); // Complete Constructor void private: string FirstName; string LastName; int DayOfBirth; int MonthOfBirth; int YearOfBirth; }; //-------------------------------------------------------------------------#endif 7. Implement the constructors in the Students.cpp file as follows: //-------------------------------------------------------------------------Display();

using namespace std;

#include "Students.h" //--------------------------------------------------------------------------

//-------------------------------------------------------------------------_fastcall TStudent::TStudent() { FirstName LastName DayOfBirth = "John"; = "Doe"; = 1;

MonthOfBirth = 1; YearOfBirth } //-------------------------------------------------------------------------TStudent::TStudent(string FN, string LN) { FirstName LastName DayOfBirth = FN; = LN; = 1; = 1990;

MonthOfBirth = 1; YearOfBirth } = 1985;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//-------------------------------------------------------------------------TStudent::TStudent(int DOB, int MOB, int YOB) { FirstName LastName DayOfBirth = "William"; = "Smith"; = DOB;

MonthOfBirth = MOB; YearOfBirth } //-------------------------------------------------------------------------TStudent::TStudent(string fn, string ln, int DOB, int MOB, int YOB) { FirstName LastName DayOfBirth = fn; = ln; = DOB; = YOB;

MonthOfBirth = MOB; YearOfBirth } //-------------------------------------------------------------------------void { // Display the characteristics of the student cout << "Characteristics of this student"; cout << "\nFull Name: " << FirstName << " " << LastName; cout << "\nDate of Birth: " << DayOfBirth << "/" << MonthOfBirth << "/" << YearOfBirth << "\n"; } //-------------------------------------------------------------------------8. Test the constructors in the main() function with the following: //-------------------------------------------------------------------------#include <iostream> using namespace std; #include "Students.h" //-------------------------------------------------------------------------TStudent::Display() = YOB;

void {

Exit()

cout << "\n\nPress any key to continue...";

} //-------------------------------------------------------------------------int main() { TStudent DefaultStudent;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
DefaultStudent.Display(); cout << endl;

TStudent WithNameOnly("Genevieve", "Souchon"); WithNameOnly.Display(); cout << endl;

TStudent ByDateOfBirth(12, 5, 1987); ByDateOfBirth.Display(); cout << endl;

TStudent Typical("William", "Tobolowski", 5, 15, 1985); Typical.Display();

Exit(); return 0; } //-------------------------------------------------------------------------9. Press F9 to test the program: Characteristics of this student Full Name: John Doe Date of Birth: 1/1/1990

Characteristics of this student Full Name: Genevieve Souchon Date of Birth: 1/1/1985

Characteristics of this student Full Name: William Smith Date of Birth: 12/5/1987

Characteristics of this student Full Name: William Tobolowski Date of Birth: 5/15/1985

Press any key to continue... 10. Return to your programming environment

Techniques of Initializing With a Constructor


We have already seen various techniques of initializing member variables and implementing member methods. In the same way, a constructor can be defined locally, in the header file: Brick Unit - Header File: Brick.h

//--------------------------------------------------------------------------#ifndef BricksH #define BricksH

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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
class TBrick { public: TBrick(double L, double h, double t) { Length = L; Height = h; Thickness = t; } double void double void double void double void private: double Length; double Height; double Thickness; }; //--------------------------------------------------------------------------#endif
There is another technique you can use to initialize the member variables in a constructor. To initialize the list of members, after defining the constructor, which is after the parentheses, type a colon, followed by the name of an argument and include the initial value in parentheses. The initializations are separated by a comma. Since the constructor is a method, make sure you provide its body. To initialize the members of our TBrick object, we can type: Brick Unit - Header File: Brick.h

getLength() const; setLength(const double l); getHeight() const; setHeight(const double h); getThickness() const; setThickness(const double t); CementVolume(); ShowProperties();

//-------------------------------------------------------------------------#ifndef BricksH #define BricksH

//-------------------------------------------------------------------------class TBrick { public: TBrick() : Length(3.25), Height(2.55), Thickness(3.55) {} TBrick(double L, double h, double t) { Length = L; Height = h; Thickness = t; } double void double void double void double void private: double Length; double Height; double Thickness; }; getLength() const; setLength(const double l); getHeight() const; setHeight(const double h); getThickness() const; setThickness(const double t); CementVolume(); ShowProperties();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//-------------------------------------------------------------------------#endif
The source file would be as follows. Brick Unit - Source File: Brick.cpp

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

#include "Bricks.h" //--------------------------------------------------------------------------

//-------------------------------------------------------------------------double { return Length; } //-------------------------------------------------------------------------void { Length = l; } //-------------------------------------------------------------------------double { return Height; } //-------------------------------------------------------------------------void { Height = h; } //-------------------------------------------------------------------------double { return Thickness; } //-------------------------------------------------------------------------void { Thickness = t; } //-------------------------------------------------------------------------TBrick::setThickness(const double t) TBrick::getThickness() const TBrick::setHeight(const double h) TBrick::getHeight() const TBrick::setLength(const double l) TBrick::getLength() const

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
double { double Enclosure = 0.50; // This includes both walls of the brick itself double HoleLength = Length - 0.75; // Including both holes double double HoleThickness = Thickness - Enclosure; double HoleVolume = HoleLength * HoleThickness * Height; double TotalVolume = Length * Height * Thickness; double ValidVolume = TotalVolume - HoleVolume; TBrick::CementVolume()

return ValidVolume; } //-------------------------------------------------------------------------void { cout << "Foundation Brick Properties"; cout << setiosflags(ios::fixed) << setprecision(2); cout << "\nLength = " << Length; cout << "\nHeight = " << Height; cout << "\nThickness = " << Thickness; cout << "\nCement Volume = " << CementVolume() << "\n"; } //-------------------------------------------------------------------------To test the program, we would implement the main() function as follows. Main Unit - Source File: Main.cpp

TBrick::ShowProperties()

//-------------------------------------------------------------------------#include <iostream> using namespace std; #include "Bricks.h" //--------------------------------------------------------------------------

int main() { TBrick Lott; Lott.ShowProperties();

return 0; } //-------------------------------------------------------------------------We can use the same technique to initialize other constructors if more than one. We can therefore change the constructors of the program we had earlier using this syntax. Brick Unit - Header File: Brick.h

//--------------------------------------------------------------------------#ifndef BricksH

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#define BricksH

//--------------------------------------------------------------------------class TBrick { public: TBrick() : Length(0), Height(0), Thickness(0) {} TBrick(double L) : Length(L), Height(4.35), Thickness(3.05) {} TBrick(double L, double h, double t) : Length(L), Height(h), Thickness(t) {} double void double void double void double void private: double Length; double Height; double Thickness; }; //--------------------------------------------------------------------------#endif
The source file remains the same as above. The main() function would be implemented as follows. Main.cpp

getLength() const; setLength(const double l); getHeight() const; setHeight(const double h); getThickness() const; setThickness(const double t); CementVolume(); ShowProperties();

//-------------------------------------------------------------------------#include <iostream> using namespace std; #include "Bricks.h" //--------------------------------------------------------------------------

int main() { // Calling the object using the default constructor TBrick Lott; Lott.ShowProperties();

// This time, the program will use the constructor that has one argument TBrick Motto(6.12); Motto.ShowProperties();

// The following object is supplied with arguments TBrick Hott(5.25, 3.55, 3.55); Hott.ShowProperties();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

return 0; } //-------------------------------------------------------------------------This would produce the following result:

Foundation Brick Properties Length = 0.00 Height = 0.00 Thickness = 0.00 Cement Volume = 0.00 Foundation Brick Properties Length = 6.12 Height = 4.35 Thickness = 3.05 Cement Volume = 21.63 Foundation Brick Properties Length = 5.25 Height = 3.55 Thickness = 3.55 Cement Volume = 17.44

Press any key to continue...


If you do not want to implement these constructors in the header file, you can carry them to the source file, using the same syntax, like this: Brick Unit - Header File: Brick.h

//-------------------------------------------------------------------------#ifndef BricksH #define BricksH

//-------------------------------------------------------------------------class TBrick { public: TBrick(); TBrick(double L); TBrick(double L, double h, double t); double void double void double void double void private: double Length; double Height; getLength() const; setLength(const double l); getHeight() const; setHeight(const double h); getThickness() const; setThickness(const double t); CementVolume(); ShowProperties();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
double Thickness; }; //-------------------------------------------------------------------------#endif
Brick Unit - Source File: Brick.cpp

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

#include "Bricks.h" //--------------------------------------------------------------------------

TBrick::TBrick() : Length(0), Height(0), Thickness(0) { } //-------------------------------------------------------------------------TBrick::TBrick(double L) : Length(L), Height(4.35), Thickness(3.05) { } //-------------------------------------------------------------------------TBrick::TBrick(double L, double h, double t) : Length(L), Height(h), Thickness(t) { } //-------------------------------------------------------------------------. . .

Initializing With Constructors


1. To implement the both default and the complete constructors in the source file, change the listing of Students.h as follows: //-------------------------------------------------------------------------#ifndef StudentsH #define StudentsH #include <string> using namespace std; //-------------------------------------------------------------------------class TStudent { public: TStudent() { FirstName = "John"; LastName = "Doe"; DayOfBirth = 1; MonthOfBirth = 1; YearOfBirth = 1990;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} TStudent(string F, string L); // Name Initializer

TStudent(int DOB, int MOB, int YOB); // Initial Date of birth TStudent(string fn, string ln, int DOB, int MOB, int YOB) { FirstName LastName DayOfBirth = fn; = ln; = DOB;

MonthOfBirth = MOB; YearOfBirth } void private: string FirstName; string LastName; int DayOfBirth; int MonthOfBirth; int YearOfBirth; }; //-------------------------------------------------------------------------#endif 2. Make sure you change the implementation file as follows: 3. To use the new technique of initializing the member variables, implement the constructors in the
Students.cpp file as follows:

= YOB;

Display();

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

using namespace std;

#include "Students.h" //--------------------------------------------------------------------------

//-------------------------------------------------------------------------TStudent::TStudent(string FN, string LN) { FirstName LastName DayOfBirth = FN; = LN; = 1;

MonthOfBirth = 1; YearOfBirth } //-------------------------------------------------------------------------TStudent::TStudent(int DOB, int MOB, int YOB) { FirstName LastName = "William"; = "Smith"; = 1985;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
DayOfBirth = DOB; MonthOfBirth = MOB; YearOfBirth } //-------------------------------------------------------------------------void { // Display the characteristics of the student cout << "Characteristics of this student"; cout << "\nFull Name: " << FirstName << " " << LastName; cout << "\nDate of Birth: " << DayOfBirth << "/" << MonthOfBirth << "/" << YearOfBirth << "\n"; } //-------------------------------------------------------------------------4. Test the program and return to your programming environment. 5. To initialize the member variables using parentheses, change the Students.h file as follows: //-------------------------------------------------------------------------#ifndef StudentsH #define StudentsH #include <iostream> //-------------------------------------------------------------------------class TStudent { public: TStudent() : FirstName("John"), LastName("Doe"), DayOfBirth(1), MonthOfBirth(1), YearOfBirth(1990) {} TStudent(string F, string L); // Name Initializer TStudent::Display() = YOB;

TStudent(int DOB, int MOB, int YOB); // Initial Date of birth TStudent(string fn, string ln, int DOB, int MOB, int YOB) : FirstName(fn), LastName(ln), DayOfBirth(DOB), MonthOfBirth(MOB), YearOfBirth(YOB) {} void private: string FirstName; string LastName; Display();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
int DayOfBirth; int MonthOfBirth; int YearOfBirth; }; //-------------------------------------------------------------------------#endif 6. Test the program and return to your programming environment 7. To use this initialization in the implementation file, change the Students.h file as follows: //-------------------------------------------------------------------------#ifndef StudentsH #define StudentsH #include <string> using namespace std; //-------------------------------------------------------------------------class TStudent { public: TStudent(); TStudent(string F, string L); // Name Initializer

TStudent(int DOB, int MOB, int YOB); // Initial Date of birth TStudent(string fn, string ln, int DOB, int MOB, int YOB); void private: string FirstName; string LastName; int DayOfBirth; int MonthOfBirth; int YearOfBirth; }; //-------------------------------------------------------------------------#endif 8. Change the Students.cpp file as follows: //-------------------------------------------------------------------------#include "Students.h" //-------------------------------------------------------------------------Display();

//-------------------------------------------------------------------------TStudent::TStudent() : FirstName("John"), LastName("Doe"), DayOfBirth(1), MonthOfBirth(1), YearOfBirth(1990) { } //-------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
-------TStudent::TStudent(string FN, string LN) : FirstName(FN), LastName(LN), DayOfBirth(1), MonthOfBirth(1), YearOfBirth(1985) {

} //-------------------------------------------------------------------------TStudent::TStudent(int DOB, int MOB, int YOB) : FirstName("William"), LastName("Smith"), DayOfBirth(DOB), MonthOfBirth(MOB), YearOfBirth(YOB) { } //-------------------------------------------------------------------------TStudent::TStudent(string fn, string ln, int DOB, int MOB, int YOB) : FirstName(fn), LastName(ln), DayOfBirth(DOB), MonthOfBirth(MOB), YearOfBirth(YOB) { } //-------------------------------------------------------------------------void { // Display the characteristics of the student cout << "Characteristics of this student"; cout << "\nFull Name: " << FirstName << " " << LastName; cout << "\nDate of Birth: " << DayOfBirth << "/" << MonthOfBirth << "/" << YearOfBirth << "\n"; } //-------------------------------------------------------------------------9. Press F9 to test the program and return to your programming environment. TStudent::Display()

The Copy Constructor


Copying an Object
After creating an object and assigning appropriate values to its members, you can perform any regular operation on it. Although this gets a little particular with objects, which will be expanded when learning about operator overloading, you can assign an object to another object. We have already learned:

How to assign A value to a variable The value of one variable to another A value to an objects member

Example int a = 250; NbrOfBoys = NbrOfGirls; Video.Category = Drama

Assigning a variable to another is equivalent to making a copy of that variable. As you assign a variable to another, you can assign one object to another. Both objects must be recognizably equivalent to the compiler. Imagine you want to build the same brick twice. All you have to do is to assign one brick to another, which is

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
take care of in the following main() function:

//-------------------------------------------------------------------------#include <iostream> using namespace std; #include "Bricks.h" //--------------------------------------------------------------------------

int main() { // Declaring one brick TBrick Hott(5.25, 3.55, 3.55); Hott.ShowProperties(); cout << endl;

// Assigning one brick to another TBrick Bosco = Hott; Bosco.ShowProperties();

return 0; } //-------------------------------------------------------------------------Here is an example of running the program:

Foundation Brick Properties Length = 5.25 Height = 3.55 Thickness = 3.55 Cement Volume = 17.44

Foundation Brick Properties Length = 5.25 Height = 3.55 Thickness = 3.55 Cement Volume = 17.44

Press any key to continue...


Notice that both orders display the same thing.

Using a Copy Constructor


Besides the default constructor, the compiler creates another function method called the copy constructor. This is another special method that is used for operations such as copying an object into another. Remember, we have seen that a variable can be initialized using the = symbol or the parentheses, as in the following example:

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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//--------------------------------------------------------------------------

int main() { // Assigning a value to a variable using the = sign int CheeseSteak = 2; // Assigning a value using the parenthesis int TunaSalad(4); // Assigning one variable to another int TurkeyHam(TunaSalad); // Assignment with parenthesis double PriceCS(3.12); double PriceTS = 2.95; // Assigning the price of one item to another double PriceTH(PriceTS);

double TotalCS, TotalTS, TotalTH; TotalCS = CheeseSteak * PriceCS; TotalTS = TunaSalad * PriceTS; TotalTH = TurkeyHam * PriceTH;

cout << "Total Order\n"; cout << setiosflags(ios::fixed) << setprecision(2); cout << CheeseSteak << " orders of Cheese Steak, Price = $" << TotalCS << "\n"; cout << TunaSalad << " orders of Tuna Salad, Price = $" << TotalTS << endl; cout << TurkeyHam << " orders of Turkey Ham, Price = $" << TotalTH << endl;

return 0; } //-------------------------------------------------------------------------This would produce:

Total Order 2 orders of Cheese Steak, Price = $6.24 4 orders of Tuna Salad, Price = $11.80 4 orders of Turkey Ham, Price = $11.80

Press any key to continue...


When you have two instances of an object such as: Video Drama, Comedy; you can assign one object to another like this: Drama = Comedy; This operation indeed assigns a copy of the Comedy Video to the Drama object. Behind the scenes, this transaction is handled by the copy constructor. Like the default constructor, the compiler automatically creates a copy constructor when an onbject is instantiated. Like the default constructor, you can explicitly create a copy constructor; it has a different syntax although it also holds the same name as the object. The syntax of

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
the copy constructor.

ObjectName(ObjectName& Name);
The copy constructor takes one argument, which is the same as the object itself. When a copy is made, it holds and carries the building constructor of the object. This object is specified as the argument. As a copy whose value still resides with the object, this argument should be passed as a reference. As a copy, this argument should not be modified. It is only used to pass a copy of the object to the other objects that need it. Therefore, the argument should not be modified. As a result, it should be declared as a constant. The syntax of the copy constructor becomes:

ObjectName(const ObjectName& Name);


To copy one object to another, first create a copy constructor:

//-------------------------------------------------------------------------#ifndef BricksH #define BricksH //-------------------------------------------------------------------------class TBrick { public: TBrick(); TBrick(double L, double h, double t); TBrick(const TBrick &Brk); double void double void double void double void private: double Length; double Height; double Thickness; }; //-------------------------------------------------------------------------#endif
In the implementation, assign a member variable of the copy constructor to the equivalent member of the object:

getLength() const; setLength(const double l); getHeight() const; setHeight(const double h); getThickness() const; setThickness(const double t); CementVolume(); ShowProperties();

//-------------------------------------------------------------------------TBrick::TBrick(const TBrick& B) { Length Height = B.Length; = B.Height;

Thickness = B.Thickness; } //-------------------------------------------------------------------------Here is an example that uses a copy constructor to copy one order into another:

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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#include "Bricks.h" //--------------------------------------------------------------------------

int main() { TBrick Beam(7.25, 4.85, 5.15), Hoyt;

Beam.ShowProperties(); cout << endl;

// Create the other brick similar to the first // Assigning using the assignment operator Hoyt = Beam; Hoyt.ShowProperties(); cout << endl;

// Assigning using the parentheses TBrick Mollo(Beam); Hoyt.ShowProperties();

return 0; } //-------------------------------------------------------------------------This would produce:

Foundation Brick Properties Length = 7.25 Height = 4.85 Thickness = 5.15 Cement Volume = 34.50

Foundation Brick Properties Length = 7.25 Height = 4.85 Thickness = 5.15 Cement Volume = 34.50

Foundation Brick Properties Length = 7.25 Height = 4.85 Thickness = 5.15 Cement Volume = 34.50

Press any key to continue...

Using the Copy Constructor


1. To use the default copy constructor created by the compiler, change the content of the main()

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
function as follows: //-------------------------------------------------------------------------#include <iostream> using namespace std; #include "Students.h" //-------------------------------------------------------------------------int main() { TStudent Student1("Pamela", "Wattson", 2, 18, 1988); Student1.Display(); cout << endl;

TStudent DefaultStudent; DefaultStudent.Display(); cout << endl;

TStudent DuplicateHer = Student1; DuplicateHer.Display();

return 0; } //-------------------------------------------------------------------------2. Execute the program to test it and return to your programming environment. 3. To explicitly create your own copy constructor, declare one in the header file as follows: //-------------------------------------------------------------------------#ifndef StudentsH #define StudentsH #include <iostream> using namespace std; //-------------------------------------------------------------------------class TStudent { public: TStudent(); TStudent(string F, string L); // Name Initializer

TStudent(int DOB, int MOB, int YOB); // Initial Date of birth TStudent(string fn, string ln, int DOB, int MOB, int YOB); TStudent(const TStudent& S); void private: string FirstName; string LastName; int DayOfBirth; int MonthOfBirth; Display();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
int YearOfBirth; }; //-------------------------------------------------------------------------#endif 4. Implement your copy constructor as follows: //-------------------------------------------------------------------------TStudent::TStudent(const TStudent& Stud) : FirstName(Stud.FirstName), LastName(Stud.LastName), DayOfBirth(Stud.DayOfBirth), MonthOfBirth(Stud.MonthOfBirth), YearOfBirth(Stud.YearOfBirth) { } //-------------------------------------------------------------------------5. Test the program again and return to your programming environment. 6. Save the project.

Destructors
Introduction
As opposed to a constructor, a destructor is called when a program has finished using an instance of an object. A destructor does the cleaning behind the scenes. Like the default constructor, the compiler always create a default destructor if you don't create one. Like the default constructor, a destructor also has the same name as its object. This time, the name of the destructor starts with a tilde. To create your own destructor, in the header file, type ~ followed by the name of the object. Here is an example:

//-------------------------------------------------------------------------#ifndef BricksH #define BricksH

//-------------------------------------------------------------------------class TBrick { public: TBrick(); TBrick(double L, double h, double t); TBrick(const TBrick &Brk); ~TBrick(); double void double void double void double void private: double Length; double Height; getLength() const; setLength(const double l); getHeight() const; setHeight(const double h); getThickness() const; setThickness(const double t); CementVolume(); ShowProperties();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
double Thickness; }; //-------------------------------------------------------------------------#endif
As done with a default constructor, you don't need to put anything in the implementation of a destructor. In fact, when a program terminates, the compiler can itself destroy all of the objects and variables that your program has used. The only true time you will be concerned with destroying objects is if the objects were created dynamically, which we will learn when studying pointers. You can implement your destructor in the header file by just providing it with empty parentheses:

//-------------------------------------------------------------------------#ifndef BricksH #define BricksH

//-------------------------------------------------------------------------class TBrick { public: ... ~TBrick() {} ... private: ... }; //-------------------------------------------------------------------------#endif


Otherwise, you can also implement it in the cpp file with empty parentheses. Here is an example:

//-------------------------------------------------------------------------TBrick::~TBrick() { } //--------------------------------------------------------------------------

Using Destructors
1. To illustrate the construction and destruction effects of an object, create a new Console Application named Library 2. Change the content of the file as follows: //-------------------------------------------------------------------------#include <iostream> using namespace std; //-------------------------------------------------------------------------class TBook { public: TBook(); // Constructor ~TBook(); // Destructor void Message() { cout << "\tI read the book\n"; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
}; //-------------------------------------------------------------------------TBook::TBook() { cout << "I see a book... Using the Constructor\n"; } //-------------------------------------------------------------------------TBook::~TBook() { cout << "I close the book! Using the Destructor\n"; } //-------------------------------------------------------------------------int main() { cout << "I am at the library\n"; { TBook A; }

cout << "\nI didn't like that book. I will try another\n\n"; { TBook B; B.Message(); }

cout << "\nI am getting out of the library\n\n";

return 0; } //-------------------------------------------------------------------------3. Execute the program to see the result: I am at the library I see a book... Using the Constructor I close the book! Using the Destructor

I didn't like that book. I will try another

I see a book... Using the Constructor I read the book I close the book! Using the Destructor

I am getting out of the library 4. Return to your programming environment 5. Reopen the Students project from the Students2 folder. 6. To create a destructor for our TStudent class, change the header file as follows:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//-------------------------------------------------------------------------#ifndef StudentsH #define StudentsH #include <iostream> using namespace std; //-------------------------------------------------------------------------class TStudent { public: TStudent(); TStudent(string F, string L); // Name Initializer

TStudent(int DOB, int MOB, int YOB); // Initial Date of birth TStudent(string fn, string ln, int DOB, int MOB, int YOB); ~TStudent(); TStudent(const TStudent& S); void private: string FirstName; string LastName; int DayOfBirth; int MonthOfBirth; int YearOfBirth; }; //-------------------------------------------------------------------------#endif 7. Implement the destructor in the Students.cpp file as follows: //-------------------------------------------------------------------------TStudent::~TStudent() { } //-------------------------------------------------------------------------8. Test the program and return to your programming environment. Display();

Previous

Copyright 2000-2004 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Arrays and Pointers of Classes


Classes and Arrays
An Array of Object Variables
We have learned to treat classes and structures as normal variables including creating an object by declaring a variable. We can define an object as follows: #include <iostream> using namespace std;

struct Point { char Letter; int x; int y; };

int main() { Point location;

location.Letter = 'D'; location.x location.y = 5;

= -2;

cout << "Point Location " << location.Letter << "(" << location.x << ", " << location.y << ");" << endl;

return 0; } This would produce: Point Location D(5, -2); Remember that you can also use the typedef keyword to customize the name of a data type. For example, the Point class can be type-defined as follows: typedef Point Coordinate; Coordinate location; As you would declare an array of variables, you can also declare an array of objects and manipulate each member of the array as if it were a regular variable. To do this, type the name of the class, followed by a valid C++ name for the variable, and followed by a dimension included in square brackets. Here is an example: #include <iostream> using namespace std;

struct Point {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
char Letter; int x; int y; };

int main() { Point coordinates[4];

return 0; } Using the typedef keyword, you can create a common name that would represent an array of objects. This can be done as follows: #include <iostream> using namespace std;

struct Point { char Letter; int x; int y; };

int main() { typedef Point Points[4]; Points coordinates;

return 0; } In this case, the name Points means the same thing as declaring an array of 4 Point variables. After declaring a variable as an array of objects, each member of the array has its own value you can assign, change, or retrieve. To get the value stored in a member variable of a member of an array, access it using its index. For example, to access the value of the third member variable of the first member of the above array, you could write the following: coordinates[0].y;

Initializing an Array of Objects


There are various ways you can initialize an array of objects. You can initialize the variable as a whole, when declaring it. Still, there are at least two ways you can initialize a variable when declaring it. To do this, assign an opening and closing curly brackets combination to the variable. Inside the curly brackets, provide a list of the values of each member variable object, first in the order they appear in the class, second in the incremental order of the array. Here is an example: #include <iostream> using namespace std;

struct Point

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ char Letter; int x; int y; };

int main() { Point Coordinates[4] = {'P', -4, 'L', 5, 0, 'Q', -3, -2, 1, 'M', 2, 6};

cout << "Point Coordinates"; cout << "\n" << Coordinates[0].Letter << "(" << Coordinates[0].x << ", " << Coordinates[0].y << ");"; cout << "\n" << Coordinates[1].Letter << "(" << Coordinates[1].x << ", " << Coordinates[1].y << ");"; cout << "\n" << Coordinates[2].Letter << "(" << Coordinates[2].x << ", " << Coordinates[2].y << ");"; cout << "\n" << Coordinates[3].Letter << "(" << Coordinates[3].x << ", " << Coordinates[3].y << ");\n"; return 0; } This would produce: Point Coordinates P(-4, 0); Q(-3, -2); L(5, 1); M(2, 6); Another technique you can use, which would make the initialization easier to read, consists of including the values of each member of the array in its own set of curly brackets. It would be done as follows: #include <iostream> using namespace std;

struct Point { char Letter; int x; int y; };

int main() { Point Coordinates[4] = { {'P', -4, {'L', 5, 0}, {'Q', -3, -2}, 1}, {'M', 2, 6}};

cout << "Point Coordinates";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\n" << Coordinates[0].Letter << "(" << Coordinates[0].x << ", " << Coordinates[0].y << ");"; cout << "\n" << Coordinates[1].Letter << "(" << Coordinates[1].x << ", " << Coordinates[1].y << ");"; cout << "\n" << Coordinates[2].Letter << "(" << Coordinates[2].x << ", " << Coordinates[2].y << ");"; cout << "\n" << Coordinates[3].Letter << "(" << Coordinates[3].x << ", " << Coordinates[3].y << ");\n"; return 0; } In our introduction to Classes, we also saw that you could declare an instance of a structure when creating it. This was done by providing a name for the variable between the closing curly bracket and the semi-colon. In the same way, when declaring such a variable, you can initialize it directly. Here is an example: #include <iostream> using namespace std;

struct Point { char Letter; int x; int y; } Coordinates[4] = {'P', -4, 0, 'Q', -3, -2,'L', 5, 1, 'M', 2, 6};

int main() { cout << "Point Coordinates"; cout << "\n" << Coordinates[0].Letter << "(" << Coordinates[0].x << ", " << Coordinates[0].y << ");"; cout << "\n" << Coordinates[1].Letter << "(" << Coordinates[1].x << ", " << Coordinates[1].y << ");"; cout << "\n" << Coordinates[2].Letter << "(" << Coordinates[2].x << ", " << Coordinates[2].y << ");"; cout << "\n" << Coordinates[3].Letter << "(" << Coordinates[3].x << ", " << Coordinates[3].y << ");\n"; return 0; } In the same way, you can initialize the array when creating the variable: #include <iostream> using namespace std;

struct Point { char Letter; int x; int y; } Coordinates[4] = { {'P', -4, 0}, {'Q', -3, -2},

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{'L', 5, 1}, {'M', 2, 6}};

int main() { cout << "Point Coordinates"; cout << "\n" << Coordinates[0].Letter << "(" << Coordinates[0].x << ", " << Coordinates[0].y << ");"; cout << "\n" << Coordinates[1].Letter << "(" << Coordinates[1].x << ", " << Coordinates[1].y << ");"; cout << "\n" << Coordinates[2].Letter << "(" << Coordinates[2].x << ", " << Coordinates[2].y << ");"; cout << "\n" << Coordinates[3].Letter << "(" << Coordinates[3].x << ", " << Coordinates[3].y << ");\n"; return 0; } The above techniques of initialization are convenient for small objects, traditionally used as C structures. The other technique you can use, also convenient for an array of a more elaborate object, consists of initializing each member of the array. To do this, you assign a value to each member of the object. This can be done as follows: #include <iostream> using namespace std;

struct Point { char Letter; int x; int y; };

int main() { Point Coordinates[2];

Coordinates[0].Letter = 'P'; Coordinates[0].x = -4; Coordinates[0].y = 0;

Coordinates[1].Letter = 'Q'; Coordinates[1].x = -3; Coordinates[1].y = -2;

cout << "Point Coordinates"; cout << "\n" << Coordinates[0].Letter << "(" << Coordinates[0].x << ", " << Coordinates[0].y << ");"; cout << "\n" << Coordinates[1].Letter << "(" << Coordinates[1].x << ", " << Coordinates[1].y << ");\n";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return 0; } Here is an example of running the program: Point Coordinates P(-4, 0); Q(-3, -2); Once you have declared and initialized an array of objects, you can use the values of its member variables as you see fit. For example, from the above Point class, you can request the coordinates of two points, write an equation that calculates their distance or one that gets their slope, and display it to the user. This can be done as follows:

#include <iostream> using namespace std;

struct Point { char Letter; int x; int y; };

int main() { Point Points[2]; double Slope;

cout << "Enter the coordinates of the points\n"; cout << "x1 = "; cin >> Points[0].x; cout << "y1 = "; cin >> Points[0].y; cout << "x2 = "; cin >> Points[1].x; cout << "y2 = "; cin >> Points[1].y;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Points[0].Letter = 'A'; Points[1].Letter = 'B';

if( Points[0].x != Points[1].x ) Slope = (Points[1].y - Points[0].y) / (Points[1].x - Points[0].x); else Slope = 0.00;

cout << "The slope of " << Points[0].Letter << "(" << Points[0].x << ", " << Points[0].y << ") and " << Points[1].Letter << "(" << Points[1].x << ", " << Points[1].y << ") is " << Slope << endl;

return 0; } Here is an example of running the program: Enter the coordinates of the points x1 = -2 y1 = 3 x2 = 1 y2 = -3 The slope of A(-2, 3) and B(1, -3) is -2

An Array of Objects as Argument


Like a regular data type, an array of objects can be passed as an argument to a function. To do this, when declaring and when implementing the function, provide the array in the parentheses of the function as you would do with any other regular variable. Here is an example that takes and processes an argument that is an array of objects: void ProcessCoordinates(Point points[]) { cout << "Enter the coordinates of four points\n"; cout << "x1 = "; cin >> points[0].x; cout << "y1 = "; cin >> points[0].y; cout << "x2 = "; cin >> points[1].x; cout << "y2 = "; cin >> points[1].y; cout << "x3 = "; cin >> points[2].x; cout << "y3 = "; cin >> points[2].y; cout << "x4 = "; cin >> points[3].x; cout << "y4 = "; cin >> points[3].y; } The above function was using an array whose dimension you know. If you do not know or cannot predict the dimension of an array, you can/should/must pass an additional argument that holds the number of members of the array. When calling a function that takes a single-dimension array of objects, the name of the argument is sufficient to the compiler. Other than this, you can apply all the other rules we learned for arrays of regular data types: #include <iostream> using namespace std;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

struct Point { char Letter; int x; int y; };

void ProcessCoordinates(Point points[]); void DisplayCoordinates(Point points[], const int size);

int main() { Point coordinates[4];

ProcessCoordinates(coordinates); cout << endl; DisplayCoordinates(coordinates, 4);

return 0; }

void ProcessCoordinates(Point points[]) { cout << "Enter the coordinates of four points\n"; cout << "x1 = "; cin >> points[0].x; cout << "y1 = "; cin >> points[0].y; points[0].Letter = 'A'; cout << "x2 = "; cin >> points[1].x; cout << "y2 = "; cin >> points[1].y; points[1].Letter = 'B'; cout << "x3 = "; cin >> points[2].x; cout << "y3 = "; cin >> points[2].y; points[2].Letter = 'C'; cout << "x4 = "; cin >> points[3].x; cout << "y4 = "; cin >> points[3].y; points[3].Letter = 'D'; }

void DisplayCoordinates(Point points[], const int size) { cout << "Point Coordinates"; for(int i = 0; i < size; i++) cout << "\n" << points[i].Letter << "(" << points[i].x << ", " << points[i].y << ");"; } Here is an example of running the program: Enter the coordinates of four points x1 = -1 y1 = 5 x2 = -2

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
y2 = -4 x3 = 3 y3 = 5 x4 = 2 y4 = -4

Point Coordinates A(-1, 5); B(-2, -4); C(3, 5); D(2, -4);

Classes and Pointers


Declaring a Pointer to an Object
Header File: cone.h //-------------------------------------------------------------------------#ifndef ConeH #define ConeH //-------------------------------------------------------------------------class Cone { private: double _rad; double _hgt; public: Cone(); Cone(double radius, double height); Cone(const Cone& c); ~Cone(); void setRadius(const double radius) { _rad = radius; } void setHeight(const double height) { _hgt = height; } double getRadius() const { return _rad; } double getHeight() const { return _hgt; } double CalculateBaseArea() const; double CalculateLateralArea() const; double CalculateTotalArea() const; double CalculateVolume() const; }; //-------------------------------------------------------------------------#endif Source File: cone.cpp //-------------------------------------------------------------------------#include <math.h> #include "Cone.h"

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//using namespace std; //-------------------------------------------------------------------------Cone::Cone() : _rad(0.00), _hgt(0.00) {

} //-------------------------------------------------------------------------Cone::Cone(double r, double h) : _rad(r), _hgt(h) {

} //-------------------------------------------------------------------------Cone::Cone(const Cone& c) : _rad(c._rad), _hgt(c._hgt) {

} //-------------------------------------------------------------------------Cone::~Cone() {

} //-------------------------------------------------------------------------double Cone::CalculateBaseArea() const { // The area of the base of the cone return _rad * _rad * 3.14159; } //-------------------------------------------------------------------------double Cone::CalculateLateralArea() const { // The area covered by the tissue that covers the tent double radius2 = _rad * _rad; double height2 = _hgt * _hgt; double slantHeight = sqrt(radius2 + height2); return 3.14159 * _rad * slantHeight; } //-------------------------------------------------------------------------double Cone::CalculateTotalArea() const { return CalculateBaseArea() + CalculateLateralArea();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} //-------------------------------------------------------------------------double Cone::CalculateVolume() const { // The interior volume available for inhabiting the tent return (3.14159 * _rad * _rad * _hgt) / 3; } //-------------------------------------------------------------------------Like a regular data type, you can declare a class as a pointer, you can pass it to a function as a reference or as a pointer, and you can dynamically create an instance of a class. To declare a pointer to a class, type its name, followed by an asterisk and followed by a name for the variable. Here is an example: Cone *pCone; Like a pointer to a regular data type, after declaring a pointer to a class, you should let the compiler know what variable the pointer is pointing to. This can easily be done by assigning the address of an existing variable as follows: #include <iostream> #include "cone.h" using namespace std;

int main() { Cone iceCone; Cone *pCone = &iceCone;

double radius, height;

cout << "Enter the cone's dimensions\n"; cout << "Radius: "; cin >> radius; cout << "Height: "; cin >> height;

pCone->setRadius(radius); pCone->setHeight(height);

cout << "Cone's Characteristics"; cout << "\nRadius: cout << "\nHeight: cout << "\nBase Area: cout << "\nTotal Area: " << pCone->getRadius(); " << pCone->getHeight(); " << pCone->CalculateBaseArea(); " << pCone->CalculateTotalArea();

cout << "\nTexture Area: " << pCone->CalculateLateralArea() << endl;

return 0; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Here is an example of running the program: Enter the cone's dimensions Radius: 38.44 Height: 20.72 Cone's Characteristics Radius: Height: Base Area: Total Area: 38.44 20.72 4642.12 9915.67

Texture Area: 5273.55

Dynamic Objects
One of the advantages of using pointers is that they give you the ability to use memory only as needed. This is done by using the asterisk * and the new operators. The syntax of declaring a pointer to an object is: ClassName* VariableName = new ClassName; The ClassName is the class whose variable you want to declare. It could be in the program or one that shipped with the compiler. Once again, the asterisk lets the compiler know that the class is declared as a pointer. The variable name follows the same rules we have applied to other variables so far. There are two main ways you can provide values to the member variables of your dynamic object. You can request their values from the user, from another object or function, or you can initialize the variable. Still there are at least two ways you can initialize the variable. When declaring it, since you would be using a constructor to build the object, you can use the constructor that takes the number of values you want to initialize. Consider the above Cone class. This class provides three constructors, one of which takes two arguments to initialize a complete Cone variable. You can use this constructor when using the new operator. In the parentheses, provide a value for each member variable. Here is an example: #include <iostream> #include "cone.h" using namespace std;

int main() { Cone *pCone = new Cone(25.55, 20.15);

cout << "Cone's Characteristics"; cout << "\nRadius: cout << "\nHeight: cout << "\nBase Area: cout << "\nTotal Area: " << pCone->getRadius(); " << pCone->getHeight(); " << pCone->CalculateBaseArea(); " << pCone->CalculateTotalArea();

cout << "\nTexture Area: " << pCone->CalculateLateralArea() << endl;

return 0; } This would produce: Cone's Characteristics Radius: Height: Base Area: 25.55 20.15 2050.84

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Total Area: 4662.71 Texture Area: 2611.88 If you want to use, or have used, the default constructor to create the object, you can then use one of its methods to initialize the variable. Here is an example: #include <iostream> #include "cone.h" using namespace std;

int main() { Cone *pCone = new Cone();

pCone->setRadius(25.55); pCone->setHeight(20.15);

cout << "Cone's Characteristics"; cout << "\nRadius: cout << "\nHeight: cout << "\nBase Area: cout << "\nTotal Area: " << pCone->getRadius(); " << pCone->getHeight(); " << pCone->CalculateBaseArea(); " << pCone->CalculateTotalArea();

cout << "\nTexture Area: " << pCone->CalculateLateralArea() << endl;

return 0; } Of course, at any time, you can change the values of the pointer using either one of its constructors or its methods. After using a variable that was declared using the new operator, you can reclaim the memory space it was using. This is done with the delete operator. Here is an example: #include <iostream> #include "cone.h" using namespace std;

int main() { Cone *pCone = new Cone();

pCone->setRadius(25.55); pCone->setHeight(20.15);

cout << "Cone's Characteristics"; cout << "\nRadius: cout << "\nHeight: cout << "\nBase Area: cout << "\nTotal Area: " << pCone->getRadius(); " << pCone->getHeight(); " << pCone->CalculateBaseArea(); " << pCone->CalculateTotalArea();

cout << "\nTexture Area: " << pCone->CalculateLateralArea() << endl;

pCone = new Cone(44.42, 35.72);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\nCone's Characteristics"; cout << "\nRadius: cout << "\nHeight: cout << "\nBase Area: cout << "\nTotal Area: " << pCone->getRadius(); " << pCone->getHeight(); " << pCone->CalculateBaseArea(); " << pCone->CalculateTotalArea();

cout << "\nTexture Area: " << pCone->CalculateLateralArea() << endl;

return 0; } This would produce: Cone's Characteristics Radius: Height: Base Area: Total Area: 25.55 20.15 2050.84 4662.71

Texture Area: 2611.88

Cone's Characteristics Radius: Height: Base Area: Total Area: 44.42 35.72 6198.79 14153.2

Texture Area: 7954.38

Pointers to Arrays of Objects


Instead of using one pointer to an object, you can declare an array of pointers to object. The syntax used is: ClassName *VariableName[Dimension]; The ClassName must be an existing object. You can use your own object or one that shipped with the compiler. After the asterisk operator, type a valid name for a C++ variable. The dimension, which is (an estimate of) the number of elements of the array, is included in square brackets. After declaring the variable, you can initialize each member of the array using the new operator. This operator allocates enough memory space for the member of the array. This means that the initialization with the new operator can be followed by an actual initialization of the member variables of the array. To initialize a member of the array, you have various options. You must first call the new operator for each member of the array. Once again, you can use one of the constructors. Consider the above Cone object. We saw that one of its constructors took two arguments to create an object. You can use such a constructor to initialize a member of the array. Here are examples: #include <iostream> #include "cone.h" using namespace std;

int main() { Cone *pCone[3];

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
pCone[0] = new Cone(25.55, 20.15); pCone[1] = new Cone(12.44, 18.62); pCone[2] = new Cone(48.12, 38.84);

cout << "Cone's Characteristics\n"; for(int i = 0; i < 3; i++) { cout << "\n - Cone No. " << i + 1 << " -"; cout << "\nRadius: cout << "\nHeight: cout << "\nBase Area: cout << "\nTotal Area: " << pCone[i]->getRadius(); " << pCone[i]->getHeight(); " << pCone[i]->CalculateBaseArea(); " << pCone[i]->CalculateTotalArea();

cout << "\nTexture Area: " << pCone[i]->CalculateLateralArea() << endl; }

return 0; } This would produce: Cone's Characteristics

- Cone No. 1 Radius: Height: Base Area: Total Area: 25.55 20.15 2050.84 4662.71

Texture Area: 2611.88

- Cone No. 2 Radius: Height: Base Area: Total Area: 12.44 18.62 486.172 1361.33

Texture Area: 875.159

- Cone No. 3 Radius: Height: Base Area: Total Area: 48.12 38.84 7274.46 16622.9

Texture Area: 9348.43 If you had already created some objects and want to use their values, you can assign the desired variable to the member of the array of your choice. Here are examples: #include <iostream> #include "cone.h" using namespace std;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
int main() { Cone *pCone[3]; Cone conic(66.14, 50.82); Cone *iceCreamCone = new Cone(8.74, 6.82);

pCone[0] = &conic; pCone[1] = iceCreamCone; pCone[2] = new Cone(48.12, 38.84);

cout << "Cone's Characteristics\n"; for(int i = 0; i < 3; i++) { cout << "\n - Cone No. " << i + 1 << " -"; cout << "\nRadius: cout << "\nHeight: cout << "\nBase Area: cout << "\nTotal Area: " << pCone[i]->getRadius(); " << pCone[i]->getHeight(); " << pCone[i]->CalculateBaseArea(); " << pCone[i]->CalculateTotalArea();

cout << "\nTexture Area: " << pCone[i]->CalculateLateralArea() << endl; }

return 0; } This would produce: Cone's Characteristics

- Cone No. 1 Radius: Height: Base Area: Total Area: 66.14 50.82 13742.9 31074.1

Texture Area: 17331.3

- Cone No. 2 Radius: Height: Base Area: Total Area: 8.74 6.82 239.979 544.373

Texture Area: 304.395

- Cone No. 3 Radius: Height: Base Area: Total Area: 48.12 38.84 7274.46 16622.9

Texture Area: 9348.43 Another technique you can use is to first allocate memory space for a member of the array,

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
then use one of the methods of the object to initialize that particular member of the array. This can be taken care of with set methods. After using the array, you can delete each of its members using the delete operator. Here is an example: #include <iostream> #include "cone.h" using namespace std;

int main() { Cone *pCone[3];

pCone[0] = new Cone; pCone[0]->setRadius(25.55); pCone[0]->setHeight(20.15);

pCone[1] = new Cone; pCone[1]->setRadius(12.44); pCone[1]->setHeight(18.62);

pCone[2] = new Cone; pCone[2]->setRadius(48.12); pCone[2]->setHeight(38.84);

cout << "Cone's Characteristics\n"; for(int i = 0; i < 3; i++) { cout << "\n - Cone No. " << i + 1 << " -"; cout << "\nRadius: cout << "\nHeight: cout << "\nBase Area: cout << "\nTotal Area: << endl; } " << pCone[i]->getRadius(); " << pCone[i]->getHeight(); " << pCone[i]->CalculateBaseArea(); " << pCone[i]->CalculateTotalArea();

cout << "\nTexture Area: " << pCone[i]->CalculateLateralArea()

delete pCone[0]; delete pCone[1]; delete pCone[2];

return 0; }

An Object Passed as Pointer


To pass an object as pointer, when declaring and when implementing the object, use the asterisk operator between the class name and the variable name. Consequently, when defining the function, access the members of the object using the arrow operator: void RequestDimensions(Cone* cn)

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ double Radius, Height;

cout << "Enter the cone's dimensions\n"; cout << "Radius: "; cin >> Radius; cout << "Height: "; cin >> Height;

cn->setRadius(Radius); cn->setHeight(Height); } When calling such a function, if the variable was declared as a regular item, in the parentheses of the function, call the variable using the reference operator: #include <iostream> #include "cone.h" using namespace std;

void RequestDimensions(Cone* cn) { double Radius, Height;

cout << "Enter the cone's dimensions\n"; cout << "Radius: "; cin >> Radius; cout << "Height: "; cin >> Height;

cn->setRadius(Radius); cn->setHeight(Height); }

int main() { Cone typeCone;

RequestDimensions(&typeCone);

cout << "\nCone's Characteristics"; cout << "\nRadius: cout << "\nHeight: cout << "\nBase Area: cout << "\nTotal Area: " << typeCone.getRadius(); " << typeCone.getHeight(); " << typeCone.CalculateBaseArea(); " << typeCone.CalculateTotalArea();

cout << "\nTexture Area: " << typeCone.CalculateLateralArea();

return 0; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Here is an example of running the program: Enter the cone's dimensions Radius: 24.58 Height: 20.64

Cone's Characteristics Radius: Height: Base Area: Total Area: 24.58 20.64 1898.07 4376.58

Texture Area: 2478.5 As you may have realized, when an argument is passed as pointer, if the function modifies its value, the object would be altered. This has the same effect as passing an object by reference because, once more, the function has access to the memory location of the argument. Consequently, there is an advantage of speed when passing an argument as pointer. If, on the other hand, you do not want the function to modify the value of the argument, you can pass it as a constant pointer. Here is an example: #include <iostream> #include "cone.h" using namespace std;

void RequestDimensions(Cone*); void ShowCharacteristics(const Cone *pCone);

int main() { Cone typeCone;

RequestDimensions(&typeCone);

ShowCharacteristics(&typeCone);

return 0; }

void RequestDimensions(Cone* cn) { double Radius, Height;

cout << "Enter the cone's dimensions\n"; cout << "Radius: "; cin >> Radius; cout << "Height: "; cin >> Height;

cn->setRadius(Radius); cn->setHeight(Height); }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
void ShowCharacteristics(const Cone *pCone) { cout << "\nCone's Characteristics"; cout << "\nRadius: cout << "\nHeight: cout << "\nBase Area: cout << "\nTotal Area: " << pCone->getRadius(); " << pCone->getHeight(); " << pCone->CalculateBaseArea(); " << pCone->CalculateTotalArea();

cout << "\nTexture Area: " << pCone->CalculateLateralArea(); }

Classes and Pointers to Functions


A Pointer to Function as a Member Variable
When studying pointers to functions, we learned to use a programmer's type-defined declaration to create an alias to a pointer to function. We used an example such as the following: typedef double (*Multiply)(const double a); With this declaration, the word Multiply can be used in place of a function that takes a doubleprecision value as argument and the function returns a double. We learned that such a Multiply name could be used to declare a variable that in fact would be used as a function. Based on this feature of the C++ language, the Multiply name can also be used to declare a member variable of an object. Such a member variable would be interpreted as a function. The declaration can be done as follows: typedef double (*Multiply)(const double a);

struct TSquare { Multiply Perimeter; }; As done with the regular pointer to function, you do not implement the Perimeter method. In fact, so far, the compiler does not know what to do with the Perimeter member. Therefore, you must formally define a function that can implement the behavior that the Perimeter member is supposed to use. Such a function can be defined as follows: double Perimetre(const double x) { return x * 4; } Even with this definition of the Perimetre() function, there is no relationship between the Perimeter member of the TSquare class and the Perimetre() independent function, and the compiler does not see any relationship between them. This means that, until you join these two functions, the compiler would not know what to do with the member of the object. To use the Perimeter member of the TSquare object, you should first assign it an appropriate function that has the same signature as its alias. Then you can use the member of the class as if it were a regular method of the object. Here is an example of how this would be done: //--------------------------------------------------------------------------#include <iostream> using namespace std;

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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
typedef double (*Multiply)(const double a); //--------------------------------------------------------------------------struct TSquare { Multiply Perimeter; }; //--------------------------------------------------------------------------double Perimetre(const double x) { return x * 4; } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TSquare Sqr;

double Side = 25.55; Sqr.Perimeter = Perimetre;

cout << "Square Characteristics"; cout << "\nSide: " << Side;

cout << "\nPerimeter: " << Sqr.Perimeter(Side);

return 0; } //--------------------------------------------------------------------------Using this same approach, you can declare different types of pointers to function as you see fit and using the function signature of your choice. Keep in mind that, when an alias is used to declare a variable, because it is declaring a variable type and not a function, you cannot create various aliases with the same name. This causes a name conflict, even if you try using different function signatures. Here is an example: //--------------------------------------------------------------------------#include <iostream>

using namespace std;

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

typedef double (*Multiply)(const double a); typedef double (*Multiple)(const double x, const double y); //--------------------------------------------------------------------------struct TSquare { Multiply Perimeter; Multiple Area; };

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//--------------------------------------------------------------------------double Perimetre(const double x) { return x * 4; } //--------------------------------------------------------------------------double Surface(const double x, const double y) { return x * y; } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TSquare Sqr;

double Side = 25.55; Sqr.Perimeter = Perimetre; Sqr.Area = Surface;

cout << "Square Characteristics"; cout << "\nSide: " << Side;

cout << "\nPerimeter: " << Sqr.Perimeter(Side); cout << "\nArea: " << Sqr.Area(Side, Side);

return 0; } //---------------------------------------------------------------------------

Pointers to Method
Many of the functions and classes you will be using when creating applications are from already existing libraries. The idea is to reduce your efforts and be a little faster and productive. You also will be creating a lot of functions and classes. Once you have created such functionalities, there will be no reason to always write the same code over and over again. For example, if you had previously created a class that can process a rectangle object, it would not be good to create a new rectangle class when you need one, you can just refer to one of your classes that can do the job. Code reuse is a tremendous feature of object oriented programming and you should take advantage of it. We have just learned that you can use a pointer to function to declare a member or members of an object. We learned that, to do this, you must have a function that would implement the desired functionality of the member variable. What about the reverse? Can you create a pointer to a method and use it as a declarable type? The C++ language allows you to use a member function of an object as pointer to function. To do this, the C++ language require that the name of the method be fully qualified because the compiler would need to know which object possesses that method. The syntax you would use to create such an alias is: typedef ReturnType (ClassName::*VariableName)(Arguments, if any); The typedef keyword lets the compiler know that you are creating an alias. The return type must be either a regular data type (int, char, double and their variants) or an object (class a struct). Between the first parentheses, provide the name of the object (class or structure) that "owns" the method whose alias you want to create. The VariableName is a valid C++

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
name of a variable (and not the function member). If the method takes argument(s), you can provide the type(s) of argument(s) in the second parentheses. If the method does not take any argument, leave the (second) parentheses empty. Imagine you create a special class that would regularly help you perform arithmetic operations. Such a class can be structured as follows: class TArithmetic { public: double Addition(double Value1, double Value2); double Subtraction(double Value1, double Value2); double Multiplication(double Value1, double Value2); double Division(double Numerator, double Denominator); }; Imagine that, in your program, you want to perform an addition of two values and produce a result. You can create an alias to the Addition method as follows: typedef double (TArithmetic::*Add)(double x, double y); With this definition, the word Add can be used in place of a function that takes two doubleprecision values as arguments and returns a real value. To use this alias, you must point it to the desired method of the object. This can be done as follows: Add Plus = &TArithmetic::Addition; Now, the name Plus can be used to call the Addition() method of the TArithmetic class. Of course, because using a class, you must first declare a variable from it. Because Plus is in fact a pointer, you must call it as such. Here is an example of how Plus can be used as a function: //--------------------------------------------------------------------------#include <iostream>

using namespace std;

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

class TArithmetic { public: double Addition(double Value1, double Value2); double Subtraction(double Value1, double Value2); double Multiplication(double Value1, double Value2); double Division(double Numerator, double Denominator); }; //--------------------------------------------------------------------------double TArithmetic::Addition(double Val1, double Val2) { return Val1 + Val2; } //--------------------------------------------------------------------------double TArithmetic::Subtraction(double Val1, double Val2) { return Val1 - Val2; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//--------------------------------------------------------------------------double TArithmetic::Multiplication(double Val1, double Val2) { return Val1 * Val2; } double TArithmetic::Division(double Num, double Den) { if( Den == 0 ) return 0; // else is implied return Num / Den; } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { typedef double (TArithmetic::*Add)(double x, double y);

TArithmetic Oper; Add Plus = &TArithmetic::Addition;

double APlusB = (Oper.*Plus)(244, 125);

cout << "244 + 125 = " << APlusB;

return 0; } //--------------------------------------------------------------------------When we studied pointers to functions, we learned to declare them as follows:

double (*Add)(double x, double y); It would be a good idea to use this alias as a pointer to methods of a class. This could be done as follows: //--------------------------------------------------------------------------int main(int argc, char* argv[]) { double (*Add)(double x, double y);

TArithmetic Oper; Add = Oper.Addition;

double APlusB = Add(244, 125);

cout << "244 + 125 = " << APlusB;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return 0; } //---------------------------------------------------------------------------

Objects and Pointers to Function


As mentioned already when studying pointers to functions, callback functions are heavily used in Microsoft Windows programming. Besides the regular variables, these functions, called procedures, can take objects as argument. These functions are a little more restrictive. A pointer to function is a type of function whose name can be assigned to a variable as if it were a regular variable. This eases their use in Win32 procedures and VCL's events. The syntax of declaring a pointer to function is: DataType (*FunctionName)(ObjectName); The DataType is the kind of value the function will return. The FunctionName must be a valid name for a function. Because you are creating a pointer to function, the name of the function must be followed by an asterisk. This time, unlike pointer to functions of void or other regular data types, a pointer to function that involves an object type must necessarily have at least one argument of class or structure type. To illustrate this use of pointers to function, we will take an example:

On a Cartesian coordinate system, a line is known as a junction of two points. One of the operations you can perform on such a line is to calculate its length. The equation used is:

To calculate this distance, you can declare a function that would take two points as arguments. This function can be implemented and tested as follows: //--------------------------------------------------------------------------#include <iostream> #include <math.h>

using namespace std;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//---------------------------------------------------------------------------

namespace Geometry { struct TPoint { double x; double y; TPoint(double X=0, double Y=0) : x(X), y(Y) {} }; } //--------------------------------------------------------------------------double Distance(Geometry::Point Pt1, Geometry::Point Pt2) { double L1 = pow(Pt2.x - Pt1.x, 2); double L2 = pow(Pt2.y - Pt1.y, 2); return sqrt(L1 + L2); } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { Geometry::Point P(-3, 2); Geometry::Point Q(4, -1); double Length = Distance(P, Q);

cout << "The distance between P(-3, 2) and Q(4, -1) is " << Length;

return 0; } //--------------------------------------------------------------------------On a Cartesian coordinate system, a triangle is represented by three points:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Because this definition does not distinguish a particular type of triangle, it allows calculating the perimeter of a triangle, which is simply done by adding the lengths of the three sides. To perform this calculation, you can create a function that takes three points as arguments. Because a function that performs the distance calculation is already available, you can pass three of its pointers to the new function. Each argument is passed as a pointer to a function that takes two Point objects. After specifying the arguments, pass the necessary arguments that will actually be passed to the function that performs the distance calculations. Such a function can be declared as follows: double Perimeter(double (*Length1)(Point A, Point B), double (*Length2)(Point B, Point C), double (*Length3)(Point A, Point C), Point First, Point Second, Point Third); To implement this function, you must call the Distance function for each argument passed as pointer to function. Other than than, you would follow the same rules for implementing functions. Our Perimeter() function can be implemented as follows: //--------------------------------------------------------------------------double Perimeter( double (*Length1)(Point A, Point B), double (*Length2)(Point B, Point C), double (*Length3)(Point A, Point C), Point First, Point Second, Point Third ) { double AB = (*Length1)(First, Second); double BC = (*Length2)(Second, Third); double AC = (*Length3)(First, Third); return AB + BC + AC; } //--------------------------------------------------------------------------So far, the compiler does not know how the calculations are performed for the calls in the Perimeter() function. You let the compiler know this when calling the Perimeter() function. In this case, you provide the name of each function that performs the needed calculation. For our example, the name of the function is Distance. Therefore, you would pass it three times. In the function call, the name of the function is used because the actual argument is a pointer to function. The Perimeter() function can be tested as follows:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//--------------------------------------------------------------------------#include <iostream> #include <math.h>

using namespace std;

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

namespace Geometry { struct TPoint { double x; double y; TPoint(double X=0, double Y=0) : x(X), y(Y) {} }; } //--------------------------------------------------------------------------double Distance(Geometry::Point Pt1, Geometry::Point Pt2) { double L1 = pow(Pt2.x - Pt1.x, 2); double L2 = pow(Pt2.y - Pt1.y, 2); return sqrt(L1 + L2); } //--------------------------------------------------------------------------using namespace Geometry; double Perimeter( double (*Length1)(Point A, Point B), double (*Length2)(Point B, Point C), double (*Length3)(Point A, Point C), Point First, Point Second, Point Third ) { double AB = (*Length1)(First, Second); double BC = (*Length2)(Second, Third); double AC = (*Length3)(First, Third); return AB + BC + AC; } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { Geometry::Point Pt1(-3, -2); Geometry::Point Pt2(2, -2); Geometry::Point Pt3(4, 2);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
double Perim = Perimeter(Distance, Distance, Distance, Pt1, Pt2, Pt3);

cout << "Perimeter: " << Perim << endl;

return 0; } //--------------------------------------------------------------------------This would produce: Perimeter: 17.5344

Press any key to continue... To simplify the declaration of the function that takes an argument as pointer to function, you can type define the argument using the typedef keyword. This can be done as follows: //--------------------------------------------------------------------------#include <iostream> #include <math.h>

using namespace std;

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

namespace Geometry { struct TPoint { double x; double y; TPoint(double X=0, double Y=0) : x(X), y(Y) {} }; } //--------------------------------------------------------------------------double Distance(Geometry::Point Pt1, Geometry::Point Pt2) { double L1 = pow(Pt2.x - Pt1.x, 2); double L2 = pow(Pt2.y - Pt1.y, 2); return sqrt(L1 + L2); } //--------------------------------------------------------------------------typedef double (*SideLength)(Geometry::Point First, Geometry::Point Second); double Perimeter(SideLength, SideLength, SideLength, Geometry::Point First, Geometry::Point Second, Geometry::Point Third );

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//--------------------------------------------------------------------------using namespace Geometry;

int main(int argc, char* argv[]) { Point Pt1(-3, -2); Point Pt2( 2, -2); Point Pt3( 4, 2);

double Perim = Perimeter(Distance, Distance, Distance, Pt1, Pt2, Pt3);

cout << "Perimeter: " << Perim << endl;

return 0; } //--------------------------------------------------------------------------double Perimeter( double (*Length1)(Point A, Point B), double (*Length2)(Point B, Point C), double (*Length3)(Point A, Point C), Point First, Point Second, Point Third ) { double AB = (*Length1)(First, Second); double BC = (*Length2)(Second, Third); double AC = (*Length3)(First, Third); return AB + BC + AC; } //--------------------------------------------------------------------------In this program, SideLength is another name for a pointer to function that takes two Point as arguments. Based on this approach, you can also calculate the Perimeter of a rectangle or any quadratic or other geometric figure whose corners can be identified on a Cartesian coordinate system:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Classes and Self-Return


Self Returning an Object
The constructors are not the only member functions that can be declared with the name of the class. C++ allows you to manipulate the members of a class without using an external function. This technique uses a member function that can return the parent class. To have a function that can refer to the object itself, in the body of the class, declare a method that holds the same name as the class, followed by a valid name of a function and the parentheses. Here is an example: //-------------------------------------------------------------------------#ifndef FlatShapesH #define FlatShapesH //-------------------------------------------------------------------------namespace FlatShapes { struct TTriangle { private: double TriBase; double TriHeight; double getBase() const; void setBase(const double B);

double getHeight() const; void public: void setDimensions(const double B, const double H); setHeight(const double H);

TTriangle(); TTriangle(double B, double H); TTriangle(const TTriangle &Tri); ~TTriangle();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
double Area() const { return TriBase * TriHeight / 2; }

TTriangle Additional();

__property double Base = { read = getBase, write = setBase }; __property double Height = { read = getHeight, write = setHeight }; }; } //-------------------------------------------------------------------------#endif An example of using such a function would consist of changing the value of each member of the class. Since the function is declared as returning the value of the same variable, you can implement it as follows: //--------------------------------------------------------------------------

#include "FlatShapes.h" //--------------------------------------------------------------------------

//-------------------------------------------------------------------------namespace FlatShapes { TTriangle::TTriangle() : TriBase(0.00), TriHeight(0.00) { } //-------------------------------------------------------------------------TTriangle::TTriangle(double B, double H) : TriBase(B), TriHeight(H) { } //-------------------------------------------------------------------------TTriangle::TTriangle(const TTriangle &Tri) : TriBase(Tri.TriBase), TriHeight(Tri.TriHeight) { } //-------------------------------------------------------------------------TTriangle::~TTriangle() { } //-------------------------------------------------------------------------double TTriangle::getBase() const

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ return (TriBase < 0 ) ? 0 : TriBase; } //-------------------------------------------------------------------------void { TriBase = ( B < 0 ) ? 0 : B; } //-------------------------------------------------------------------------double TTriangle::getHeight() const { return (TriHeight < 0) ? 0 : TriHeight; } //-------------------------------------------------------------------------void { TriHeight = (H < 0 ) ? 0 : H; } //-------------------------------------------------------------------------void { setBase(B); setHeight(H); } //-------------------------------------------------------------------------TTriangle TTriangle::Additional() { TTriangle Tri; TTriangle::setDimensions(const double B, const double H) TTriangle::setHeight(double H) TTriangle::setBase(double B)

// The constant double values used here were randomly chosen Tri.TriBase = TriBase + 12.52;

Tri.TriHeight = TriHeight + 8.95;

return Tri; } //-------------------------------------------------------------------------} Calling this self-returning function is equivalent to changing the values of the member variables, as illustrated when called in the main() function: //-------------------------------------------------------------------------#include <iostream>

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#include "FlatShapes.h"

//-------------------------------------------------------------------------using namespace std; using namespace FlatShapes;

void ShowCharacteristics(const TTriangle*); //-------------------------------------------------------------------------int main(int argc, char* argv[]) { TTriangle Angular;

Angular.setDimensions(22.44, 26.38); ShowCharacteristics(&Angular);

cout << endl << endl; TTriangle Plane = Angular.Additional(); ShowCharacteristics(&Plane);

return 0; } //-------------------------------------------------------------------------void ShowCharacteristics(const TTriangle* Tri) { cout << " - Triangle Characteristics -"; cout << "\nBase: " << Tri->Base;

cout << "\nHeight: " << Tri->Height; cout << "\nArea: } //-------------------------------------------------------------------------You can use this ability to declare almost any type of function that returns the same class. One particular method can be used to modify the default values of the member variables. Another method can be used to convert the values of another class into those needed by the class. " << Tri->Area();

The this Pointer


C++ proposes an alternative to returning an object from one of its member functions. Instead of explicitly declaring a variable when implementing a function that returns the same object, the compiler simply needs to know what object you want to return: the object that called the method or a newly declared one. If you want to return the same object, you can use a special pointer called this. As its name implies, the this pointer is a self referencing object, which means it allows you to designate the object that is making the call as the same object you are referring to. Using the this pointer is a technique that allows you to perform any necessary operation on an object without the help of an external function and returning the same object. Suppose you want to transform the Additional() method of the TTriangle object above so it

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
would return the same variable that calls it. Because the method will return the same object, you do not need to declare a local variable to hold the changed variable. Since the member variables of the object will be modified, the member function cannot be declared as a constant. When implementing this method, the values of the variables will certainly be modified to implement whatever behavior you want. To return the same object, the this object must be called as a pointer, with *this. Here is the new implementation of the function: //-------------------------------------------------------------------------TTriangle TTriangle::Additional() { // The constant double values used here were randomly chosen Tri.TriBase = TriBase + 12.52;

Tri.TriHeight = TriHeight + 8.95;

return *this; } //-------------------------------------------------------------------------Using the same approach, you can define and use other methods that return the same object: //-------------------------------------------------------------------------#ifndef FlatShapesH #define FlatShapesH //-------------------------------------------------------------------------namespace FlatShapes { struct TTriangle { private: double TriBase; double TriHeight; double getBase() const; void setBase(const double B);

double getHeight() const; void public: void setDimensions(const double B, const double H); setHeight(const double H);

TTriangle(); TTriangle(double B, double H); TTriangle(const TTriangle &Tri); ~TTriangle(); double Area() const { return TriBase * TriHeight / 2; }

TTriangle Additional(); TTriangle AddAConstant(const double d); TTriangle AddAnotherObject(const TTriangle& E);

__property double Base = { read = getBase, write = setBase }; __property double Height = { read = getHeight, write = setHeight

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
}; }; } //-------------------------------------------------------------------------#endif Such methods can be implemented to return the this pointer and the same object that made the call: //--------------------------------------------------------------------------

#include "FlatShapes.h" //--------------------------------------------------------------------------

//-------------------------------------------------------------------------namespace FlatShapes { . . . No Change //-------------------------------------------------------------------------TTriangle TTriangle::Additional() { // The constant double values used here were randomly chosen TriBase = TriBase + 12.52;

TriHeight = TriHeight + 8.95;

return *this; }

//-------------------------------------------------------------------------TTriangle TTriangle::AddAConstant(const double d) { TriBase = TriBase + d;

TriHeight = TriHeight + d;

return *this; } //-------------------------------------------------------------------------TTriangle TTriangle::AddAnotherObject(const TTriangle& E) { TriBase += E.TriBase;

TriHeight += E.TriHeight;

return *this;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} //-------------------------------------------------------------------------} Since the function that returns the this pointer returns it as a pointer, you can reinforce the fact that the variable that is being returned is modified. Therefore, instead of returning the object as a regular variable, you should make the returned value a reference: //-------------------------------------------------------------------------#ifndef FlatShapesH #define FlatShapesH //-------------------------------------------------------------------------namespace FlatShapes { struct TTriangle { private: double TriBase; double TriHeight; double getBase() const; void setBase(const double B);

double getHeight() const; void public: void setDimensions(const double B, const double H); setHeight(const double H);

TTriangle(); TTriangle(double B, double H); TTriangle(const TTriangle &Tri); ~TTriangle(); double Area() const { return TriBase * TriHeight / 2; }

TTriangle& Additional(); TTriangle& AddAConstant(const double d); TTriangle& AddAnotherObject(const TTriangle& E);

__property double Base = { read = getBase, write = setBase }; __property double Height = { read = getHeight, write = setHeight }; }; } //-------------------------------------------------------------------------#endif In this case, remember to use the reference operator, the ampersand: //-------------------------------------------------------------------------TTriangle& TTriangle::Additional() { // The constant double values used here were randomly chosen

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
TriBase = TriBase + 12.52;

TriHeight = TriHeight + 8.95;

return *this; }

//-------------------------------------------------------------------------TTriangle& TTriangle::AddAConstant(const double d) { TriBase = TriBase + d;

TriHeight = TriHeight + d;

return *this; } //-------------------------------------------------------------------------TTriangle& TTriangle::AddAnotherObject(const TTriangle& E) { TriBase += E.TriBase;

TriHeight += E.TriHeight;

return *this; } //--------------------------------------------------------------------------

Previous

Copyright 2005 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Operator Overloading
Overloading an Operator
Introduction
Operator overloading is the ability to tell the compiler how to perform a certain operation when its corresponding operator is used on one or more variables. For example, the compiler acts differently with regards to the subtraction operator - depending on how the operator is being used. When it is placed on the left of a numeric value such as -48, the compiler considers the number a negative value. When used between two integral values, such as 80-712, the compiler applies the subtraction operation. When used between an integer and a double-precision number, such as 558-9.27, the compiler subtracts the left number from the right number; the operation produces a double-precision number. When the - symbol is doubled and placed on one side of a variable, such as --Variable or Variable--, the value of the variable needs to be decremented; in other words, the value 1 shall be subtracted from it. All of these operations work because the subtraction operator - has been reconfigured in various classes to act appropriately. Suppose you create a class named TCountry as follows:
//--------------------------------------------------------------------------struct TCountry { string Name; double Population; long double Area; string Capital; char Government; }; //---------------------------------------------------------------------------

Suppose you declare two TCountry variables such as:


TCountry SriLanka, BanglaDesh;

If you write an expression such as SriLanka + BanglaDesh and want to display the result, the compiler would need to know what you are trying to achieve. Do you want to add the names of the countries and create a new string name? Do you want to get the result of their combined populations, or the total or their areas? Operator overloading allows you to help the compiler perform this type of operation when it is applied on your object(s).

Defaults Methods: A Review


When studying constructors, we learned that, whenever you create an object, the compiler automatically creates some of its necessary methods. For example, you can create a TSquare class as follows:
//--------------------------------------------------------------------------#include <iostream> #include <iomanip> using namespace std; //--------------------------------------------------------------------------struct TSquare { public:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
void setSide(const double s) { Side = s; } double getSide() const { return Side; } double Perimeter() const { return 4 * Side; } double Area() const { return Side * Side; } private: double Side; }; //--------------------------------------------------------------------------void Properties(const TSquare& Carre) { cout << "Properties of the square"; cout << setiosflags(ios::fixed) << setprecision(2); cout << "\nSide: " << Carre.getSide();

cout << "\nPerimeter: " << Carre.Perimeter(); cout << "\nArea: } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TSquare CupHolder; " << Carre.Area();

CupHolder.setSide(35.55); Properties(CupHolder);

return 0; } //---------------------------------------------------------------------------

To start, if you do not create a constructor, the compiler would create one for you. This is called the default constructor. Otherwise, you can create your own:
//--------------------------------------------------------------------------struct TSquare { public: TSquare(); void setSide(const double s) { Side = s; } double getSide() const { return Side; } double Perimeter() const { return 4 * Side; } double Area() const { return Side * Side; } private: double Side; };

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//--------------------------------------------------------------------------TSquare::TSquare() { } //---------------------------------------------------------------------------

In the same way, if you do not create a destructor, the compiler would also create one for you. Otherwise, you can create your own destructor:
//--------------------------------------------------------------------------struct TSquare { public: TSquare(); virtual ~TSquare(); void setSide(const double s) { Side = s; } double getSide() const { return Side; } double Perimeter() const { return 4 * Side; } double Area() const { return Side * Side; } private: double Side; }; //--------------------------------------------------------------------------TSquare::TSquare() { } //--------------------------------------------------------------------------TSquare::~TSquare() { } //---------------------------------------------------------------------------

To allow making copies of objects, the compiler also creates an appropriate constructor for you if you do not define one for your object. This is called the copy constructor. You can still explicitly create one as follows:
//--------------------------------------------------------------------------struct TSquare { public: TSquare(); TSquare(const TSquare& Q); virtual ~TSquare(); void setSide(const double s) { Side = s; } double getSide() const { return Side; } double Perimeter() const { return 4 * Side; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
double Area() const { return Side * Side; } private: double Side; }; //--------------------------------------------------------------------------TSquare::TSquare() { } //--------------------------------------------------------------------------TSquare::TSquare(const TSquare& Sq) : Side(Sq.Side) { } //--------------------------------------------------------------------------TSquare::~TSquare() { } //---------------------------------------------------------------------------

In reality, there are four default functions that the compiler creates for you if you do not define them yourself. Besides the default constructor, the copy constructor, and the destructor, the compiler also create an overloaded assignment operator function for you. This can be easily seen on the code completion if you have not yet created this function for an object: So far, we have been able to assign a variable declared from a class to another variable of the same type. Here is an example:
//--------------------------------------------------------------------------void Properties(const TSquare& Carre) { cout << "Properties of the square"; cout << setiosflags(ios::fixed) << setprecision(2); cout << "\nSide: " << Carre.getSide();

cout << "\nPerimeter: " << Carre.Perimeter(); cout << "\nArea: } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TSquare Holder, Loop; " << Carre.Area();

Holder.setSide(35.55); Properties(Holder); cout << "\n\n";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Loop.setSide(18.04); TSquare Base(Loop); Properties(Base); cout << "\n\n";

TSquare Sink = Holder; Properties(Sink);

return 0; } //---------------------------------------------------------------------------

This assignment operation is possible because the compiler is configured to take care of it, using its own default created overloaded assignment operator function.

Overloading an Operator
The C++ language recognizes 45 operators of various types. The most usual and the most regular operator is the output extraction operator << used to display anything in C++. The input >> operator is used to retrieve data input. Arithmetic operators are used to perform numeric operations. The unary operators are used to control the sign or behavior of a variable. There are many other binary and C++ specific operators. When customized, the arithmetic and any other operators can be applied to varying circumstances. When overloaded, the operators are implemented as functions using the operator keyword. For example, the syntax of overloading the addition operator + would be operator+().

Overloading the Operators


The Assignment Operator
The assignment operator works by giving the value of one variable to another variable of the same type or closely similar. Suppose you declare two integer variables as follows:
//--------------------------------------------------------------------------#include <iostream> using namespace std; //---------------------------------------------------------------------------

int main(int argc, char* argv[]) { double A, B;

cout << "Values of variables"; cout << "\nA: " << A; cout << "\nB: " << B;

return 0; } //---------------------------------------------------------------------------

In reality (that is, on a different compiler, such as MSVC), this would produce:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Values of variables A: 2.122e-314 B: 2.53936e-314

As you can see, as long as a variable is not initialized, it holds a garbage value. Suppose you initialize the A variable as follows:
//--------------------------------------------------------------------------#include <iostream> using namespace std; //---------------------------------------------------------------------------

int main(int argc, char* argv[]) { double A, B;

A = 266.52; cout << "Values of variables"; cout << "\nA: " << A; cout << "\nB: " << B;

return 0; } //---------------------------------------------------------------------------

This would produce:


Values of variables A: 266.52 B: 2.53936e-314

This time, once a variable has been initialized, it holds the appropriate value. Notice that the B variable that has not been initialized is still holding garbage. If you want to give the value of one variable to another variable, you can use the = operator between them as follows:
//--------------------------------------------------------------------------#include <iostream> using namespace std; //---------------------------------------------------------------------------

int main(int argc, char* argv[]) { double A, B;

A = 266.52; cout << "Values of variables"; cout << "\nA: " << A;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\nB: " << B;

A = B;

cout << "\n\nValues of variables"; cout << "\nA: " << A; cout << "\nB: " << B;

return 0; } //---------------------------------------------------------------------------

The = sign implements the assignment operation. It works on two variables, one on each side of the symbol. After it has operated, the value that the right variable holds is given to the left variable. An example of executing the above program would be:
Values of variables A: 266.52 B: 2.53936e-314

Values of variables A: 2.53936e-314 B: 2.53936e-314

Notice that although the A variable had been initialized previously, by assigning it to another variable, its value changes. On its second call, the A variable has lost its previous variable and holds whatever value the B variable was given. If you want to assign the value of A to B, you would write:
//--------------------------------------------------------------------------#include <iostream> using namespace std; //---------------------------------------------------------------------------

int main(int argc, char* argv[]) { double A, B;

A = 266.52; cout << "Values of variables"; cout << "\nA: " << A; cout << "\nB: " << B;

B = A;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\n\nValues of variables"; cout << "\nA: " << A; cout << "\nB: " << B;

return 0; } //---------------------------------------------------------------------------

The first time the variables are called, the initialized A variable displays a recognizable value while B is still holding garbage. After B has been initialized, on the second call, both variables hold the same value:
Values of variables A: 266.52 B: 2.53936e-314

Values of variables A: 266.52 B: 266.52

To use the assignment operator on your own object, you should (or must) let the compiler know how to handle the assignment operator on a variable declared from such an object. To do this, create your own implementation of the assignment operator. The assignment operator is defined using the operator keyword followed by the = symbol and the traditional parentheses of every function. As a function, the operator must be declared in the body of the class, along with the other method members. In order for this function to be accessible outside of the class, it should be listed in the public section. Like any member method, the function should have a return value, at least void. Therefore it could be created as follows:
//---------------------------------------------------------------------------

#ifndef RectangleH #define RectangleH //--------------------------------------------------------------------------class TRectangle { public: TRectangle(double L = 0.00, double H = 0.00) : Length(L), Height(H) {} TRectangle(const TRectangle& R) : Length(R.Length), Height(R.Height) {} ~TRectangle() {} void setLength(const double L) { Length = L; } double getLength() const { return Length; } void setHeight(const double H) { Height = H; } double getHeight() const { return Height; } double Perimeter() const { return 2 * (Length + Height); } double Area() const { return Length * Height; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
void operator=(); private: double Length; double Height; }; //--------------------------------------------------------------------------#endif

We saw earlier that, to perform an assignment, one variable is given the value of another, similar, variable, as in Var1 = Var2. The variable on the right is given the value of the variable on the left. For this operation, we must have a source variable (right) whose value we want to assign to the other variable (left). We must make sure that this source variable is the same type as the value we are trying to get; otherwise, the compiler would not be able to perform the operation. Therefore, the source variable will be provided as argument to the function; and this argument must be the same as the class on which the operation is applied. For this reason, the function operator can be created as:
void operator=(TRectangle Rect);

To assign one variable to another, there must be a correspondence between a member of the source variable and a member of the target or left variable. Therefore, the function operator can be implemented as follows:
//--------------------------------------------------------------------------void TRectangle::operator=(TRectangle Rect) { Length = Rect.Length; Height = Rect.Height; } //---------------------------------------------------------------------------

The assignment operator is simply used to assign the value of a source variable to another variable. During this operation, the value of the source variable is not modified. Therefore, the argument should be passed as a constant. This changes the function to:
void operator=(const TRectangle Rect);

To speed up the retrieval of the value of the argument, you can let the compiler access the value of the argument directly to its address. This is done by passing the argument as reference. Since the argument is (also) passed as a constant, there is no modification of the value of the argument. The function can be declared as:
void operator=(const TRectangle& Rect);

We saw earlier that when one variable is assigned to another, as in B = A, the value of the source variable A is given to the target or left variable B. This means that, after the operation, the function should return a non-void variable. Since the new value of the variable must be the same as the source variable, the function should return a variable of the same class. The operator function would become:
TRectangle operator=(const TRectangle& Rect);

When a variable is assigned a value, its own value must change, regardless of the value it was holding; we saw this earlier when we called the A variable after it had been assigned the value of B. Therefore, the operation should return a reference to the type of object. This changes the decclaration of the function to:
TRectangle& operator=(const TRectangle& Rect);

From this, the function must return a value, since it is not defined with void anymore. The assignment operation is performed from one object to another object of the same kind. This means the function must return the same variable that called it. Therefore, the function must return the this pointer. Here is the correct implementation of the function:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//--------------------------------------------------------------------------TRectangle& TRectangle::operator=(const TRectangle& Rect) { Length = Rect.Length; Height = Rect.Height;

return *this; } //---------------------------------------------------------------------------

Overloading the Arithmetic Operators


In C++, the addition operation is applied with the + symbol. Depending on the circumstance, it can be considered a unary or a binary operator. It is used as a unary operator when applied to one variable. The addition binary operator is used on two variables to add their values. Suppose you have two variables A and B. To add their values, you would type A + B. You can display such a value on the console as follows:
//--------------------------------------------------------------------------#include <iostream> using namespace std; //---------------------------------------------------------------------------

int main(int argc, char* argv[]) { double A, B;

A = 1266.52; B = 3520.46;

cout << "Values of variables"; cout << "\nA = " << A; cout << "\nB = " << B; cout << "\nA + B = " << A + B;

return 0; } //---------------------------------------------------------------------------

As you can see, the binary addition operator is performed on two variables. To apply it on a class, you must create a function operator that takes two arguments. Since the values of the arguments will not be modified, you should pass them as constant references. The function can be declared as follows:
//--------------------------------------------------------------------------#ifndef RectangleH

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#define RectangleH //--------------------------------------------------------------------------class TRectangle { public: TRectangle(double L = 0.00, double H = 0.00) : Length(L), Height(H) {} ... TRectangle& operator=(const TRectangle& Rect); void operator+(const TRectangle& x, const TRectangle& y); private: double Length; double Height; }; //--------------------------------------------------------------------------#endif

To implement the function, you would add the values of the arguments. When performing this operation, there must be a correspondence between a variable of one argument and the equivalent variable of the other argument. Therefore, you would implement the function as follows:
//--------------------------------------------------------------------------void TRectangle::operator+(const TRectangle& x, const TRectangle& y) { x.Length + y.Length; x.Height + y.Height; } //---------------------------------------------------------------------------

If you execute the program with the function declared in the public section, you would get an error because C++ does not allow a binary operator to be overloaded (with two or more arguments) in a class. The solution is to declare the function outside of the class. The problem is that, to perform this binary operation, you will need access to the private or protected members of the class. Therefore, the operator function must be declared as a friend of the class:
//--------------------------------------------------------------------------#ifndef RectangleH #define RectangleH //--------------------------------------------------------------------------class TRectangle { friend void operator+(const TRectangle& x, const TRectangle& y);

public: TRectangle(double L = 0.00, double H = 0.00) : Length(L), Height(H) {}

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
... TRectangle& operator=(const TRectangle& Rect); private: double Length; double Height; }; //--------------------------------------------------------------------------#endif

Since the operator+() is not a member of the class anymore, its implementation becomes:
//--------------------------------------------------------------------------void operator+(const TRectangle& x, const TRectangle& y) { x.Length + y.Length; x.Length + y.Length; } //---------------------------------------------------------------------------

With this implementation of the function, the compiler does not complain anymore and the compilation is smooth. Also, it is now safe to add two variables declared from the TRectangle class:
//--------------------------------------------------------------------------int main(int argc, char* argv[]) { TRectangle Rect(42.88, 36.14);

TRectangle Recto; Recto + Rect;

return 0; } //---------------------------------------------------------------------------

Since the operator+() function is declared as void, which means it does not return any value, it does not provide a value that can be displayed on the console. For example the following does not make sense:
//--------------------------------------------------------------------------int main(int argc, char* argv[]) { TRectangle Rect(42.88, 36.14); TRectangle Recto(16.52, 22.65);

cout << Recto + Rect;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

return 0; } //---------------------------------------------------------------------------

Refering to the former program that added A and B, instead of displaying the result of A + B on the console, you might want to store it in another variable. To do that, you would perform the addition and then assign the result to another variable. The assignment would appear as follows:
//--------------------------------------------------------------------------#include <iostream> using namespace std; //---------------------------------------------------------------------------

int main(int argc, char* argv[]) { double A, B, C;

A = 1266.52; B = 3520.46; C = A + B;

cout << "Values of variables"; cout << "\nA = " << A; cout << "\nB = " << B; cout << "\nC = " << C;

return 0; } //---------------------------------------------------------------------------

This demonstrates that the binary addition applied on two variables in fact provides a third result; and this result is a variable of the same type. In other words, after performing the addition, the operator+() function must return a variable of the same type. The function should return TRectangle and can be declared as follows:
//--------------------------------------------------------------------------#ifndef RectangleH #define RectangleH //--------------------------------------------------------------------------class TRectangle { friend TRectangle operator+(const TRectangle& x, const TRectangle& y);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

public: TRectangle(double L = 0.00, double H = 0.00) : Length(L), Height(H) {} ... TRectangle& operator=(const TRectangle& Rect); private: double Length; double Height; }; //--------------------------------------------------------------------------#endif

This time, the function must return a variable of the same type. During its implementation, you can declare a new variable of the same type, assign each of its variables to the equivalent added variable of the arguments, and then return that variable. Here is an example:
//--------------------------------------------------------------------------TRectangle operator+(const TRectangle& x, const TRectangle& y) { TRectangle Room;

Room.Length = x.Length + y.Length; Room.Height = x.Height + y.Height;

return Room; } //---------------------------------------------------------------------------

Now we can add two TRectangle variables and store the result in another variable:
//--------------------------------------------------------------------------int main(int argc, char* argv[]) { TRectangle Rect(42.88, 36.14), Recto(16.52, 22.65), CDCase;

CDCase = Recto + Rect; cout << "Properties of the CD Case"; Properties(CDCase);

return 0; } //---------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
To declare the other arithmetic operators, use the same syntax. Here is the header file:
//--------------------------------------------------------------------------#ifndef RectangleH #define RectangleH //--------------------------------------------------------------------------class TRectangle { friend TRectangle operator+(const TRectangle& x, const TRectangle& y); friend TRectangle operator-(const TRectangle& x, const TRectangle& y); friend TRectangle operator*(const TRectangle& x, const TRectangle& y); friend TRectangle operator/(const TRectangle& x, const TRectangle& y); public: TRectangle(double L = 0.00, double H = 0.00) : Length(L), Height(H) {} TRectangle(const TRectangle& R) : Length(R.Length), Height(R.Height) {} ~TRectangle() {} void setLength(const double L) { Length = L; } double getLength() const { return Length; } void setHeight(const double H) { Height = H; } double getHeight() const { return Height; } double Perimeter() const { return 2 * (Length + Height); } double Area() const { return Length * Height; } TRectangle& operator=(const TRectangle& Rect);

private: double Length; double Height; }; //--------------------------------------------------------------------------#endif

The implementation of these functions also follows the same syntax applied to the addition operator:
//---------------------------------------------------------------------------

using namespace std;

#include "Rectangle.h" //---------------------------------------------------------------------------

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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
TRectangle& TRectangle::operator=(const TRectangle& Rect) { Length = Rect.Length; Height = Rect.Height;

return *this; } //--------------------------------------------------------------------------TRectangle operator+(const TRectangle& x, const TRectangle& y) { TRectangle R;

R.Length = x.Length + y.Length; R.Height = x.Height + y.Height;

return R; } //--------------------------------------------------------------------------TRectangle operator-(const TRectangle& x, const TRectangle& y) { TRectangle R;

R.Length = x.Length - y.Length; R.Height = x.Height - y.Height;

return R; } //--------------------------------------------------------------------------TRectangle operator*(const TRectangle& x, const TRectangle& y) { TRectangle R;

R.Length = x.Length * y.Length; R.Height = x.Height * y.Height;

return R; }//--------------------------------------------------------------------------TRectangle operator/(const TRectangle& x, const TRectangle& y) { TRectangle R;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
if( y.Length == 0 ) // Avoid a zero denominator R.Length = 0; else R.Length = x.Length / y.Length;

if( y.Height == 0 ) R.Height = 0; else R.Height = x.Height / y.Height;

return R; } //---------------------------------------------------------------------------

Adding a Constant to an Object


Using integers or floating numbers, we are used to adding a constant to a variable, as in the following:
//--------------------------------------------------------------------------#include <iostream> using namespace std; //---------------------------------------------------------------------------

int main(int argc, char* argv[]) { double A = 1266.52; double D;

D = A + 350.44; cout << "Values of variables"; cout << "\nA = " << A; cout << "\nD = " << D;

return 0; } //---------------------------------------------------------------------------

Suppose that, instead of adding two objects, you decide to add a constant number to a class variable, as follows:
//--------------------------------------------------------------------------int main(int argc, char* argv[]) { TRectangle Rect(42.88, 36.14);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
TRectangle Plate = Rect + 32.84;

cout << "\n\nProperties of the plate";

Properties(Plate);

return 0; } //---------------------------------------------------------------------------

By overloading the addition operator, you can apply this operation to a variable declared from a class. To add a constant to the variable, you must create a version of the operator+() function that would take a constant and add it to the desired variable. After the operation is performed, the function must return a new variable that holds the new value (if the function does not return a value, the operation would be useless; you cannot display it on the console and you cannot assign the result to another variable). Therefore, the function would be declared as follows:
//--------------------------------------------------------------------------#ifndef RectangleH #define RectangleH //--------------------------------------------------------------------------class TRectangle { friend TRectangle operator+(const TRectangle& x, const TRectangle& y);

public: TRectangle(double L = 0.00, double H = 0.00) : Length(L), Height(H) {} ... TRectangle& operator=(const TRectangle& Rect); TRectangle& operator+(const double d); private: double Length; double Height; }; //--------------------------------------------------------------------------#endif

The implementation of the function depends on what you are trying to achieve. For example, you can decide to add the constant value to only one member variable of the class. After performing the operation, the function must return the same variable on which it was applied, which is represented with the this pointer:
//--------------------------------------------------------------------------TRectangle& TRectangle::operator+(const double Number) {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Length = Length + Number; return *this; } //---------------------------------------------------------------------------

You can also add the constant argument to each member variable of the class:
//--------------------------------------------------------------------------TRectangle& TRectangle::operator+(const double Number) { Length = Length + Number; Height = Height + Number;

return *this; } //---------------------------------------------------------------------------

Once the compiler knows how to add a constant to a variable declared from your class, you can use the operation the same way you would proceed for an integer or floating variable:
//--------------------------------------------------------------------------int main(int argc, char* argv[]) { TRectangle Rect(42.88, 36.14), Recto(16.52, 22.65), CDCase;

CDCase = Recto + Rect; cout << "Properties of the CD Case"; Properties(CDCase); TRectangle Plate = Rect + 32.84;

cout << "\n\nProperties of the plate"; Properties(Plate);

return 0; } //---------------------------------------------------------------------------

The Sum Assignment Operator


In the past we learned that one way to add a value to a variable is by using the sum assignment operator applied to the variable itself. Here is an example:
//--------------------------------------------------------------------------#include <iostream> using namespace std; //---------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
int main(int argc, char* argv[]) { double A = 1266.52; double D = 560.25;

cout << "Values of variables"; cout << "\nA: " << A; cout << "\nD: " << D;

A += 350.44; cout << "\n\nAfter incrementing A, the values of variables are"; cout << "\nA: " << A; cout << "\nD: " << D;

return 0; } //---------------------------------------------------------------------------

The expression A += 350.44 is equivalent to A = A + 350.44. In other words, the constant value 350.44 is added to the variable A and renders the same variable A without the need of another variable. Besides adding a constant number to itself, a variable can also add the value of another variable of the same type to itself and thus modify the value it is holding. This is illustrated in the following:
//--------------------------------------------------------------------------#include <iostream> using namespace std; //---------------------------------------------------------------------------

int main(int argc, char* argv[]) { double A = 1266.52; double D = 560.25;

cout << "Values of variables"; cout << "\nA: " << A; cout << "\nD: " << D;

A += 350.44; cout << "\n\nAfter incrementing A, the values of variables are"; cout << "\nA: " << A; cout << "\nD: " << D;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

A += D; cout << "\n\nAfter self-adding D to A, the values of variables are"; cout << "\nA: " << A; cout << "\nD: " << D;

return 0; } //---------------------------------------------------------------------------

The += operation allows a variable to add a constant value to itself and change its (own) value after the operation. By default, this operation cannot be performed on a class. As we saw with adding a constant to a variable declared from a class, we can create our own version of the += operator to help the compiler figure out what to do when this operator is applied on our object. The function used to perform this operation would look as follows:
//--------------------------------------------------------------------------#ifndef RectangleH #define RectangleH //--------------------------------------------------------------------------class TRectangle { friend TRectangle operator+(const TRectangle& x, const TRectangle& y); friend TRectangle operator-(const TRectangle& x, const TRectangle& y); friend TRectangle operator*(const TRectangle& x, const TRectangle& y); friend TRectangle operator/(const TRectangle& x, const TRectangle& y);

public: ... TRectangle& operator=(const TRectangle& Rect); TRectangle& operator+(const double d); TRectangle& Adder(const TRectangle& x); void operator+=();

private: double Length; double Height; }; //--------------------------------------------------------------------------#endif

The addition assignment operator += works by assigning a value to a variable and hold a new value. The compiler will need to know what value is being added to the variable. Therefore, you

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
must provide an argument that specifies this value. If this value is a variable of the same type that is being worked on, you must provide it by changing the function as: void operator+=(TRectangle Rect); The value of such an argument will not be modified in the function; it will only serve as the source of the value that is being added. For this reason, it should be passed as a constant. As long as it is not being modified, to speed up code execution, you should pass it as reference. The function would then change to:
//--------------------------------------------------------------------------#ifndef RectangleH #define RectangleH //--------------------------------------------------------------------------class TRectangle { friend TRectangle operator+(const TRectangle& x, const TRectangle& y); friend TRectangle operator-(const TRectangle& x, const TRectangle& y); friend TRectangle operator*(const TRectangle& x, const TRectangle& y); friend TRectangle operator/(const TRectangle& x, const TRectangle& y);

public: ... TRectangle& operator=(const TRectangle& Rect); TRectangle& operator+(const double d); TRectangle& Adder(const TRectangle& x); void operator+=(const TRectangle& Rect); private: double Length; double Height; }; //--------------------------------------------------------------------------#endif

The implementation of this function simply consists, once more, of deciding what to add and what to leave out. For our example, we will add a member variable of the TRectangle variable that is making the call to the corresponding member variable of the argument:
//--------------------------------------------------------------------------void TRectangle::operator+=(const TRectangle& R) { Length += R.Length; Height += R.Height; } //---------------------------------------------------------------------------

After implementing this function, you can apply the += operator on a program as follows:
//--------------------------------------------------------------------------int main(int argc, char* argv[])

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ TRectangle Rect(42.88, 36.14), Recto(16.52, 22.65), Plate;

cout << "First Properties of Rect"; Properties(Rect);

Plate = Rect + 15.44; cout << "\n\nAfter adding a constant to the rectangle"; Properties(Plate);

Rect += Recto; cout << "\n\nSecond Properties of Rect"; Properties(Rect);

return 0; } //---------------------------------------------------------------------------

The += operator can also be applied by adding a constant value to the class variable that is making the call. The function can be declared as:
//--------------------------------------------------------------------------#ifndef RectangleH #define RectangleH //--------------------------------------------------------------------------class TRectangle { ... public: ... TRectangle& operator=(const TRectangle& Rect); TRectangle& operator+(const double d); TRectangle& Adder(const TRectangle& x); void operator+=(const double d); void operator+=(const TRectangle& Rect); private: double Length; double Height; }; //--------------------------------------------------------------------------#endif

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
You can implement the function by deciding what member function would be modified. For this example, we will add the constant argument to each member variable of the class variable that is making the call:
//--------------------------------------------------------------------------void TRectangle::operator+=(const double d) { Length += d; Height += d; } //---------------------------------------------------------------------------

Once again, you can apply this operator once the compiler knows what to do with it. Here is an example:
//--------------------------------------------------------------------------int main(int argc, char* argv[]) { TRectangle Rect(42.88, 36.14), Recto(16.52, 22.65), Plate;

cout << "First Properties of Rect"; Properties(Rect);

cout << "\n\nFirst call of the Plate rectangle"; Properties(Plate);

Plate += 15.44;

cout << "\n\nAfter adding a constant to the Plate rectangle"; Properties(Plate);

Rect += Recto; cout << "\n\nSecond Properties of Rect"; Properties(Rect);

return 0; } //---------------------------------------------------------------------------

When the += operatotor is called by a variable, the value of the variable is modified. Because the += is a binary operator, it is forcefully applied on two value. After its execution, it results in a new value that can be assigned to another variable. Since a value is returned, it is safer to return a non-void value. The return value should be the same as the variable that made the call. This would change the function as follows:
//--------------------------------------------------------------------------#ifndef RectangleH

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#define RectangleH //--------------------------------------------------------------------------class TRectangle { ... public: ... TRectangle& operator=(const TRectangle& Rect); TRectangle& operator+(const double d); TRectangle& Adder(const TRectangle& x); TRectangle operator+=(const double d); TRectangle operator+=(const TRectangle& Rect); private: ... }; //--------------------------------------------------------------------------#endif

Because the variable that makes the call also gets modified and preserves the newly acquired value, you can reinforce this by returning a reference instead of a regular object:
//--------------------------------------------------------------------------#ifndef RectangleH #define RectangleH //--------------------------------------------------------------------------class TRectangle { ... public: ... TRectangle& operator=(const TRectangle& Rect); TRectangle& operator+(const double d); TRectangle& Adder(const TRectangle& x); TRectangle& operator+=(const double d); TRectangle& operator+=(const TRectangle& Rect); private: ... }; //--------------------------------------------------------------------------#endif

Now, the compiler expects the function to return a value. Since the variable that makes the call is also the same that is returned, the function should return the object that called it. This is done by returning the this pointer:
//---------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
TRectangle& TRectangle::operator+=(const double d) { Length += d; Height += d;

return *this; } //--------------------------------------------------------------------------TRectangle& TRectangle::operator+=(const TRectangle& R) { Length += R.Length; Height += R.Height;

return *this; } //---------------------------------------------------------------------------

The other assignment operators can be declared as we did for the += operator:
//--------------------------------------------------------------------------#ifndef RectangleH #define RectangleH //--------------------------------------------------------------------------class TRectangle { friend TRectangle operator+(const TRectangle& x, const TRectangle& y); friend TRectangle operator-(const TRectangle& x, const TRectangle& y); friend TRectangle operator*(const TRectangle& x, const TRectangle& y); friend TRectangle operator/(const TRectangle& x, const TRectangle& y);

public: TRectangle(double L = 0.00, double H = 0.00); TRectangle(const TRectangle& R); ~TRectangle() {} void setLength(const double L) { Length = L; } double getLength() const { return Length; } void setHeight(const double H) { Height = H; } double getHeight() const { return Height; } void setDimensions(const double L, const double H); double Perimeter() const { return 2 * (Length + Height); } double Area() const { return Length * Height; } TRectangle& operator=(const TRectangle& Rect);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
TRectangle& operator+(const double d); TRectangle& Adder(const TRectangle& x); TRectangle& operator+=(const double d); TRectangle& operator+=(const TRectangle& Rect); TRectangle& operator-=(const TRectangle& Rect); TRectangle& operator*=(const TRectangle& Rect); TRectangle& operator/=(const TRectangle& Rect);

private: double Length; double Height; }; //--------------------------------------------------------------------------#endif

The implementation also follows the same logic:


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

using namespace std;

#include "Rectangle.h" //---------------------------------------------------------------------------

//--------------------------------------------------------------------------TRectangle::TRectangle(double L, double H) : Length(L), Height(H) { } //--------------------------------------------------------------------------TRectangle::TRectangle(const TRectangle& R) : Length(R.Length), Height(R.Height) { } //--------------------------------------------------------------------------void TRectangle::setDimensions(const double L, const double H) { Length = L, Height = H; } //--------------------------------------------------------------------------TRectangle& TRectangle::operator=(const TRectangle& Rect) { Length = Rect.Length;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Height = Rect.Height;

return *this; } //--------------------------------------------------------------------------TRectangle& TRectangle::operator+(const double Number) { Length = Length + Number; return *this; } //--------------------------------------------------------------------------TRectangle operator+(const TRectangle& x, const TRectangle& y) { TRectangle R;

R.Length = x.Length + y.Length; R.Height = x.Height + y.Height;

return R; } //--------------------------------------------------------------------------TRectangle operator-(const TRectangle& x, const TRectangle& y) { TRectangle R;

R.Length = x.Length - y.Length; R.Height = x.Height - y.Height;

return R; } //--------------------------------------------------------------------------TRectangle operator*(const TRectangle& x, const TRectangle& y) { TRectangle R;

R.Length = x.Length * y.Length; R.Height = x.Height * y.Height;

return R; } //--------------------------------------------------------------------------TRectangle operator/(const TRectangle& x, const TRectangle& y)

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ TRectangle R;

if( y.Length == 0 ) // Avoid a zero denominator R.Length = 0; else R.Length = x.Length / y.Length;

if( y.Height == 0 ) R.Height = 0; else R.Height = x.Height / y.Height;

return R; } //--------------------------------------------------------------------------TRectangle& TRectangle::Adder(const TRectangle& x) { Length = Length + x.Length; Height = Height + x.Height;

return *this; } //--------------------------------------------------------------------------TRectangle& TRectangle::operator+=(const double d) { Length += d; Height += d;

return *this; } //--------------------------------------------------------------------------TRectangle& TRectangle::operator+=(const TRectangle& R) { Length += R.Length; Height += R.Height;

return *this; } //--------------------------------------------------------------------------TRectangle& TRectangle::operator-=(const TRectangle& R)

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ Length -= R.Length; Height -= R.Height;

return *this; } //--------------------------------------------------------------------------TRectangle& TRectangle::operator*=(const TRectangle& R) { Length *= R.Length; Height *= R.Height;

return *this; } //--------------------------------------------------------------------------TRectangle& TRectangle::operator/=(const TRectangle& R) { if( R.Length == 0 ) Length = 0; else Length /= R.Length;

if( R.Height == 0 ) Height = 0; else Height /= R.Height;

return *this; } //---------------------------------------------------------------------------

The operators defined as such can appropriately be applied to the variables as needed:
//--------------------------------------------------------------------------#include <iostream> #include <iomanip> using namespace std; #include "Rectangle.h" //---------------------------------------------------------------------------

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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
void Properties(const TRectangle& Rect) { cout << setiosflags(ios::fixed) << setprecision(2); cout << "\nLength: cout << "\nHeight: " << Rect.getLength(); " << Rect.getHeight();

cout << "\nPerimeter: " << Rect.Perimeter(); cout << "\nArea: } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TRectangle Rect, Recto; " << Rect.Area();

Rect.setDimensions(42.88, 36.14); Recto.setDimensions(16.52, 22.65);

cout << "Using the += Operator"; Rect += Recto; Properties(Rect);

Rect.setDimensions(42.88, 36.14); Recto.setDimensions(16.52, 22.65);

cout << "\n\nUsing the -= Operator"; Rect -= Recto; Properties(Rect);

Rect.setDimensions(42.88, 36.14); Recto.setDimensions(16.52, 22.65);

cout << "\n\nUsing the *= Operator"; Rect *= Recto; Properties(Rect);

Rect.setDimensions(42.88, 36.14); Recto.setDimensions(16.52, 22.65);

cout << "\n\nUsing the /= Operator"; Rect /= Recto; Properties(Rect);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return 0; } //---------------------------------------------------------------------------

This would produce:


Using the += Operator Length: Height: 59.40 58.79

Perimeter: 236.38 Area: 3492.13

Using the -= Operator Length: Height: 26.36 13.49

Perimeter: 79.70 Area: 355.60

Using the *= Operator Length: Height: 708.38 818.57

Perimeter: 3053.90 Area: 579857.36

Using the /= Operator Length: Height: 2.60 1.60

Perimeter: 8.38 Area: 4.14

Press any key to continue...

Overloading Boolean Operators


Boolean operators are used to compare the values held by two variables of a program. For example, the >= binary operator is used to find out whether one value is greater than another, as illustrated in the following main() function:
//--------------------------------------------------------------------------#include <iostream> using namespace std; //---------------------------------------------------------------------------

int main(int argc, char* argv[]) { double A = 1266.52;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
double D = 560.25;

if( A >= D ) cout << "A is greater than D";

return 0; } //---------------------------------------------------------------------------

To perform this operation, the compiler examines the value of each variable. If the left variable has a value greater than that of the right variable, the comparison returns true; otherwise, the comparison returns false. This means a comparison opration is in fact a function that applies to two variables. Because the C++ compiler does not allow an overloaded operator to take two arguments, the function must be declared outside of the class. Since the function needs to have access to the private (or protected) members of the variables, it should be declared as a friend of the function. The data type common to Boolean operations and functions is bool and will be used to return the result of comparison functions:
//--------------------------------------------------------------------------#ifndef RectangleH #define RectangleH //--------------------------------------------------------------------------class TRectangle { friend TRectangle operator+(const TRectangle& x, const TRectangle& y); friend TRectangle operator-(const TRectangle& x, const TRectangle& y); friend TRectangle operator*(const TRectangle& x, const TRectangle& y); friend TRectangle operator/(const TRectangle& x, const TRectangle& y); friend bool operator>=(const TRectangle& x, const TRectangle& y);

public: ... private: ... }; //---------------------------------------------------------------------------

Once again, the implementation of this function depends on the class or the intended result. For example, if the class is a square or any regular polygon, because its sides are equal, you can perform the comparison on the length of the sides:
//--------------------------------------------------------------------------#include <iostream> using namespace std; //---------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//--------------------------------------------------------------------------struct TSquare { friend bool operator>=(const TSquare& q1, const TSquare& q2); public: TSquare(double s = 0.00) : Side(s) {} TSquare(const TSquare& Q) : Side(Q.Side) {} ~TSquare() {} void setSide(const double s) { Side = s; } double getSide() const { return Side; } double Perimeter() const { return 4 * Side; } double Area() const { return Side * Side; } TSquare& operator=(const TSquare& Q); TSquare& operator+(const double Plus); private: double Side; }; //--------------------------------------------------------------------------bool operator>=(const TSquare& q1, const TSquare& q2) { if( q1.Side >= q2.Side ) return true; // Return true and exit from the function return false; // If you get here, the comparison was not successful } //--------------------------------------------------------------------------TSquare& TSquare::operator=(const TSquare& q) { Side = q.Side; return *this; } //--------------------------------------------------------------------------TSquare& TSquare::operator+(const double P) { Side = Side + P; return *this; } //--------------------------------------------------------------------------void Properties(const TSquare& Carre) { cout << "\nSide: " << Carre.getSide(); cout << "\nPerimeter: " << Carre.Perimeter();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\nArea: " << Carre.Area(); } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TSquare Square(24.08), Carre(15.36);

if( Square >= Carre ) cout << "Square is greater than Carre";

return 0; } //---------------------------------------------------------------------------

If the program consists of a restaurant menu, you can perform the comparison on the number of items ordered. If the classes are bank accounts, you can compare the balance on each account. In reality, every overloaded operator depends on your intentions and can be applied on one or more member variables and you can decide what validates the truthfulness of the comparison. For a geometric figure like the rectangle, we will compare the area of each rectangle. When the area of the left rectangle is greater than the area of the right rectangle, we will decide that the left rectangle if greater than the right rectangle:
//--------------------------------------------------------------------------bool operator>=(const TRectangle& x, const TRectangle& y) { if( x.Area() >= y.Area() ) return true; return false; } //---------------------------------------------------------------------------

With such an operator defined, you can compare two rectangles:


//--------------------------------------------------------------------------int main(int argc, char* argv[]) { TRectangle Rect, Recto;

Rect.setDimensions(42.88, 36.14); Recto.setDimensions(16.52, 22.65);

if( Rect >= Recto ) cout << "Rect is wider than Recto";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return 0; } //---------------------------------------------------------------------------

The other comparison operators can be overloaded following the same logic. For example, here are their declarations:
//--------------------------------------------------------------------------#ifndef RectangleH #define RectangleH //--------------------------------------------------------------------------class TRectangle { friend TRectangle operator+(const TRectangle& x, const TRectangle& y); friend TRectangle operator-(const TRectangle& x, const TRectangle& y); friend TRectangle operator*(const TRectangle& x, const TRectangle& y); friend TRectangle operator/(const TRectangle& x, const TRectangle& y); friend bool operator==(const TRectangle& x, const TRectangle& y); friend bool operator!=(const TRectangle& x, const TRectangle& y); friend bool operator<(const TRectangle& x, const TRectangle& y); friend bool operator<=(const TRectangle& x, const TRectangle& y); friend bool operator>(const TRectangle& x, const TRectangle& y); friend bool operator>=(const TRectangle& x, const TRectangle& y);

public: ... private: double Length; double Height; }; //--------------------------------------------------------------------------#endif

Their implementations also follow the same logic applied to the += operator:
//--------------------------------------------------------------------------using namespace std; #include "Rectangle.h" //--------------------------------------------------------------------------... //--------------------------------------------------------------------------bool operator==(const TRectangle& x, const TRectangle& y) { if( x.Area() == y.Area() )

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return true; return false; } //--------------------------------------------------------------------------bool operator!=(const TRectangle& x, const TRectangle& y) { if( x.Area() != y.Area() ) return true; return false; } //--------------------------------------------------------------------------bool operator<(const TRectangle& x, const TRectangle& y) { if( x.Area() < y.Area() ) return true; return false; } //--------------------------------------------------------------------------bool operator<=(const TRectangle& x, const TRectangle& y) { if( x.Area() <= y.Area() ) return true; return false; } //--------------------------------------------------------------------------bool operator>(const TRectangle& x, const TRectangle& y) { if( x.Area() > y.Area() ) return true; return false; } //--------------------------------------------------------------------------bool operator>=(const TRectangle& x, const TRectangle& y) { if( x.Area() >= y.Area() ) return true; return false; } //--------------------------------------------------------------------------... //---------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
This allows you to perform any comparison on variables declared from the class. Here is an example:
//--------------------------------------------------------------------------#include <iostream> using namespace std; #include "Rectangle.h" //---------------------------------------------------------------------------

//--------------------------------------------------------------------------void Properties(const TRectangle& Rect) { cout << "\nLength: cout << "\nHeight: " << Rect.getLength(); " << Rect.getHeight();

cout << "\nPerimeter: " << Rect.Perimeter(); cout << "\nArea: } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TRectangle Rect(42.88, 36.14), Recto(16.52, 22.65); " << Rect.Area();

if( Rect != Recto ) cout << "Rect and Recto don't share the same size\n";

return 0; } //---------------------------------------------------------------------------

The Stream Operators


The stream operators are used to either display items on the console or to request items from an external source.

Overloading the Output Operator


The output operator << is used to display data on the console screen. We have been using it as in the following example:
//--------------------------------------------------------------------------#include <iostream> using namespace std; //---------------------------------------------------------------------------

int main(int argc, char* argv[]) {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
double A = 1266.52; double D = 560.25;

cout << "Values of the variables"; cout << "\nA: " << A; cout << "\nD: " << D;

return 0; } //---------------------------------------------------------------------------

As it does with regular variables, the compiler can be configured appropriately when the output operator is applied to a variable declared from a class. This makes it possible to write a statement such as: TCountry Pais; cout << Pais; To appropriately display a variable on the console, you must overloaded the output << operator and tell the compiler how to behave when this operator is used on the variable. The function used to perform this operation is structured as operator<<(). Like any of the operators we have used so far, the compiler needs to know what variable is being worked on. Therefore, you must at least pass this variable as argument. When the output operator is executed, the intention is only to display the value(s) of the variable without modification. For this reason, the argument should be passed as a constant reference:
//--------------------------------------------------------------------------#ifndef RectangleH #define RectangleH //--------------------------------------------------------------------------class TRectangle { ... public: ... void operator<<(const TRectangle& Rect); private: ... }; //--------------------------------------------------------------------------#endif

Any data display on the screen is managed by a class called ostream. This class communicates to the << operator how data must be displayed. Therefore, if you want to control how the compiler would display data, you must pass this class to your operator. Because the variable will be modified, in order to keep the modification performed on the variable, you should pass it as reference. This changes the function to:
//--------------------------------------------------------------------------#ifndef RectangleH

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#define RectangleH //--------------------------------------------------------------------------class TRectangle { ... public: ... void operator<<(ostream& Ostr, const TRectangle& Rect);

private: ... }; //--------------------------------------------------------------------------#endif

Since the ostream is an external class, make sure you include its header file, which is iostream.h. Now that the overloaded operator function is using two variables, it cannot be part of the class: you must declare it outside of the class. In order for the function to access private (and/or protected) member variables of the class, you should make it a friend of the class. The function becomes:
//--------------------------------------------------------------------------#ifndef RectangleH #define RectangleH #include <iostream> //--------------------------------------------------------------------------class TRectangle { friend void operator<<(ostream& Ostr, const TRectangle& Rect); ...

private: ... }; //--------------------------------------------------------------------------#endif

To implement this function, once again, tell the compiler what to do with it. You can access some members or each member variable of the class whose values you want to display and define how their values must be displayed. For this exercise, we will list the dimensions of the rectangle the way the corrdinates or a Cartesian point are displayed:
//--------------------------------------------------------------------------void operator<<(ostream& Ostr, const TRectangle& R) { Ostr << "(" << R.Length << ", " << R.Height << ")"; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//---------------------------------------------------------------------------

With the operator thus defined, the compiler knows how and what to display on the output operator. Here is an example of using it in a function:
//--------------------------------------------------------------------------int main(int argc, char* argv[]) { TRectangle Rect(42.88, 36.14);

cout << "Rectangle: Rect"; cout << Rect;

return 0; } //---------------------------------------------------------------------------

In practical terms, the output operator << is a binary operator: it operates on two values. Consequently, it provides a result in the form of a third value. This means the operator<<() function should return a value. Because it is applied on the ostream class which allows it to tell the ostream class how to display data on the right side of the operator, the ostream argument is the one that gets modified and that is being worked on. The second argument, in this case the TRectangle is simply the source of data that will be displayed. Therefore, the function should return an instance of the ostream class. This means the function should be declared as follows:
//--------------------------------------------------------------------------#ifndef RectangleH #define RectangleH #include <iostream> //--------------------------------------------------------------------------class TRectangle { friend ostream& operator<<(ostream& Ostr, const TRectangle& Rect); ... public: ... private: ... }; //--------------------------------------------------------------------------#endif

This time, the function should return the result of the operation:
//--------------------------------------------------------------------------ostream& operator<<(ostream& Ostr, const TRectangle& R) { Ostr << "(" << R.Length << ", " << R.Height << ")";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return Ostr; } //---------------------------------------------------------------------------

The Input Operator


The input operator >> is used to request a value or some values from the user. Here is an example:
//--------------------------------------------------------------------------#include <iostream> using namespace std; //---------------------------------------------------------------------------

int main(int argc, char* argv[]) { double A;

cout << "Type a double-precision number: "; cin >> A;

cout << "\nThe value you typed is: " << A;

return 0; } //---------------------------------------------------------------------------

In the same way, you can write an overloaded version of the input operator. Its syntax would be: operator>>(). The class used to request values from the console is istream. To apply this operator, you should pass both an istream object and an instane of the class whose variables you want to request. Following the same logic applied to the output operator, the function would be declared as follows:
//--------------------------------------------------------------------------#ifndef RectangleH #define RectangleH #include <iostream> //--------------------------------------------------------------------------class TRectangle { friend ostream& operator<<(ostream& Ostr, const TRectangle& Rect); friend istream& operator>>(istream& Istr, TRectangle& Rect); ... public: ... private:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
... }; //--------------------------------------------------------------------------#endif

When implementing this function, you will define how data input for the class will be processed, what to display and what to retrieve. Here is an example for our TRectangle class:
//--------------------------------------------------------------------------istream& operator>>(istream& Istr, TRectangle& R) { cout << "Length: "; Istr >> R.Length; cout << "Height: "; Istr >> R.Height;

return Istr; } //---------------------------------------------------------------------------

Now the cin >> operator can use an instance of your class the same way it would request the value of a regular variable. The cout and cin as defined can be called from any function. Here is an example:
//--------------------------------------------------------------------------#include <iostream> using namespace std; #include "Rectangle.h" //--------------------------------------------------------------------------void Properties(const TRectangle& R) { cout << R;

cout << "\nPerimeter: " << R.Perimeter(); cout << "\nArea: " << R.Area(); } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TRectangle Rect;

cout << "Enter the dimensions of the rectangle\n"; cin >> Rect;

cout << "\nPropeties of the rectangle\n"; Properties(Rect);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

return 0; } //---------------------------------------------------------------------------

Previous

Copyright 2000-2005 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Classes and Functions


Combinations
In order to perform the various assignments it receives, the computer manipulates objects created in a program. In most significant applications, one object is not enough to accomplish a whole purpose. As we have learned that the use of one variable in a program is unrealistic, we can also combine various objects to create a more realistic and complete application. There are various techniques used to mix objects in a program. To imitate the idea of combining different variables in a program, we will start by passing an object as a function argument, then we will be using various objects in the same program.

Objects and Functions


One of the most regular operations you will perform in your program consists of mixing objects and functions. Fortunately, C++ allows you to pass an object to a function or to return an object from a function. An object you use in a program can come from any source: an object built-in the operating system (part of the Win32 library), an object shipped with Borland C++ Builder, an object that is part of the C++ language, or one that you create. The first thing you should do is create an object, unless you are using an existing one. Lets build a conic tent. It is recognized by its radius, its height, the base area, and the area occupied by the texture. Our tent will look long, this is because I purposely included most of the techniques or features of building an object as we have learned so far. The header file creates a TCone object made of three constructors and a destructor. Since we will have private dimensions, we use get and set methods to take care of transactions between the object and the external world. We will also perform appropriate calculations. Header File: Cone.h
//---------------------------------------------------------------------------

#ifndef ConeH #define ConeH //--------------------------------------------------------------------------struct TCone { public: TCone(); // Default constructor // Constructor to initialize // Copy constructor

TCone(double r, double h); TCone(const TCone& c); ~TCone();

// Destructor

void setRadius(const double r) { Radius = r; } void setHeight(const double h) { Height = h; } double getRadius() const { return Radius; } double getHeight() const { return Height; } double Base() const; double TextureArea() const; double Volume() const; private:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
double Radius; double Height; }; //--------------------------------------------------------------------------#endif

The source file is used to initialize the object (its member variables) and to perform the necessary calculations involved with the object. Source File: Cone.cpp
//--------------------------------------------------------------------------#include <math> using namespace std;

#include "Cone.h" //---------------------------------------------------------------------------

//const double PI = 3.1415926535; //--------------------------------------------------------------------------TCone::TCone() : Radius(0.00), Height(0.00) { //TODO: Add your source code here } //--------------------------------------------------------------------------TCone::TCone(double r, double h) : Radius(r), Height(h) { //TODO: Add your source code here } //--------------------------------------------------------------------------TCone::TCone(const TCone& c) : Radius(c.Radius), Height(c.Height) { //TODO: Add your source code here } //--------------------------------------------------------------------------TCone::~TCone() { //TODO: Add your source code here } //---------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
double TCone::Base() const { // The area of the base of the cone return Radius * Radius * M_PI; } //--------------------------------------------------------------------------double TCone::TextureArea() const { // The area covered by the tissue that covers the tent double Radius2 = Radius * Radius; double Height2 = Height * Height; double SlantHeight = sqrt(Radius2 + Height2); return M_PI * Radius * SlantHeight; } //--------------------------------------------------------------------------double TCone::Volume() const { // The interior volume available for inhabiting the tent return (M_PI * Radius * Radius * Height) / 3; } //---------------------------------------------------------------------------

Once the object is built, you can call it from another function. As we have done with the main() function, you can call an object as is using the default constructor, which itself has the responsibility of using default values for its members: Source File: Main.cpp
//--------------------------------------------------------------------------#include <iostream> using namespace std; #include "Cone.h" //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TCone Conic;

cout << "A tent with default dimensions"; cout << "\nRadius: " << Conic.getRadius(); cout << "\nHeight: " << Conic.getHeight(); cout << "\nBase Area: " << Conic.Base(); cout << "\nTexture Area: " << Conic.TextureArea() << "\n";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return 0; } //---------------------------------------------------------------------------

The program produces:


A tent with default dimensions Radius: 0 Height: 0 Base Area: 0 Texture Area: 0

In the same way you can provide values for the object, using the right constructor or the right method: Source File: Main.cpp
//--------------------------------------------------------------------------#include <iostream> using namespace std; #include "Cone.h" //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TCone Tone(25.55, 32.95); cout << "A tent with default dimensions"; cout << "\nRadius: cout << "\nHeight: cout << "\nBase Area: " << Tone.getRadius(); " << Tone.getHeight(); " << Tone.Base();

cout << "\nTexture Area: " << Tone.TextureArea() << "\n";

return 0; } //---------------------------------------------------------------------------

With an object as complete as our cone, you can let the user provide the dimensions for the tent: Source File: Main.cpp
//--------------------------------------------------------------------------#include <iostream> using namespace std; #include "Cone.h" //--------------------------------------------------------------------------int main(int argc, char* argv[]) {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
TCone Camper; double r, h;

cout << "Specify the dimensions of the tent\n"; cout << "Radius: "; cin >> r; cout << "Radius: "; cin >> h;

Camper.setRadius(r); Camper.setHeight(h);

cout << "\nA tent with user-defined dimensions"; cout << "\nRadius: cout << "\nHeight: cout << "\nBase Area: " << Camper.getRadius(); " << Camper.getHeight(); " << Camper.Base();

cout << "\nTexture Area: " << Camper.TextureArea() << "\n";

return 0; } //---------------------------------------------------------------------------

Which would produce, for example:


Specify the dimensions of the tent Radius: 7.24 Radius: 4.88

A tent with user-defined dimensions Radius: Height: Base Area: 7.24 4.88 164.675

Texture Area: 198.59

The Starting Object


1. Start your programming environment if you didnt yet. 2. Create a C++ application and save the project in a folder called ROSH1. Save the starting unit as Main.cpp and the project as ROSH 3. Create a new unit and save it as Students in the ROSH1 folder 4. Change the Students.h file as follows:
//--------------------------------------------------------------------------#ifndef StudentsH

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#define StudentsH #include <iostream> //--------------------------------------------------------------------------class TStudent { public: TStudent(); TStudent(string fn, string ln, int d, int m, int y); ~TStudent(); string getFirstName() { return FirstName; } string getLastName() { return LastName; } int getDayOfBirth() { return DayOfBirth; } int getMonthOfBirth() { return MonthOfBirth; } int getYearOfBirth() { return YearOfBirth; } private: string FirstName; string LastName; int DayOfBirth; int MonthOfBirth; int YearOfBirth; }; //--------------------------------------------------------------------------#endif

5. Change the Students.cpp file as follows:


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

using namespace std;

#include "Students.h" //---------------------------------------------------------------------------

TStudent::TStudent() { FirstName = "John"; LastName = "Doe"; DayOfBirth = 1; MonthOfBirth = 1; YearOfBirth = 1990; } //---------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
TStudent::TStudent(string fn, string ln, int d, int m, int y) : FirstName(fn), LastName(ln), DayOfBirth(d), MonthOfBirth(m), YearOfBirth(y) {

} //--------------------------------------------------------------------------TStudent::~TStudent() { //TODO: Add your source code here } //---------------------------------------------------------------------------

6. Implement the Main.cpp file as follows:


//--------------------------------------------------------------------------#include <iostream> using namespace std; #include "Students.h" //---------------------------------------------------------------------------

int main(int argc, char* argv[]) { TStudent St;

cout << "Student with default values"; cout << "\nFull Name: " << St.getFirstName() << " " << St.getLastName(); cout << "\nDate of Birth: " << St.getDayOfBirth() << "/" << St.getMonthOfBirth() << "/" << St.getYearOfBirth();

return 0; } //---------------------------------------------------------------------------

7. To test the program, press F9:


Student with default values Full Name: John Doe Date of Birth: 1/1/1990

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
8. Return to your programming environment. 9. To test the program with other values, change the Main.cpp file as follows:
//--------------------------------------------------------------------------#include <iostream> using namespace std; #include "Students.h" //---------------------------------------------------------------------------

int main(int argc, char* argv[]) { TStudent St("Jeannette", "Smith", 12, 5, 1988);

cout << "Student Information"; cout << "\nFull Name: " << St.getFirstName() << " " << St.getLastName(); cout << "\nDate of Birth: " << St.getDayOfBirth() << "/" << St.getMonthOfBirth() << "/" << St.getYearOfBirth();

return 0; } //---------------------------------------------------------------------------

10. Test the program 11. Return to your programming environment. 12. To let the user provide the values of an object, you can request these values from the user and fill out the object with those values. To see an example, change the Main.cpp file as follows:
//--------------------------------------------------------------------------#include <iostream> using namespace std; #include "Students.h" //--------------------------------------------------------------------------int main(int argc, char* argv[]) { string FN, LN; int Day, Month, Year; cout << "Enter the student's information\n"; cout << "First Name: "; cin >> FN; cout << "Last Name: "; cin >> LN;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "Day of Birth: "; cin >> Day; cout << "Month of Birth: "; cin >> Month; cout << "Year of Birth: "; cin >> Year;

TStudent St(FN, LN, Day, Month, Year);

cout << "\nStudent Information"; cout << "\nFull Name: " << St.getFirstName() << " " << St.getLastName(); cout << "\nDate of Birth: " << St.getDayOfBirth() << "/" << St.getMonthOfBirth() << "/" << St.getYearOfBirth();

return 0; } //---------------------------------------------------------------------------

13. Test the program by press F9. Here is an example:


Enter the student's information First Name: Gregory Last Name: Ballack Day of Birth: 22 Month of Birth: 6 Year of Birth: 1988

Student Information Full Name: Gregory Ballack Date of Birth: 22/6/1988

14. Return to your programming environment 15. Writing values to an object allows the user to control the object. Thats why set methods are very valuable. To provide set methods, change the header file of the TStudents object as follows: Header File: Students.h
//--------------------------------------------------------------------------#ifndef StudentsH #define StudentsH #include <iostream> //---------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
class TStudent { public: TStudent(); TStudent(string fn, string ln, int d, int m, int y); ~TStudent(); void setFirstName(string f) { FirstName = f; } string getFirstName() { return FirstName; } void setLastName(string l) { LastName = l; } string getLastName() { return LastName; } void setDayOfBirth(int d) { DayOfBirth = d; } int getDayOfBirth() { return DayOfBirth; } void setMonthOfBirth(int m) { MonthOfBirth = m; } int getMonthOfBirth() { return MonthOfBirth; } void setYearOfBirth(int y) { YearOfBirth = y; } int getYearOfBirth() { return YearOfBirth; }

private: string FirstName; string LastName; int DayOfBirth; int MonthOfBirth; int YearOfBirth; }; //--------------------------------------------------------------------------#endif

16. To request values of the Tstudents object, change the Main.cpp file as follows: Source File: Main.cpp
//--------------------------------------------------------------------------#include <iostream> using namespace std; #include "Students.h" //--------------------------------------------------------------------------int main(int argc, char* argv[]) { string FN, LN; int Day, Month, Year; TStudent St;

cout << "Enter the student's information\n";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "First Name: "; cin >> FN; cout << "Last Name: "; cin >> LN; cout << "Day of Birth: "; cin >> Day; cout << "Month of Birth: "; cin >> Month; cout << "Year of Birth: "; cin >> Year;

St.setFirstName(FN); St.setLastName(LN); St.setDayOfBirth(Day); St.setMonthOfBirth(Month); St.setYearOfBirth(Year);

cout << "\nStudent Information"; cout << "\nFull Name: " << St.getFirstName() << " " << St.getLastName(); cout << "\nDate of Birth: " << St.getDayOfBirth() << "/" << St.getMonthOfBirth() << "/" << St.getYearOfBirth();

return 0; } //---------------------------------------------------------------------------

17. To test the program, press F9. Here is an example:


Enter the student's information First Name: Juan Last Name: Gomez Day of Birth: 2 Month of Birth: 2 Year of Birth: 1991

Student Information Full Name: Juan Gomez Date of Birth: 2/2/1991

18. Return to your programming environment

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

An object as an Argument
After creating an object, it becomes a data type, sometimes referred to as a programmer defined data type. As an identifier, you can declare an object inside of a function and use it. That is what we have done so far when using objects inside of the main() function. There are two techniques used to involve an object with a function. You can pass a member of an object as argument to a function, or you can pass the whole object as an argument. When passing an object as a parameter, you should be familiar with the construction of the object. Know its members and which ones you need to use. The code completion feature is highly useful in this circumstance. Instead of displaying the characteristics of the tent in the main() function, we can use an external function to perform that assignment. Source File: Main.cpp
//--------------------------------------------------------------------------#include <iostream> using namespace std; #include "Cone.h" //--------------------------------------------------------------------------void ShowTent(TCone c) { cout << "Characteristics of this tent"; cout << "\nRadius: " << c.getRadius(); cout << "\nHeight: " << c.getHeight(); cout << "\nBase Area: " << c.Base(); cout << "\nTexture Area: " << c.TextureArea() << "\n"; } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TCone Tent; ShowTent(Tent);

return 0; } //---------------------------------------------------------------------------

Even if you let the user provide the values of the object, after constructing such an object, you can pass it to a function that would manipulate it, including displaying its characteristics: Source File: Main.cpp
//--------------------------------------------------------------------------#include <iostream> #include <iomanip> using namespace std; #include "Cone.h" //---------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
void ShowTent(TCone c) { cout << "\nCharacteristics of this tent"; cout << setiosflags(ios::fixed) << setprecision(2); cout << "\nRadius: cout << "\nHeight: cout << "\nBase Area: " << c.getRadius(); " << c.getHeight(); " << c.Base();

cout << "\nTexture Area: " << c.TextureArea() << "\n"; } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TCone Tent; double r, h;

cout << "Specify the dimensions of the tent\n"; cout << "Radius: "; cin >> r; cout << "Height: "; cin >> h;

Tent.setRadius(r); Tent.setHeight(h); ShowTent(Tent);

return 0; } //---------------------------------------------------------------------------

Here is an example of running the program:


Specify the dimensions of the tent Radius: 10.24 Height: 6.84

Characteristics of this tent Radius: Height: Base Area: 10.24 6.84 329.42

Texture Area: 396.15

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Using an Object as an Argument


1. To use an object as argument, change the Main.cpp file as follows:
//--------------------------------------------------------------------------#include <iostream> using namespace std; #include "Students.h" //--------------------------------------------------------------------------int main(int argc, char* argv[]) { string FN, LN; int Day, Month, Year; void ShowStudent(TStudent s);

cout << "Enter the student's information\n"; cout << "First Name: "; cin >> FN; cout << "Last Name: "; cin >> LN; cout << "Day of Birth: "; cin >> Day; cout << "Month of Birth: "; cin >> Month; cout << "Year of Birth: "; cin >> Year;

TStudent St(FN, LN, Day, Month, Year); ShowStudent(St);

return 0; } //--------------------------------------------------------------------------void ShowStudent(TStudent s) { cout << "\nStudent Registration"; cout << "\nFull Name: " << s.getFirstName() << " " << s.getLastName(); cout << "\nDate of Birth: " << s.getDayOfBirth() << "/" << s.getMonthOfBirth() << "/" << s.getYearOfBirth(); }//---------------------------------------------------------------------------

2. To test the program, press F9. Here is an example:


Enter the student's information First Name: Joan Last Name: Lucent Day of Birth: 18

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Month of Birth: 4 Year of Birth: 1986

Student Registration Full Name: Joan Lucent Date of Birth: 18/4/1986

3. Return to your programming environment

Objects and their External Interaction


Returning an Object
As a data type, you can use an object as returning value of a function. The issue this time is a little different. When returning an object, you should be familiar with the construction of the object, especially its constructorr. Since you will mostly return an object as complete as possible, the returned variable is a constructor. Therefore, when building the object inside of the function, make sure that the object can be used as a variable. Ask yourself if the object you are returning can be passed an argument to another function. Can it be used to display the complete properties of the object? As opposed to requesting the dimensions of the tent from the main() function, we will use an external function to take care of that so that when the object is returned, we will trust that it can be used by another part of the program. Source File: Main.cpp
//--------------------------------------------------------------------------#include <iostream> #include <iomanip> using namespace std; #include "Cone.h" //---------------------------------------------------------------------------

void Exit() {

} //--------------------------------------------------------------------------void ShowTent(TCone c) { cout << "\nCharacteristics of this tent"; cout << setiosflags(ios::fixed) << setprecision(2); cout << "\nRadius: cout << "\nHeight: " << c.getRadius(); " << c.getHeight();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\nBase Area: " << c.Base(); cout << "\nTexture Area: " << c.TextureArea() << "\n"; } //--------------------------------------------------------------------------TCone ObtainDimensions() { double r, h;

cout << "Specify the dimensions of the tent\n"; cout << "Radius: "; cin >> r; cout << "Radius: "; cin >> h;

return TCone::TCone(r, h); // Returning the constructor } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TCone Tent;

Tent = ObtainDimensions(); ShowTent(Tent);

Exit(); return 0; } //---------------------------------------------------------------------------

An example of running the program would produce:


Specify the dimensions of the tent Radius: 8.44 Radius: 5.26

Characteristics of this tent Radius: Height: Base Area: 8.44 5.26 223.79

Texture Area: 263.69

Another version of the ObainDimensions() function would consist of assigning the values of the member variables of the object to the right access methods: Source File: Main.cpp

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//--------------------------------------------------------------------------TCone ObtainDimensions() { double r, h; TCone Tonic;

cout << "Specify the dimensions of the tent\n"; cout << "Radius: "; cin >> r; cout << "Height: "; cin >> h;

Tonic.setRadius(r); Tonic.setHeight(h); return Tonic; } //---------------------------------------------------------------------------

As another technique, you can first build the object by assembling the necessary member variables. Once the variables are gathered, you build an object based on those and return such an object from the function. Here is an example: Source File: Main.cpp
//--------------------------------------------------------------------------TCone ObtainDimensions() { double r, h;

cout << "Specify the dimensions of the tent\n"; cout << "Radius: "; cin >> r; cout << "Height: "; cin >> h;

TCone Copper(r, h); return Copper; } //---------------------------------------------------------------------------

Any of these techniques should allow you to return the desired object from a function and be able to use that object somewhere else, including displaying its properties using another function:
Specify the dimensions of the tent Radius: 18.12 Height: 10.26

Characteristics of this tent Radius: Height: 18.12 10.26

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Base Area: 1031.49

Texture Area: 1185.37

Returning an Object From a Function


1. To apply an example of returning an object, change the Main.cpp file as follows:
//--------------------------------------------------------------------------#include <iostream> using namespace std; #include "Students.h" //---------------------------------------------------------------------------

int main(int argc, char* argv[]) { TStudent Stud; TStudent Register(); void ShowStudent(TStudent Grade1);

Stud = Register(); ShowStudent(Stud);

return 0; } //--------------------------------------------------------------------------void ShowStudent(TStudent s) { cout << "\nStudent Registration"; cout << "\nFull Name: " << s.getFirstName() << " " << s.getLastName(); cout << "\nDate of Birth: " << s.getDayOfBirth() << "/" << s.getMonthOfBirth() << "/" << s.getYearOfBirth(); }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//--------------------------------------------------------------------------TStudent Register() { string FN, LN; int Day, Month, Year; TStudent s;

cout << "Enter the student's information\n"; cout << "First Name: "; cin >> FN; cout << "Last Name: "; cin >> LN; cout << "Day of Birth: "; cin >> Day; cout << "Month of Birth: "; cin >> Month; cout << "Year of Birth: "; cin >> Year;

s.setFirstName(FN); s.setLastName(LN); s.setDayOfBirth(Day); s.setMonthOfBirth(Month); s.setYearOfBirth(Year);

return s; } //---------------------------------------------------------------------------

2. Press F9 to test the program. Here is an example:


Enter the student's information First Name: Jarrel Last Name: Jeremies Day of Birth: 2 Month of Birth: 4 Year of Birth: 1991

Student Registration Full Name: Jarrel Jeremies Date of Birth: 2/4/1991

3. Return to your programming environment

Passing an Object by Reference


Since an object is a data type, it enjoys the features of the other, regular, variables. For example, instead of returning an object from a function, when this is not possible because of some circumstances, you can pass an object by reference. Like another variable, when an object is passed by reference, any alteration made on the object will be kept when the function exists. This

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
feature allows you to declare a function as void but return a completely built object. To pass an object by reference, use the ampersand between its name and the name of the argument inside of the function parentheses: Source File: Main.cpp
//--------------------------------------------------------------------------#include <iostream> #include <iomanip> using namespace std; #include "Cone.h" //---------------------------------------------------------------------------

void Exit() {

} //--------------------------------------------------------------------------void ShowTent(TCone c) { cout << "\nCharacteristics of this tent"; cout << setiosflags(ios::fixed) << setprecision(2); cout << "\nRadius: cout << "\nHeight: cout << "\nBase Area: " << c.getRadius(); " << c.getHeight(); " << c.Base();

cout << "\nTexture Area: " << c.TextureArea() << "\n"; } //--------------------------------------------------------------------------void ObtainDimensions(TCone& Tone) { double r, h;

cout << "Specify the dimensions of the tent\n"; cout << "Radius: "; cin >> r; cout << "Radius: "; cin >> h;

Tone.setRadius(r); Tone.setHeight(h); } //--------------------------------------------------------------------------int main(int argc, char* argv[])

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ TCone Tent;

ObtainDimensions(Tent); ShowTent(Tent);

Exit();

return 0; } //---------------------------------------------------------------------------

Here is example of running the program:


Specify the dimensions of the tent Radius: 5.12 Radius: 3.84

Characteristics of this tent Radius: Height: Base Area: 5.12 3.84 82.35

Texture Area: 102.94

Passing an Object by Reference


1. To pass an object as reference, change the Main.cpp file as follows:
//--------------------------------------------------------------------------#include <iostream> using namespace std; #include "Students.h" //---------------------------------------------------------------------------

int main(int argc, char* argv[]) { TStudent Stud; void Register(TStudent&); void ShowStudent(TStudent Grade1);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Register(Stud); ShowStudent(Stud);

return 0; } //--------------------------------------------------------------------------void Register(TStudent& S) { string FN, LN; int Day, Month, Year;

cout << "Enter the student's information\n"; cout << "First Name: "; cin >> FN; cout << "Last Name: "; cin >> LN; cout << "Day of Birth: "; cin >> Day; cout << "Month of Birth: "; cin >> Month; cout << "Year of Birth: "; cin >> Year;

S.setFirstName(FN); S.setLastName(LN); S.setDayOfBirth(Day); S.setMonthOfBirth(Month); S.setYearOfBirth(Year); } //--------------------------------------------------------------------------void ShowStudent(TStudent s) { cout << "\nStudent Registration"; cout << "\nFull Name: " << s.getFirstName() << " " << s.getLastName(); cout << "\nDate of Birth: " << s.getDayOfBirth() << "/" << s.getMonthOfBirth() << "/" << s.getYearOfBirth(); } //---------------------------------------------------------------------------

2. Test the program and return to your programming environment

Friend Functions of a Class


Good programming techniques dictate that you should hide the variables used to store data of a class. This is done by declaring the member variables in the private section. Once a variable is

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
hidden like that, only the members of the same class have access to it. The C++ language provides an alternative to this problem. Although you can still hide your variables, you can create special functions that have a priviledged access to the members of the private section of a class. These functions are not members of the class, they are just granted special access to the hidden member variables. Such functions are qualified as friends. To declare a friend function, start with the friend keyword, followed by the return value, followed by the name of the function, its parentheses, and possibly the necessary arguments. Since a friend is not a function member of the object, you should provide access to the object, one way or another. When a function has been declared as a friend of a class, the class grants and controls the friendship. The friend keyword is used only when declaring the friendly function. When defining the function, proceed as if it were a regularly declared function, omitting the friend keyword. Because friend functions are given special access, they can be declared anywhere in the class; but a good habit is to position them on top of the object just under the opening curly braket. This allow the compiler, you, and anybody who reads your code to have the list of friends of the class. Here is a starting example. The Item class has two member variables that represent the quantity and the unit price. Both members are hidden in the private section, which means they cannot be seen outside of the class. Instead of creating a TotalPrice() member function, a friend function is declared so it can access the private members of the object:
//--------------------------------------------------------------------------#include <iostream> using namespace std;

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

class TForSale { friend double TotalPrice(TForSale i); public: TForSale(int q = 0, double p = 0.00); private: int Qty; double UnitPrice; }; //--------------------------------------------------------------------------TForSale::TForSale(int Quantity, double Price) : Qty(Quantity), UnitPrice(Price) { } //--------------------------------------------------------------------------double TotalPrice(TForSale i) { return i.Qty * i.UnitPrice; } //---------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
int main(int argc, char* argv[]) { TForSale item(12, 0.99);

cout << "Total Price: $" << TotalPrice(item) << endl;

return 0; } //---------------------------------------------------------------------------

An example of running the program would produce:


Total Price: $11.88

Although the above example comports only one function, an object can have as many friends as you see fit. For example, you can create a TTriangle object that has a Base and a Height private members, then declare two friend functions, one to calculate the perimeter and the other to calculate the area. The previous program was made of only one file. This time, you can separate the interface and the implementations in two files. The object definition could appear as follows:
//---------------------------------------------------------------------------

#ifndef TriangleH #define TriangleH //--------------------------------------------------------------------------struct TTriangle { friend double Perimeter(TTriangle Tri); friend double Area(TTriangle Tri);

public: TTriangle(double B = 0.00, double H = 0.00); TTriangle(const TTriangle& t); ~TTriangle(); double getBase() const; double getHeight() const; private: double Base; double Height; }; //---------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#endif

Once the friends have been declared, you can define them in the header file of the object as if they were part of the interface. Here is an example:
//---------------------------------------------------------------------------

#ifndef TriangleH #define TriangleH //--------------------------------------------------------------------------struct TTriangle { friend double Perimeter(TTriangle Tri); friend double Area(TTriangle Tri);

public: TTriangle(double B = 0.00, double H = 0.00); TTriangle(const TTriangle& t); ~TTriangle(); double getBase() const; double getHeight() const; private: double Base; double Height; }; //--------------------------------------------------------------------------double Perimeter(TTriangle Tri) { double RootOfHB = sqrt((Tri.Base * Tri.Base) + (Tri.Height * Tri.Height));

return Tri.Base + Tri.Height + RootOfHB; } //--------------------------------------------------------------------------double Area(TTriangle Tri) { return Tri.Base * Tri.Height / 2; } //--------------------------------------------------------------------------#endif

Just like all the functions and methods we have used so far, friend functions also can use the convention. To fastcall friend functions, type between the return type and the function name:
//---------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#ifndef TriangleH #define TriangleH //--------------------------------------------------------------------------struct TTriangle { friend double Perimeter(TTriangle Tri); friend double Area(TTriangle Tri);

public: TTriangle(double B = 0.00, double H = 0.00); TTriangle(const TTriangle& t); ~TTriangle(); double getBase() const; double getHeight() const; private: double Base; double Height; }; //--------------------------------------------------------------------------double Perimeter(TTriangle Tri) { double RootOfHB = sqrt((Tri.Base * Tri.Base) + (Tri.Height * Tri.Height));

return Tri.Base + Tri.Height + RootOfHB; } //--------------------------------------------------------------------------double Area(TTriangle Tri) { return Tri.Base * Tri.Height / 2; } //--------------------------------------------------------------------------#endif

Since you will usually choose to hide your hard work, you can define the friend functions in the source file of the object, as follows:
//--------------------------------------------------------------------------#include <math> using namespace std;

#include "Triangle.h" //---------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//--------------------------------------------------------------------------double Perimeter(TTriangle Tri) { double RootOfHB = sqrt((Tri.Base * Tri.Base) + (Tri.Height * Tri.Height));

return Tri.Base + Tri.Height + RootOfHB; } //--------------------------------------------------------------------------double Area(TTriangle Tri) { return Tri.Base * Tri.Height / 2; } //--------------------------------------------------------------------------TTriangle::TTriangle(double B, double H) : Base(B), Height(H) { } //--------------------------------------------------------------------------TTriangle::TTriangle(const TTriangle& t) : Base(t.Base), Height(t.Height) { } //--------------------------------------------------------------------------TTriangle::~TTriangle() { } //--------------------------------------------------------------------------double TTriangle::getBase() const { return Base; } //--------------------------------------------------------------------------double TTriangle::getHeight() const { return Height; } //---------------------------------------------------------------------------

Friends are called like any other regular global functions, by their names. They do not need to be qualified with the period operator. Therefore, they can be called by any function. They can be passed any variable declared from the friendly object; and as you know already, they have access to all members of the object. Here is a declaration of the TTriangle object in the main() function,

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
We use an external function to display the characteristics of the object. Notice that this external function calls the friend functions of the class without qualifying them:
//--------------------------------------------------------------------------#include <iostream> #include <iomanip> using namespace std; #include "Triangle.h" //---------------------------------------------------------------------------

//--------------------------------------------------------------------------void Characteristics(const TTriangle& T) { cout << "Characteristics of the triangle\n"; cout << setiosflags(ios::fixed) << setprecision(2); cout << "Base: cout << "Height: " << T.getBase() << endl; " << T.getHeight() << endl;

cout << "Perimeter: " << Perimeter(T) << endl; cout << "Area: } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TTriangle Trng(12.55, 10.85); " << Area(T) << endl;

Characteristics(Trng);

return 0; } //---------------------------------------------------------------------------

Here is an example of running the program:


Characteristics of the triangle Base: Height: 12.55 10.85

Perimeter: 39.99 Area: 68.08

When a friend function does not modify the value(s) of the objects member variable(s) it

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
accesses, like a regular function, you should pass the object as a constant to protect your variables from erroneous modification. Here is an example:
//--------------------------------------------------------------------------#ifndef TriangleH #define TriangleH //--------------------------------------------------------------------------struct TTriangle { friend double Perimeter(const TTriangle Tri); friend double Area(const TTriangle Tri);

public: TTriangle(double B = 0.00, double H = 0.00); TTriangle(const TTriangle& t); ~TTriangle(); double getBase() const; double getHeight() const; private: double Base; double Height; }; //--------------------------------------------------------------------------#endif

Of course, remember that the const keyword is used both when declaring the function and when defining it:
//--------------------------------------------------------------------------double Perimeter(const TTriangle Tri) { double RootOfHB = sqrt((Tri.Base * Tri.Base) + (Tri.Height * Tri.Height));

return Tri.Base + Tri.Height + RootOfHB; } //--------------------------------------------------------------------------double Area(const TTriangle Tri) { return Tri.Base * Tri.Height / 2; } //---------------------------------------------------------------------------

When the compiler is accessing an object passed by value, there is overhead involved with going back and forth from the declaration to the definition of the object. One way you can improve the speed of this execution is to pass the object to its friend(s) as reference. This will allow the (friend) function(s) to access the object directly at its location in memory. Here is an example:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//--------------------------------------------------------------------------#ifndef TriangleH #define TriangleH //--------------------------------------------------------------------------struct TTriangle { friend double Perimeter(TTriangle& Tri); friend double Area(TTriangle& Tri);

public: ... private: double Base; double Height; }; //--------------------------------------------------------------------------#endif

One more technique used to accelerate code execution when a (friend) function (or any function) does not modify the member variables of the object it receives is to not only pass it as a constant, but also by reference. Using this technique, although the function has access to the address of the object, the function cannot modify the objects variables values. Here is our new header file:
//--------------------------------------------------------------------------#ifndef TriangleH #define TriangleH //--------------------------------------------------------------------------struct TTriangle { friend double Perimeter(const TTriangle& Tri); friend double Area(const TTriangle& Tri);

public: ... private: double Base; double Height; }; //--------------------------------------------------------------------------#endif

When defining the (friend) functions, remember to use the same system of passing arguments as their declarations: Any function that does not modify the object argument it receives should have the object passed as a constant reference.

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
As an acquaintance of the object, a friend function is sometimes asked to perform assignments such as building and returning the object. This is the same technique used to return a complete object. To declare such a function, type the friend keyword, followed by the name of the class, followed by the name of the function and its parentheses. Possible arguments are an option. Here is an example:
//--------------------------------------------------------------------------#ifndef TriangleH #define TriangleH //--------------------------------------------------------------------------struct TTriangle { friend TTriangle GetDimensions(); friend double Perimeter(const TTriangle& Tri); friend double Area(const TTriangle& Tri);

public: TTriangle(double B = 0.00, double H = 0.00); TTriangle(const TTriangle& t); ~TTriangle(); void setDimensions(const double b, const double h); double getBase() const; double getHeight() const; private: double Base; double Height; }; //--------------------------------------------------------------------------#endif

The function would be defined as a regular function that returns the object:
//--------------------------------------------------------------------------TTriangle GetDimensions() { double x, y;

cout << "Enter base: "; cin >> x; cout << "Enter height: "; cin >> y;

return TTriangle(x, y); } //---------------------------------------------------------------------------

When calling this function, you can assign its returned value to a variable declared from the friendly object. Here is how it could be done in the main() function:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//--------------------------------------------------------------------------#include <iostream> #include <iomanip> using namespace std; #include "Triangle.h" //---------------------------------------------------------------------------

void Characteristics(const TTriangle& T) { cout << "\nCharacteristics of the triangle\n"; cout << setiosflags(ios::fixed) << setprecision(2); cout << "Base: cout << "Height: " << T.getBase() << endl; " << T.getHeight() << endl;

cout << "Perimeter: " << Perimeter(T) << endl; cout << "Area: } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TTriangle Slice; double b, h; " << Area(T) << endl;

Slice = GetDimensions(); Characteristics(Slice);

return 0; } //---------------------------------------------------------------------------

Using Friends of a Class


1. To declare a friend function of a class, change the header file as follows:
//--------------------------------------------------------------------------#ifndef StudentsH #define StudentsH #include <iostream> //--------------------------------------------------------------------------class TStudent

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ friend TStudent Registration(); public: TStudent(); TStudent(string FN, string LN); TStudent(string fn, string ln, int d, int m, int y); TStudent(const TStudent& S); ~TStudent(); void setFirstName(string f) { FirstName = f; } string getFirstName() { return FirstName; } void setLastName(string l) { LastName = l; } string getLastName() { return LastName; } void setDayOfBirth(int d) { DayOfBirth = d; } int getDayOfBirth() { return DayOfBirth; } void setMonthOfBirth(int m) { MonthOfBirth = m; } int getMonthOfBirth() { return MonthOfBirth; } void setYearOfBirth(int y) { YearOfBirth = y; } int getYearOfBirth() { return YearOfBirth; }

private: string FirstName; string LastName; int DayOfBirth; int MonthOfBirth; int YearOfBirth; }; //--------------------------------------------------------------------------#endif

2. Change the source file as follows:


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

using namespace std;

#include "Students.h" //---------------------------------------------------------------------------

//--------------------------------------------------------------------------TStudent Registration() {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
TStudent S;

// Notice that the function has access to the // private members of the class cout << "Enter the student's information\n"; cout << "First Name: "; cin >> S.FirstName; cout << "Last Name: "; cin >> S.LastName; cout << "Day of Birth: "; cin >> S.DayOfBirth; cout << "Month of Birth: "; cin >> S.MonthOfBirth; cout << "Year of Birth: "; cin >> S.YearOfBirth;

return S; } //--------------------------------------------------------------------------TStudent::TStudent() { FirstName = "John"; LastName = "Doe"; DayOfBirth = 1; MonthOfBirth = 1; YearOfBirth = 1990; } //--------------------------------------------------------------------------TStudent::TStudent(string FN, string LN) : FirstName(FN), LastName(LN), DayOfBirth(1), MonthOfBirth(1), YearOfBirth(1990) {

} //--------------------------------------------------------------------------TStudent::TStudent(string fn, string ln, int d, int m, int y) : FirstName(fn), LastName(ln), DayOfBirth(d), MonthOfBirth(m), YearOfBirth(y) {

} //--------------------------------------------------------------------------TStudent::TStudent(const TStudent& Stud) : FirstName(Stud.FirstName), LastName(Stud.LastName),

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
DayOfBirth(Stud.DayOfBirth), MonthOfBirth(Stud.MonthOfBirth), YearOfBirth(Stud.YearOfBirth) { } //--------------------------------------------------------------------------TStudent::~TStudent() { //TODO: Add your source code here } //---------------------------------------------------------------------------

3. Change the Main.cpp file as follows:


//--------------------------------------------------------------------------#include <iostream> using namespace std; #include "Students.h" //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TStudent Stud; void StudentInfo(TStudent Grade1);

Stud = Registration(); StudentInfo(Stud);

return 0; } //--------------------------------------------------------------------------void StudentInfo(TStudent s) { cout << "\nStudent Registration"; cout << "\nFull Name: " << s.getFirstName() << " " << s.getLastName(); cout << "\nDate of Birth: " << s.getDayOfBirth() << "/" << s.getMonthOfBirth() << "/" << s.getYearOfBirth(); } //---------------------------------------------------------------------------

4. Test the program. Here is an example:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Enter the student's information First Name: Josh Last Name: Annett Day of Birth: 10 Month of Birth: 12 Year of Birth: 1985

Student Registration Full Name: Josh Annett Date of Birth: 10/12/1985

5. Return to your programming environment 6. To pass a class to a friend as a reference, change the declaration of the friend function in the header file as follows:
//--------------------------------------------------------------------------#ifndef StudentsH #define StudentsH #include <iostream> //--------------------------------------------------------------------------class TStudent { friend void Registration(TStudents &Student);

public: ...

private: ... }; //--------------------------------------------------------------------------#endif

7. Change the implementation of the friend function as follows:


//--------------------------------------------------------------------------void Registration(TStudents &S) { // Notice that the function has access to the // private members of the class cout << "Enter the student's information\n"; cout << "First Name: "; cin >> S.FirstName; cout << "Last Name: "; cin >> S.LastName; cout << "Day of Birth: "; cin >> S.DayOfBirth; cout << "Month of Birth: "; cin >> S.MonthOfBirth;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "Year of Birth: "; cin >> S.YearOfBirth; } //---------------------------------------------------------------------------

8. Test the program and return to your programming environment

Mixing Different Objects in the Same Program


Before using different objects in your program, they must be known to the compiler. These objects could be part of the operating system, they could be part of C++ Builder, they could be defined as C++ objects, or you can create your own. To start, we will learn how to use objects that we create. An office supplies store has hired you to write a program that will allow customers to create their own business labels using a computer located somewhere in the store. We will use two objects for our program. TDimensions will define the dimensions of the label and another object called TLabelType will define the paper quality. A classic label has dimensions set by a length and a width. When a user or another part of the program calls the label, it mostly uses constructors; and we will use them. The first constructor takes no argument; it is used to set the default dimensions for the label. The second constructor will make sure that the supplied dimensions, if any, are correct. To protect our dimensions, the length and the width will be private; we will provide access methods to get the dimensions:
//--------------------------------------------------------------------------#ifndef RectangleH #define RectangleH //--------------------------------------------------------------------------class TRectangle { public: TRectangle(); TRectangle(double L, double W); TRectangle(const TRectangle& Rect); ~TRectangle(); void setLength(double L) { Length = L; } void setHeight(double H) { Height = H; } double getLength() { return Length; } double getHeight() { return Height; } double Perimeter(double Length, double Height); double Area(double Length, double Height); private: double Length; double Height; }; //--------------------------------------------------------------------------#endif

The source file initializes the object, controls the dimensions, and calculates the area:
//---------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
using namespace std;

#include "Rectangle.h" //---------------------------------------------------------------------------

TRectangle::TRectangle() : Length(3.25), Height(2.55) { //TODO: Add your source code here } //--------------------------------------------------------------------------TRectangle::TRectangle(double L, double H) : Length(L), Height(H) { //TODO: Add your source code here } //--------------------------------------------------------------------------TRectangle::TRectangle(const TRectangle& r) : Length(r.Length), Height(r.Height) { //TODO: Add your source code here } //--------------------------------------------------------------------------TRectangle::~TRectangle() { //TODO: Add your source code here } //--------------------------------------------------------------------------double TRectangle::Perimeter(double x, double y) { return 2 * (x + y); } //--------------------------------------------------------------------------double TRectangle::Area(double x, double y) { return x * y; } //---------------------------------------------------------------------------

The second object specifies the characteristics of the label including its model number, its color, whether the label will use a removable or a non-removable adhesive. Once again, we will use two

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
constructors for the same reasons as above. Header File: LabelType.h
//--------------------------------------------------------------------------#ifndef LabelTypeH #define LabelTypeH #include <string> using namespace std; //--------------------------------------------------------------------------class TLabelType { public: TLabelType(); TLabelType(long m, string c, string n, string a); ~TLabelType(); void setModelNumber(long m) { ModelNumber = m; } void setName(string n) { Name = n; } void setColor(string c) { Color = c; } void setAdhesive(string a) { Adhesive = a; } long getModelNumber() const; string getName() const; string getColor() const; string getAdhesive() const; private: long ModelNumber; string Name; string Color; string Adhesive; }; //--------------------------------------------------------------------------#endif

The implementation file of the TLabelType object is used to initialize an object and control its properties. Source File: LabelType.cpp
//---------------------------------------------------------------------------

using namespace std;

#include "LabelType.h" //---------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
TLabelType::TLabelType() : ModelNumber(0), Color("White"), Name("None"), Adhesive("Not Specified") { //TODO: Add your source code here } //--------------------------------------------------------------------------TLabelType::TLabelType(long m, string c, string n, string a) : ModelNumber(m), Color(c), Name(n), Adhesive(a) { //TODO: Add your source code here } //--------------------------------------------------------------------------TLabelType::~TLabelType() { //TODO: Add your source code here } //--------------------------------------------------------------------------long TLabelType::getModelNumber() const { return ModelNumber; } //--------------------------------------------------------------------------string TLabelType::getName() const { return Name; } //--------------------------------------------------------------------------string TLabelType::getColor() const { return Color; } //--------------------------------------------------------------------------string TLabelType::getAdhesive() const { return Adhesive; } //---------------------------------------------------------------------------

Once you have objects, you can declare each when desired and supply its properties if needed. In our main() function, we will first call the TDimension and the TLabelType objects using empty contructors. Whenever any function or object calls an object without specifying the properties,

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
each object will display its default values: Main File: Main.cpp
//--------------------------------------------------------------------------#include <iostream> #include <iomanip> using namespace std; #include "Rectangle.h" #include "LabelType.h" //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TRectangle Dim; TLabelType LabelType;

cout << "A label with default characteristics"; cout << "\nDimensions: " << Dim.getLength() << " * " << Dim.getHeight(); cout << "\nArea: " << Dim.Area(Dim.getLength(), Dim.getHeight());

cout << "\nModel No.: " << LabelType.getModelNumber(); cout << "\nModel Name: " << LabelType.getName(); cout << "\nColor: cout << "\nAdhesive: " << LabelType.getColor(); " << LabelType.getAdhesive();

return 0; } //---------------------------------------------------------------------------

The program would produce:


A label with default characteristics Dimensions: 3.25 * 2.55 Area: 8.2875

Model No.: 0 Model Name: None Color: Adhesive: White Not Specified

The program can also provide the values of each object, using their methods: Main File: Main.cpp

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//--------------------------------------------------------------------------#include <iostream> #include <iomanip> using namespace std; #include "Rectangle.h" #include "LabelType.h" //---------------------------------------------------------------------------

//--------------------------------------------------------------------------int main(int argc, char* argv[]) { TRectangle Dim(4.55, 2.25); TLabelType LabelType(25442, "Mandarin", "One Touch", "Non-Removable");

cout << "An example label"; cout << "\nDimensions: " << Dim.getLength() << " * " << Dim.getHeight(); cout << "\nArea: " << Dim.Area(Dim.getLength(), Dim.getHeight());

cout << "\nModel No.: " << LabelType.getModelNumber(); cout << "\nModel Name: " << LabelType.getName(); cout << "\nColor: cout << "\nAdhesive: " << LabelType.getColor(); " << LabelType.getAdhesive();

return 0; } //---------------------------------------------------------------------------

This time, the program would display different values:


An example label Dimensions: 4.55 * 2.25 Area: 10.2375

Model No.: 25442 Model Name: One Touch Color: Adhesive: Mandarin Non-Removable

Combining Objects
Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
1. To process a semi-complete registration for a student, consisting of a complete address, change the Students.h file as follows:
//--------------------------------------------------------------------------#ifndef StudentsH #define StudentsH #include <iostream> //--------------------------------------------------------------------------class TStudent { friend void Registration(TStudent &Student);

public: TStudent(); TStudent(string FN, string LN); TStudent(string fn, string ln, int d, int m, int y); TStudent(const TStudent& S); ~TStudent(); void setFirstName(string f) { FirstName = f; } string getFirstName() const { return FirstName; } void setLastName(string l) { LastName = l; } string getLastName() const { return LastName; } void setDayOfBirth(int d) { DayOfBirth = d; } int getDayOfBirth() const { return DayOfBirth; } void setMonthOfBirth(int m) { MonthOfBirth = m; } int getMonthOfBirth() const { return MonthOfBirth; } void setYearOfBirth(int y) { YearOfBirth = y; } int getYearOfBirth() const { return YearOfBirth; } void setAddress(string a) { Address = a; } string getAddress() const { return Address; } void setCity(string c) { City = c; } string getCity() const { return City; } void setState(string s) { State = s; } string getState() const { return State; } void setZIPCode(string z) { ZIPCode = z; } string getZIPCode() const { return ZIPCode; } void setCountry(string c) { Country = c; } string getCountry() const { return Country; }

private: string FirstName;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
string LastName; int DayOfBirth; int MonthOfBirth; int YearOfBirth; string Address; string City; string State; string ZIPCode; string Country; }; //--------------------------------------------------------------------------#endif

2. Change the Students.cpp file as follows:


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

using namespace std;

#include "Students.h" //---------------------------------------------------------------------------

//--------------------------------------------------------------------------void Registration(TStudent &S) { // Notice that the function has access to the // private members of the class cout << "Enter the student's information\n"; cout << "First Name: cout << "Last Name: cout << "Day of Birth: "; cin >> S.FirstName; "; cin >> S.LastName; "; cin >> S.DayOfBirth;

cout << "Month of Birth: "; cin >> S.MonthOfBirth; cout << "Year of Birth: "; cin >> S.YearOfBirth; cout << "Address: "; cin >> ws; getline(cin, S.Address); cout << "City: ";

getline(cin, S.City); cout << "State: ";

getline(cin, S.State); cout << "ZIPCode: ";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
getline(cin, S.ZIPCode); cout << "Country: "; getline(cin, S.Country); } //--------------------------------------------------------------------------TStudent::TStudent() { FirstName LastName DayOfBirth = "John"; = "Doe"; = 1;

MonthOfBirth = 1; YearOfBirth = 1990; Address City State ZIPCode Country } //--------------------------------------------------------------------------TStudent::TStudent(string FN, string LN) : FirstName(FN), LastName(LN), DayOfBirth(1), MonthOfBirth(1), YearOfBirth(1990), Address("123 Main Street"), City("This State"), State("Unkown"), ZIPCode("00001-0001"), Country("USA") { = "123 Main Street"; = "Old Town"; = "This State"; = "01234-0001"; = "USA";

} //--------------------------------------------------------------------------TStudent::TStudent(string fn, string ln, int d, int m, int y) : FirstName(fn), LastName(ln), DayOfBirth(d), MonthOfBirth(m), YearOfBirth(y), Address("123 Main Street"), City("This State"), State("Unkown"), ZIPCode("00001-0001"), Country("USA") {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} //--------------------------------------------------------------------------TStudent::TStudent(const TStudent& Stud) : FirstName(Stud.FirstName), LastName(Stud.LastName), DayOfBirth(Stud.DayOfBirth), MonthOfBirth(Stud.MonthOfBirth), YearOfBirth(Stud.YearOfBirth), Address(Stud.Address), City(Stud.City), State(Stud.State), ZIPCode(Stud.ZIPCode), Country(Stud.Country) { } //--------------------------------------------------------------------------TStudent::~TStudent() { //TODO: Add your source code here } //---------------------------------------------------------------------------

3. Create a new 4. class called TGrades object and change the Grades.h file as follows:
//---------------------------------------------------------------------------

#ifndef GradesH #define GradesH //--------------------------------------------------------------------------#endif //--------------------------------------------------------------------------class TGrades { friend void GetGrades(TGrades&); public: TGrades(); TGrades(double e, double s, double h, double g, double c, double o, double m, double p, double r, double t); ~TGrades();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
void setEnglish(double e) { English = e; } double getEnglish() { return English; } void setSecondLng(double s) { SecondLng = s; } double getSecondLng() { return SecondLng; } void setHistory(double h) { History = h; } double getHistory() { return History; } void setGeography(double g) { Geography = g; } double getGeography() { return Geography; } void setChemistry(double c) { Chemistry = c; } double getChemistry() { return Chemistry; } void setSociology(double o) { Sociology = o; } double getSociology() { return Sociology; } void setMath(double m) { Math = m; } double getMath() { return Math; } void setCompSc(double p) { CompSc = p; } double getCompSc() { return CompSc; } void setMorale(double a) { Morale = a; } double getMorale() { return Morale; } void setSports(double t) { Sports = t; } double getSports() { return Sports; } double CalcTotal(); double CalcMean(); private: double English; double SecondLng; double History; double Geography; double Chemistry; double Sociology; double Math; double CompSc; double Morale; double Sports; };

5. To implement the TGrades object, change the Grades.cpp file as follows:


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

#include "Grades.h"

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//---------------------------------------------------------------------------

TGrades::TGrades() : English(0.00), SecondLng(0.00), History(0.00), Geography(0.00), Chemistry(0.00), Sociology(0.00), Math(0.00), CompSc(0.00), Morale(0.00), Sports(0.00) { } //--------------------------------------------------------------------------TGrades::TGrades(double e, double s, double h, double g, double c, double o, double m, double p, double r, double t) : English(e), SecondLng(s), History(h), Geography(g), Chemistry(c), Sociology(o), Math(m), CompSc(p), Morale(r), Sports(t) { } //--------------------------------------------------------------------------TGrades::~TGrades() { //TODO: Add your source code here } //--------------------------------------------------------------------------double TGrades::CalcTotal() { double Total = English + SecondLng + History +

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Geography + Chemistry + Sociology + Math + CompSc + Morale + Sports;

return Total; } //--------------------------------------------------------------------------double TGrades::CalcMean() { return CalcTotal() / 10; } //--------------------------------------------------------------------------void GetGrades(TGrades& Student) { cout << "English: "; cin >> Student.English;

cout << "Second Language: "; cin >> Student.SecondLng; cout << "History: cout << "Geography: cout << "Chemistry: cout << "Sociology: cout << "Mathematics: cout << "Comp Sciences: cout << "Morale: cout << "Sports: } //--------------------------------------------------------------------------"; cin >> Student.History; "; cin >> Student.Geography; "; cin >> Student.Chemistry; "; cin >> Student.Sociology; "; cin >> Student.Math; "; cin >> Student.CompSc;

"; cin >> Student.Morale; "; cin >> Student.Sports;

6. To use both objects in the same program, implement the Main.cpp file as follows:
//--------------------------------------------------------------------------#include <iostream> #include <iomanip> using namespace std; #include "Students.h" #include "Grades.h" //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TStudent Stud; TGrades Grade; void StudentInfo(TStudent Grade1); void ShowGrades(TGrades d);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "Student Registration\n"; Registration(Stud); cout << endl; cout << "Student Grades\n"; GetGrades(Grade);

system("cls");

StudentInfo(Stud); ShowGrades(Grade);

return 0; } //--------------------------------------------------------------------------void StudentInfo(TStudent s) { cout << "===================================="; cout << "\nStudent Report"; cout << "\n------------------------------------"; cout << "\nStudent Registration"; cout << "\nFull Name: " << s.getFirstName() << " " << s.getLastName(); cout << "\nDate of Birth: " << s.getDayOfBirth() << "/" << s.getMonthOfBirth() << "/" << s.getYearOfBirth(); cout << "\nAddress: << "\n " << s.getAddress()

" << s.getCity() << ", " << s.getState()

<< ", " << s.getZIPCode() << "\n } //--------------------------------------------------------------------------void ShowGrades(TGrades d) { cout << setiosflags(ios::fixed) << setprecision(2); cout << "\n------------------------------------"; cout << "\n\tEnglish: cout << "\n\tLanguage 2: cout << "\n\tHistory: cout << "\n\tGeography: " << d.getEnglish(); " << d.getSecondLng(); " << s.getCountry();

" << d.getHistory(); " << d.getGeography();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\n\tChemistry: cout << "\n\tSociology: cout << "\n\tMathematics: " << d.getChemistry(); " << d.getSociology(); " << d.getMath();

cout << "\n\tComp Sciences: " << d.getCompSc(); cout << "\n\tMorale: cout << "\n\tSports: " << d.getMorale(); " << d.getSports();

cout << "\n------------------------------------"; cout << "\n\tTotal: " << d.CalcTotal() << "\tMean: " << d.CalcMean(); cout << "\n===================================="; } //---------------------------------------------------------------------------

7. To test the program, press F9. Here is an example: First Screen:


Student Registration Enter the student's information First Name: Last Name: Day of Birth: Paul Delamarre 28

Month of Birth: 2 Year of Birth: 1986 Address: 8402 Norton Hwy #D12 City: State: Silver Spring MD

ZIPCode: 20910-4412 Country: USA

Student Grades English: 12.50

Second Language: 10.25 History: Geography: Chemistry: Sociology: Mathematics: Comp Sciences: Morale: Sports: 14.50 13.00 15.00 12.50 16.50 17.25

14.00 15.50

Second Screen:
==================================== Student Report

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
-----------------------------------Student Registration Full Name: Paul Delamarre Date of Birth: 28/2/1986 Address: 8402 Norton Hwy #D12

Silver Spring, MD, 20910-4412 USA -----------------------------------English: Language 2: History: Geography: Chemistry: Sociology: Mathematics: 12.50 10.25 14.50 13.00 15.00 12.50 16.50

Comp Sciences: 17.25 Morale: Sports: 14.00 15.50

-----------------------------------Total: 141.00 Mean: 14.10

====================================

8. Return to your programming environment

Previous

Copyright 2000-2005 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Classes and Exceptions Handling


Introduction
Exceptions are an integral and unavoidable part of the operating system and programming. One way you can handle them is to create classes whose behaviors are prepared to deal with abnormal behavior. There are two main ways you can involve classes with exception handling routines: classes that are involved in exceptions of their own operations and classes that are specially written to handle exceptions for other classes.

Transferring Exceptions to Classes


You can create a class that is not specifically oriented towards exceptions, as any of the classes we have used so far. The simplest way to take care of exceptions in classes is to use any normal class and handle its exceptions. Such a class appears like one of the classes we have used already, except that exceptions of its abnormal behavior are taken care of. If concerned with exceptions, the minimum thing you can do in your program is to make it "aware' of eventual exceptions. This can be taken care of by including transactions or other valuable processing in a try block, followed by a three-dot catch as in catch(...). The catch in this case is prepared to handle any exception that could occur. Here is an example of a simple class:

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

const double PriceShirt = 0.99; const double PricePants = 1.75;

struct TCleaningOrder { int NumberOfShirts; int NumberOfPants; int NumberOfMisc; }; int main(int argc, char* argv[]) { TCleaningOrder Order; double TotalPriceShirts, TotalPricePants; double PriceMisc, TotalPriceMisc; double TotalOrder;

cout << " - Georgetown Cleaning Services -\n"; cout << " - Customer Order Processing -\n";

try { cout << "Number of\n"; cout << "Shirts: ";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cin >> Order.NumberOfShirts; cout << "Pairs of Paints: "; cin >> Order.NumberOfPants; cout << "Misc. Items(if none, type 0): "; cin >> Order.NumberMisc;

// If there are miscalleanous items,... if(Order.NumberOfMisc > 0) { // let the user determine the price of this misc item cout << "Enter the price of each miscellanous item: "; cin >> PriceMisc; TotalPriceMisc = Order.NumberOfMisc * PriceMisc; } else TotalPriceMisc = 0.00;

TotalPriceShirts = Order.NumberOfShirts * PriceShirt; TotalPricePants = Order.NumberOfPants * PricePants;

TotalOrder = TotalPriceShirts + TotalPricePants + TotalPriceMisc;

cout << setiosflags(ios::fixed) << setprecision(2); cout << " - Georgetown Cleaning Services -"; cout << "\n Customer Receipt -";

cout << "\n============================"; cout << "\n Item\tNumber\tPrice"; cout << "\n----------------------------"; cout << "\n Shirts\t" << Order.NumberOfShirts << "\t$" << TotalPriceShirts;

cout << "\n Pants\t" << Order.NumberOfPants << "\t$" << TotalPricePants; cout << "\n Misc\t" << Order.NumberOfMisc << "\t$" << TotalPriceMisc; cout << "\n============================"; cout << "\n Total Order:\t$" << TotalOrder; } catch(...) { cout << "\nSomething went wrong - Too Bad"; }

return 0; } //---------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Nevertheless, we have learned so far to catch exceptions and to throw them to a section that can handle them. One of the problems that could occur in a program is the clerk not entering valid numbers, which would imply that we want the compiler to multiply strings by constant numbers. Therefore, we can examine each number that the clerk would type and handle its exception in case of an invalid number. The simplest way you can check an integer is through the use of the isdigit() function. The only problem we will have at this time is that the isdigit() function checks only one digit or character. Here is one attempt at addressing the problem:

//--------------------------------------------------------------------------#include <iostream> #include <iomanip> using namespace std; //--------------------------------------------------------------------------// Constant prices of items, set by the store management const double PriceShirt = 0.99; const double PricePants = 1.75;

// Create an order object struct TCleaningOrder { int NumberOfShirts; int NumberOfPants; int NumberOfMisc; }; //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TCleaningOrder Order; double TotalPriceShirts, TotalPricePants; double PriceMisc, TotalPriceMisc; double TotalOrder;

cout << " - Georgetown Cleaning Services -\n"; cout << " - Customer Order Processing -\n";

try { cout << "Number of\n"; cout << "Shirts: "; cin >> Order.NumberOfShirts; if( isdigit(Order.NumberOfShirts) ) throw Order.NumberOfShirts; cout << "Pairs of Paints: "; cin >> Order.NumberOfPants; if( isdigit(Order.NumberOfPants) ) throw Order.NumberOfPants; cout << "Misc. Items(if none, type 0): "; cin >> Order.NumberMisc;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
if( isdigit(Order.NumberOfMisc) ) throw Order.NumberOfMisc;

// If there are miscalleanous items,... if(Order.NumberMisc > 0) { // let the user determine the price of this misc item cout << "Enter the price of each miscellanous item: "; cin >> PriceMisc; TotalPriceMisc = Order.NumberOfMisc * PriceMisc; } else TotalPriceMisc = 0.00;

TotalPriceShirts = Order.NumberOfShirts * PriceShirt; TotalPricePants = Order.NumberOfPants * PricePants;

TotalOrder = TotalPriceShirts + TotalPricePants + TotalPriceMisc;

cout << setiosflags(ios::fixed) << setprecision(2); cout << " - Georgetown Cleaning Services -"; cout << "\n Customer Receipt -";

cout << "\n============================"; cout << "\n Item\tNumber\tPrice"; cout << "\n----------------------------"; cout << "\n Shirts\t" << Order.NumberOfShirts << "\t$" << TotalPriceShirts;

cout << "\n Pants\t" << Order.NumberOfPants << "\t$" << TotalPricePants; cout << "\n Misc\t" << Order.NumberMisc << "\t$" << TotalPriceMisc; cout << "\n============================"; cout << "\n Total Order:\t$" << TotalOrder; } catch(const int n) { cout << n << " is not a valid number"; } catch(...) { cout << "\nSomething went wrong - Too Bad"; }

return 0; } //---------------------------------------------------------------------------

Practical Learning: Introduction to Class' Exceptions


Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
1. Create a C++ Console Application. 2. Save the first file as Main and save the project as Exceptional 3. Change the content of the Main.cpp file as follows:

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

class TCalculator { public: double Operand1; double Operand2; char Operator; }; //-------------------------------------------------------------------------int main(int argc, char* argv[]) { TCalculator Calc; double Result;

// Request two numbers from the user cout << "This program allows you to perform an operation on two numbers\n"; cout << "To proceed, enter two numbers\n";

try { cout << "First Number: cin >> Calc.Operand1; cout << "Operator: cin >> Calc.Operator; cout << "Second Number: "; cin >> Calc.Operand2; "; ";

// Make sure the user typed a valid operator if(Calc.Operator != '+' && Calc.Operator != '-' && Calc.Operator != '*' && Calc.Operator != '/') throw Calc.Operator; // Find out if the denominator is 0 if(Calc.Operator == '/') if(Calc.Operand2 == 0) throw 0;

// Perform an operation based on the user's choice

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
switch(Calc.Operator) { case '+': Result = Calc.Operand1 + Calc.Operand2; break;

case '-': Result = Calc.Operand1 - Calc.Operand2; break;

case '*': Result = Calc.Operand1 * Calc.Operand2; break;

case '/': Result = Calc.Operand1 / Calc.Operand2; break; }

// Display the result of the operation cout << "\n" << Calc.Operand1 << " " << Calc.Operator << " " << Calc.Operand2 << " = " << Result; } catch(const char n) { cout << "\nOperation Error: " << n << " is not a valid operator"; } catch(const int p) { cout << "\nBad Operation: Division by " << p << " not allowed"; }

return 0; } //-------------------------------------------------------------------------4. To test your program with two non-zero numbers. Here is an example:

This program allows you to perform an operation on two numbers To proceed, enter First number: 1450 Second number: 32

1450 / 32 = 45.3125

Press any key to continue...

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
5. Return to your programming environment 6. You can also use external functions that check and throw exceptions to other functions that can handle them. As an example, change the program as follows:

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

class TCalculator { public: double Operand1; double Operand2; char Operator; }; //-------------------------------------------------------------------------double CalcResult(const double x, const char p, const double y) { double R;

// Perform an operation based on the user's choice switch(p) { case '+': R = x + y; break;

case '-': R = x - y; break;

case '*': R = x * y; break;

case '/': if( y == 0 ) throw 0; R = x / y; break; }

return R; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//-------------------------------------------------------------------------int main(int argc, char* argv[]) { TCalculator Calc; double Result;

// Request two numbers from the user cout << "This program allows you to perform an operation of two numbers\n"; cout << "To proceed, enter two numbers\n";

try { cout << "First Number: cin >> Calc.Operand1; cout << "Operator: cin >> Calc.Operator; cout << "Second Number: "; cin >> Calc.Operand2; "; ";

// Make sure the user typed a valid operator if(Calc.Operator != '+' && Calc.Operator != '-' && Calc.Operator != '*' && Calc.Operator != '/') throw Calc.Operator;

Result = CalcResult(Calc.Operand1, Calc.Operator, Calc.Operand2);

// Display the result of the operation cout << "\n" << Calc.Operand1 << " " << Calc.Operator << " " << Calc.Operand2 << " = " << Result << "\n\n"; } catch(const char n) { cout << "\nOperation Error: " << n << " is not a valid operator"; } catch(const int p) { cout << "\nBad Operation: Division by " << p << " not allowed"; }

cout << "\nPress any key to continue...";

return 0; } //--------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
7. Test it and return to your programming environment.

Introduction to Exceptions in Classes


Probably the most basic use of exceptions you can make of a class is to let a class handle its own exceptions and hand the result, reliable results, to its clients. You handle exceptions in a class by using its method member. The main difference between a regular function and a class member function is that a regular function may need arguments from external functions to carry intermediary assignments. A member function of a class can use the member variables of the same class as if they were passed as arguments. You can use this feature of classes to handle exceptions effectively. This allows each class' method to handle its own exception(s), if any. We saw earlier that when an order is being processed, a clerk can enter an invalid number of items. Just like we did in the main() function, we can take care of this possible exception in a function where the order is being processed. Therefore, when solution to implement for this type of scenario is to declare a function that processes orders for the TCleaningOrder object. Here is an example:

#include <iostream> #include <iomanip>

using namespace std;

// Constant prices of items, set by the store management const double PriceShirt = 0.99; const double PricePants = 1.75;

// Create an order object struct TCleaningOrder { public: TCleaningOrder(); ~TCleaningOrder(); void ProcessOrder(); void DisplayReceipt(); private: int NumberOfShirts; int NumberOfPants; int NumberOfMisc; double TotalPriceShirts; double TotalPricePants; double TotalPriceMisc; double TotalOrder; }; //--------------------------------------------------------------------------TCleaningOrder::TCleaningOrder() : { } //--------------------------------------------------------------------------NumberOfShirts(0), NumberOfPants(0), NumberMisc(0)

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
TCleaningOrder::~TCleaningOrder() { } //--------------------------------------------------------------------------void TCleaningOrder::ProcessOrder() { double PriceMisc;

try { cout << "Number of\n"; cout << "Shirts: "; cin >> NumberOfShirts; if( isdigit(NumberOfShirts) ) throw NumberOfShirts; cout << "Pairs of Paints: "; cin >> NumberOfPants; if( isdigit(NumberOfPants) ) throw NumberOfPants; cout << "Misc. Items(if none, type 0): "; cin >> NumberMisc; if( isdigit(NumberOfMisc) ) throw NumberOfMisc;

// If there are miscalleanous items,... if(NumberMisc > 0) { // let the user determine the price of this misc item cout << "Enter the price of each miscellanous item: "; cin >> PriceMisc; TotalPriceMisc = NumberOfMisc * PriceMisc; } else TotalPriceMisc = 0.00;

TotalPriceShirts = NumberOfShirts * PriceShirt; TotalPricePants = NumberOfPants * PricePants;

TotalOrder = TotalPriceShirts + TotalPricePants + TotalPriceMisc; } catch(const int n) { cout << n << " is not a valid number"; } catch(...) { cout << "\nSomething went wrong - Too Bad"; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} //--------------------------------------------------------------------------void TCleaningOrder::DisplayReceipt() { cout << setiosflags(ios::fixed) << setprecision(2); cout << " - Georgetown Cleaning Services -"; cout << "\n Customer Receipt -";

cout << "\n============================"; cout << "\n Item\tNumber\tPrice"; cout << "\n----------------------------"; cout << "\n Shirts\t" << NumberOfShirts << "\t$" << TotalPriceShirts;

cout << "\n Pants\t" << NumberOfPants << "\t$" << TotalPricePants; cout << "\n Misc\t" << NumberOfMisc << "\t$" << TotalPriceMisc; cout << "\n============================"; cout << "\n Total Order:\t$" << TotalOrder; } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TCleaningOrder Order;

cout << " - Georgetown Cleaning Services -\n"; cout << " - Customer Order Processing -\n";

Order.ProcessOrder(); clrscr(); Order.DisplayReceipt();

return 0; } //---------------------------------------------------------------------------

Practical Learning: Class' Methods and their Exceptions


1. As an example, change the program as follows:

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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
class TCalculator { public: TCalculator(); void RequestOperands(); void setOperation(const double x, const char p, const double y); double CalcResult() const; void DisplayResult() const; private: double Operand1; double Operand2; char Operator; }; //-------------------------------------------------------------------------TCalculator::TCalculator() { } //-------------------------------------------------------------------------void TCalculator::RequestOperands() { try { cout << "First number: "; cin >> Operand1; cout << "Operator: "; cin >> Operator; cout << "Second number: "; cin >> Operand2;

// Make sure the user typed a valid operator if(Operator != '+' && Operator != '-' && Operator != '*' && Operator != '/') throw Operator;

setOperation(Operand1, Operator, Operand2); } catch(const char c) { cout << "Bad Operator: " << c << " is not a valid operator"; } } //-------------------------------------------------------------------------void TCalculator::setOperation(const double Num, const char c, const double Denom) { Operand1 = Num;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Operator = c; Operand2 = Denom; } //-------------------------------------------------------------------------double TCalculator::CalcResult() const { double R;

// Perform an operation based on the user's choice switch(Operator) { case '+': R = Operand1 + Operand2; break;

case '-': R = Operand1 - Operand2; break;

case '*': R = Operand1 * Operand2; break;

case '/': try { if( Operand2 == 0 ) throw "Division by zero not allowed";

R = Operand1 / Operand2; } catch(const char *Str) { cout << "\nBad Operator: " << Str; } break; }

return R; } //-------------------------------------------------------------------------void TCalculator::DisplayResult() const { double Result; CalcResult();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Result = CalcResult(); // Display the result of the operation cout << "\n" << Operand1 << " " << Operator << " " << Operand2 << " = " << Result; } //-------------------------------------------------------------------------int main(int argc, char* argv[]) { TCalculator Calc; double Number1, Number2, Result; char Oper;

cout << "This program allows you to perform an operation on two numbers\n"; cout << "To proceed, enter\n";

Calc.RequestOperands(); Calc.DisplayResult();

cout << "\nPress any key to continue...";

return 0; } //-------------------------------------------------------------------------2. Test the program and return to your programming environment

Exception-Oriented Classes
As in the earlier ProcessOrder() function, a method, and each necessary method, of a class can handle its own exceptions locally, perform the desired assignment, and send the result to the client that made the call. Alternatively, just like our main() function had been previously, you can create a member function of a class and let that function act as the central point of the class. Such a typical function is used to process transactions related to a class. To do this, implement the other member functions and let them throw the exceptions they encounter. While a member function is carrying its assignment, if it encounters an exception, it can throw it to the central function where the call was made. The central function would find the appropriate catch that can handle the exception. This scenario can be applied to set functions because a set function has the responsibility of checking or validating the value carried by its corresponding member variable. If the value is invalid, the set function can simply throw an exception and get out. Such a set function would look like this:

void TCleaningOrder::setShirts(const int Shirts) { if( isdigit(Shirts) ) throw Shirts; NumberOfShirts = Shirts; } This member function receives an argument and checks it. If the sent argument is not a valid digit, the setShirts() method throws an exception that carries the same argument that was sent. As you can see, and as we have done with throwing exceptions so far, the setShirts()

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
method doesn't care who (that is, what) sent the wrong argument; it simply throws it back and stops there. On the other hand, if the argument that was sent is good, the setShirts() method assigns it to the NumberOfShirts member variable (remember that it is the setShirts() responsibility to control the value that its corresponding member variable, in this case NumberOfShirts, carries). The client function that sent the request (the request consisted of asking the setShirts() function to validate the character) will need to know what to do with the thrown exception. Once a "central" function that passes arguments to other member methods that validate them, this "central" function doesn't need to throw any more exceptions, but since the others will likely or possibly throw exceptions, our "central function needs to be prepared to catch them and handle them appropriately. In the following example, the ProcessOrder() method acts as that "central" function:

//--------------------------------------------------------------------------#include <iostream> #include <iomanip>

using namespace std; //---------------------------------------------------------------------------

// Constant prices of items, set by the store management const double PriceShirt = 0.99; const double PricePants = 1.75;

// Create an order object struct TCleaningOrder { public: void setShirts(const int Shirts); int getShirts() { return NumberOfShirts; } void setPants(const int Pants); int getPants() { return NumberOfPants; } void setMisc(const int Misc); int getMisc() { return NumberOfMisc; } TCleaningOrder(); ~TCleaningOrder(); void ProcessOrder(); void DisplayReceipt(); private: int NumberOfShirts; int NumberOfPants; int NumberOfMisc; double TotalPriceShirts; double TotalPricePants; double TotalPriceMisc; double TotalOrder; }; //--------------------------------------------------------------------------TCleaningOrder::TCleaningOrder() : NumberOfShirts(0), NumberOfPants(0), NumberOfMisc(0)

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ } //--------------------------------------------------------------------------TCleaningOrder::~TCleaningOrder() { } //--------------------------------------------------------------------------void TCleaningOrder::setShirts(const int Shirts) { if( isdigit(Shirts) ) throw Shirts; NumberOfShirts = Shirts; } //--------------------------------------------------------------------------void TCleaningOrder::setPants(const int Pants) { if( isdigit(Pants) ) throw Pants; NumberOfPants = Pants; } //--------------------------------------------------------------------------void TCleaningOrder::setMisc(const int Misc) { if( isdigit(Misc) ) throw Misc; NumberOfMisc = Misc; } //--------------------------------------------------------------------------void TCleaningOrder::ProcessOrder() { double PriceMisc; int Shirts, Pants, Misc;

try { cout << "Number of\n"; cout << "Shirts: "; cin >> Shirts; setShirts(Shirts); cout << "Pairs of Paints: "; cin >> Pants; setPants(Pants); cout << "Misc. Items(if none, type 0): "; cin >> Misc; setMisc(Misc);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
// If there are miscalleanous items,... if(getMisc() > 0) { // let the user determine the price of this misc item cout << "Enter the price of each miscellanous item: "; cin >> PriceMisc; TotalPriceMisc = NumberOfMisc * PriceMisc; } else TotalPriceMisc = 0.00;

TotalPriceShirts = NumberOfShirts * PriceShirt; TotalPricePants = NumberOfPants * PricePants;

TotalOrder = TotalPriceShirts + TotalPricePants + TotalPriceMisc; } catch(const int n) { cout << n << " is not a valid number"; } catch(...) { cout << "\nSomething went wrong - Too Bad"; } } //--------------------------------------------------------------------------void TCleaningOrder::DisplayReceipt() { cout << setiosflags(ios::fixed) << setprecision(2); cout << " - Georgetown Cleaning Services -"; cout << "\n Customer Receipt -";

cout << "\n============================"; cout << "\n Item\tNumber\tPrice"; cout << "\n----------------------------"; cout << "\n Shirts\t" << NumberOfShirts << "\t$" << TotalPriceShirts;

cout << "\n Pants\t" << NumberOfPants << "\t$" << TotalPricePants; cout << "\n Misc\t" << NumberOfMisc << "\t$" << TotalPriceMisc; cout << "\n============================"; cout << "\n Total Order:\t$" << TotalOrder; } //--------------------------------------------------------------------------int main(int argc, char* argv[])

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ TCleaningOrder Order;

cout << " - Georgetown Cleaning Services -\n"; cout << " - Customer Order Processing -\n";

Order.ProcessOrder(); clrscr(); Order.DisplayReceipt();

return 0; } //---------------------------------------------------------------------------

Practical Learning: Improving Class' Exceptions


For our exercise, we will create a member function for a Calculator class. We use this function to proces a calculation. We also prepare this function to handle various exceptions that can be (or would be) thrown by other functions. The exceptions can be thrown based on a wrong operand or a wrong operator. The class can be implemented in a program as follows (some functions, such as the get methods were added to allow external functions to communicate with the member variables of the class). 1. Change the content of the file as follows:

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

class TCalculator { public: TCalculator(); TCalculator(char* Oper1, char Opr, char* Oper2); void RequestOperands(); void setOperand1(const char* Oper1); double getOperand1() const; void setOperand2(const char *Oper2); double getOperand2() const; void setOperator(const char Opr); char getOperator() const; void setOperation(const char* x, const char p, const char* y); double CalcResult() const; void DisplayResult() const; private: double Operand1;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
double Operand2; char Operator; }; //-------------------------------------------------------------------------TCalculator::TCalculator() { } //-------------------------------------------------------------------------TCalculator::TCalculator(char* Oper1, char Opr, char* Oper2) { setOperand1(Oper1); setOperator(Opr); setOperand2(Oper2); } //-------------------------------------------------------------------------void TCalculator::RequestOperands() {

char Number1[40], Number2[40]; char Oper;

try { cout << "To proceed, enter\n"; cout << "First Number: "; cin >> Number1; cout << "An Operator: "; cin >> Oper; cout << "Second Number: "; cin >> Number2;

setOperand1(Number1); setOperator(Oper); setOperand2(Number2);

CalcResult(); } catch(const char n) { cout << "\nOperation Error: " << n << " is not a valid operator"; } catch(const char *BadOperand) { cout << "\nError: " << BadOperand << " is not a valid number"; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
catch(const int n) { cout << "\nBad Operation: Division by " << n << " not allowed"; } } //-------------------------------------------------------------------------void TCalculator::setOperand1(const char* Oper1) { for(unsigned int i = 0; i < strlen(Oper1); i++) if( (!isdigit(Oper1[i])) && (Oper1[i] != '.') ) throw Oper1;

Operand1 = atof(Oper1); }

//-------------------------------------------------------------------------double TCalculator::getOperand1() const { return Operand1; }

//-------------------------------------------------------------------------void TCalculator::setOperand2(const char* Oper2) { for(unsigned int i = 0; i < strlen(Oper2); i++) if( (!isdigit(Oper2[i])) && (Oper2[i] != '.') ) throw Oper2;

Operand2 = atof(Oper2); }

//-------------------------------------------------------------------------double TCalculator::getOperand2() const { return Operand2; }

//-------------------------------------------------------------------------void TCalculator::setOperator(const char Symbol) { if(Symbol != '+' && Symbol != '-' && Symbol != '*' && Symbol != '/') throw Symbol;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Operator = Symbol; } //-------------------------------------------------------------------------char TCalculator::getOperator() const { return Operator; } //-------------------------------------------------------------------------void TCalculator::setOperation(const char* Oper1, const char Opr, const char* Oper2) { setOperand1(Oper1); setOperator(Opr); setOperand2(Oper2); } //-------------------------------------------------------------------------double TCalculator::CalcResult() const { double R;

// Perform an operation based on the user's choice switch(Operator) { case '+': R = Operand1 + Operand2; break;

case '-': R = Operand1 - Operand2; break;

case '*': R = Operand1 * Operand2; break;

case '/': try { if( Operand2 == 0 ) throw "Division by zero not allowed";

R = Operand1 / Operand2; } catch(const char *Str) {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\nBad Operator: " << Str; } break; }

return R; } //-------------------------------------------------------------------------void TCalculator::DisplayResult() const { double Result; CalcResult();

Result = CalcResult(); // Display the result of the operation cout << "\n" << Operand1 << " " << Operator << " " << Operand2 << " = " << Result; } //-------------------------------------------------------------------------int main(int argc, char* argv[]) { TCalculator Calc; double Number1, Number2, Result; char Oper;

cout << "This program allows you to perform an operation on two numbers\n";

Calc.RequestOperands(); Calc.DisplayResult();

cout << "\nPress any key to continue...";

return 0; } //-------------------------------------------------------------------------2. Test the program and return to your programming environment. 3. Just as done with the functions, you can show that a function throws one or more exceptions in its declaration. To do this, in the class, on the right side of the function that throws an exception, type the throw keyword followed by parentheses in which you would provide the type of exception that the following would throw. To apply this, change the function as follows:

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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//--------------------------------------------------------------------------

class TCalculator { public: TCalculator(); TCalculator(char* Oper1, char Opr, char* Oper2); void RequestOperands(); void setOperand1(const char* Oper1) throw(const char*); double getOperand1() const; void setOperand2(const char *Oper2) throw(const char*); double getOperand2() const; void setOperator(const char Opr) throw(const char); char getOperator() const; void setOperation(const char* x, const char p, const char* y); double CalcResult() const; void DisplayResult() const; private: double Operand1; double Operand2; char Operator; }; //-------------------------------------------------------------------------TCalculator::TCalculator() { } //-------------------------------------------------------------------------TCalculator::TCalculator(char* Oper1, char Opr, char* Oper2) { setOperand1(Oper1); setOperator(Opr); setOperand2(Oper2); } //-------------------------------------------------------------------------void TCalculator::RequestOperands() { char Number1[40], Number2[40]; char Oper;

try { cout << "To proceed, enter\n"; cout << "First Number: "; cin >> Number1; cout << "An Operator: "; cin >> Oper; cout << "Second Number: "; cin >> Number2;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
setOperand1(Number1); setOperator(Oper); setOperand2(Number2);

CalcResult(); } catch(const char n) { cout << "\nOperation Error: " << n << " is not a valid operator"; } catch(const char *BadOperand) { cout << "\nError: " << BadOperand << " is not a valid number"; } catch(const int n) { cout << "\nBad Operation: Division by " << n << " not allowed"; } } //-------------------------------------------------------------------------void TCalculator::setOperand1(const char* Oper1) throw(const char*) { for(unsigned int i = 0; i < strlen(Oper1); i++) if( (!isdigit(Oper1[i])) && (Oper1[i] != '.') ) throw Oper1;

Operand1 = atof(Oper1); } //-------------------------------------------------------------------------double TCalculator::getOperand1() const { return Operand1; } //-------------------------------------------------------------------------void TCalculator::setOperand2(const char* Oper2) throw(const char*) { for(unsigned int i = 0; i < strlen(Oper2); i++) if( (!isdigit(Oper2[i])) && (Oper2[i] != '.') ) throw Oper2;

Operand2 = atof(Oper2); }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//-------------------------------------------------------------------------double TCalculator::getOperand2() const { return Operand2; } //-------------------------------------------------------------------------void TCalculator::setOperator(const char Symbol) throw(const char) { if(Symbol != '+' && Symbol != '-' && Symbol != '*' && Symbol != '/') throw Symbol;

Operator = Symbol; } //-------------------------------------------------------------------------. . . 4. Test the program and return to your programming environment.

Separating the Object from its Implementation


As we did in previous lessons, you don't need to keep a class and its source file in the same file. You can separate the header and the C++ source in separate files. This is done in the same way you would do by creating a unit.

Practical Learning: Creating a Class


1. Create a new C++ Console Application. 2. Create a folder called Exceptional2 3. Save Unit1 as Main and save the project as Exceptions 4. To create a new class, on the main menu, click File -> New... or File -> New -> Other... 5. From the New property sheet of the New Object dialog box, double-click Unit 6. Save the class as Calculator 7. Click the Calculator.h tab and change the content of the file as follows:

//-------------------------------------------------------------------------#ifndef CalculatorH #define CalculatorH //-------------------------------------------------------------------------class TCalculator { public: TCalculator(); TCalculator(char* Oper1, char Opr, char* Oper2);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
void RequestOperands(); void setOperand1(const char* Oper1) throw(const char*); double getOperand1() const; void setOperand2(const char *Oper2) throw(const char*); double getOperand2() const; void setOperator(const char Opr) throw(const char); char getOperator() const; void setOperation(const char* x, const char p, const char* y); double CalcResult() const; void DisplayResult() const; private: double Operand1; double Operand2; char Operator; }; //-------------------------------------------------------------------------#endif 8. Click the Calculator.cpp tab and change its content as follows:

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

#include "Calculator.h" //-------------------------------------------------------------------------TCalculator::TCalculator() { } //-------------------------------------------------------------------------TCalculator::TCalculator(char* Oper1, char Opr, char* Oper2) { setOperand1(Oper1); setOperator(Opr); setOperand2(Oper2); } //-------------------------------------------------------------------------void TCalculator::RequestOperands() { char Number1[40], Number2[40]; char Oper;

try { cout << "To proceed, enter\n"; cout << "First Number: "; cin >> Number1;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "An Operator: "; cin >> Oper; cout << "Second Number: "; cin >> Number2;

setOperand1(Number1); setOperator(Oper); setOperand2(Number2);

CalcResult(); } catch(const char n) { cout << "\nOperation Error: " << n << " is not a valid operator"; } catch(const char *BadOperand) { cout << "\nError: " << BadOperand << " is not a valid number"; } catch(const int n) { cout << "\nBad Operation: Division by " << n << " not allowed"; } } //-------------------------------------------------------------------------void TCalculator::setOperand1(const char* Oper1) throw(const char*) { for(unsigned int i = 0; i < strlen(Oper1); i++) if( (!isdigit(Oper1[i])) && (Oper1[i] != '.') ) throw Oper1;

Operand1 = atof(Oper1); } //-------------------------------------------------------------------------double TCalculator::getOperand1() const { return Operand1; } //-------------------------------------------------------------------------void TCalculator::setOperand2(const char* Oper2) throw(const char*) { for(unsigned int i = 0; i < strlen(Oper2); i++) if( (!isdigit(Oper2[i])) && (Oper2[i] != '.') ) throw Oper2;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Operand2 = atof(Oper2); }

//-------------------------------------------------------------------------double TCalculator::getOperand2() const { return Operand2; } //-------------------------------------------------------------------------void TCalculator::setOperator(const char Symbol) throw(const char) { if(Symbol != '+' && Symbol != '-' && Symbol != '*' && Symbol != '/') throw Symbol;

Operator = Symbol; } //-------------------------------------------------------------------------char TCalculator::getOperator() const { return Operator; } //-------------------------------------------------------------------------void TCalculator::setOperation(const char* Oper1, const char Opr, const char* Oper2) { setOperand1(Oper1); setOperator(Opr); setOperand2(Oper2); } //-------------------------------------------------------------------------double TCalculator::CalcResult() const { double R;

// Perform an operation based on the user's choice switch(Operator) { case '+': R = Operand1 + Operand2; break;

case '-': R = Operand1 - Operand2;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
break;

case '*': R = Operand1 * Operand2; break;

case '/': try { if( Operand2 == 0 ) throw "Division by zero not allowed";

R = Operand1 / Operand2; } catch(const char *Str) { cout << "\nBad Operator: " << Str; } break; }

return R; } //-------------------------------------------------------------------------void TCalculator::DisplayResult() const { double Result; CalcResult();

Result = CalcResult(); // Display the result of the operation cout << "\n" << Operand1 << " " << Operator << " " << Operand2 << " = " << Result; } //-------------------------------------------------------------------------9. Click the Main.cpp tab and change its content as follows:

//-------------------------------------------------------------------------#include <iostream> using namespace std; #include "Calculator.h" //-------------------------------------------------------------------------int main(int argc, char* argv[]) { TCalculator Calc;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
double Number1, Number2, Result; char Oper;

cout << "This program allows you to perform an operation on two numbers\n";

Calc.RequestOperands(); Calc.DisplayResult();

return 0; } //-------------------------------------------------------------------------10. Test the program

Previous

Copyright 2000-2005 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Composition and Inheritance


Composing an Object
A common technique used to create programs with various objects consists of declaring one object inside of another. Once you have or know the object to use, you can declare it like a regular member of the object. Like another member variable, you can initialize the object and even manipulate its members.

Using an Enumerator as an Object Member


The enumerators we have used so far were intended to simply carry a list of constant integers. This is useful for conditional statements where a switch or an ifelse statements would need to perform comparisons. As an example, suppose we create the following class:
//--------------------------------------------------------------------------#ifndef LabelTypeH #define LabelTypeH //--------------------------------------------------------------------------#include <string> using namespace std; //--------------------------------------------------------------------------enum TPrintCategory { pcInkjet = 1, pcLaser, pcMultiPurpose, pcUnspecified }; //--------------------------------------------------------------------------class TLabelType { public: TLabelType(); TLabelType(unsigned int m, string n, string c, int t); TLabelType(const TLabelType& Label); ~TLabelType(); void setModelNumber(const unsigned int m) { ModelNumber = m; } void setName(const string n) { Name = n; } void setColor(const string c) { Color = c; } void setPrintType(const int i) { PrintType = i; } unsigned int getModelNumber() const; string getName() const; string getColor() const; string getPrintType() const; private: unsigned int ModelNumber; string Name; string Color; int PrintType; }; //--------------------------------------------------------------------------#endif

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
To demonstrate the use of this new enumerator, we could implement the getPrintType() function as follows:
//---------------------------------------------------------------------------

#include "LabelType.h"

//--------------------------------------------------------------------------TLabelType::TLabelType() : ModelNumber(0), Name("None"), Color("White"), PrintType(3) { } //--------------------------------------------------------------------------TLabelType::TLabelType(unsigned int m, string n, string c, int t) : ModelNumber(m), Name(n), Color(c), PrintType(t) { } //--------------------------------------------------------------------------TLabelType::TLabelType(const TLabelType& Label) : ModelNumber(Label.ModelNumber), Name(Label.Name), Color(Label.Color), PrintType(Label.PrintType) { } //--------------------------------------------------------------------------TLabelType::~TLabelType() { } //--------------------------------------------------------------------------unsigned int TLabelType::getModelNumber() const { return ModelNumber; } //--------------------------------------------------------------------------string TLabelType::getName() const {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return Name; } //--------------------------------------------------------------------------string TLabelType::getColor() const { return Color; } //--------------------------------------------------------------------------string TLabelType::getPrintType() const { string PrintingType;

switch( PrintType ) { case pcInkjet: PrintingType = "Injet"; break; case pcLaser: PrintingType = "Laser"; break; case pcMultiPurpose: PrintingType = "Multi-Purpose"; break; default: PrintingType = "Unspeficied"; }

return PrintingType; } //---------------------------------------------------------------------------

We can test our object using the main() function as follows:


//--------------------------------------------------------------------------#include <iostream> using namespace std; //--------------------------------------------------------------------------#include "LabelType.h" //---------------------------------------------------------------------------

int main(int argc, char* argv[]) { TLabelType Label;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "A label with default characteristics"; cout << "\nModel Number: " << Label.getModelNumber(); cout << "\nModel Name: " << Label.getName(); cout << "\nMain Color: " << Label.getColor(); cout << "\nPrinting Type: " << Label.getPrintType(); cout << "\n\n";

Label.setModelNumber(475832); Label.setName("Blanc d'Azure"); Label.setColor("Old Sand"); Label.setPrintType(2);

cout << "Custom Label"; cout << "\nModel Number: " << Label.getModelNumber(); cout << "\nModel Name: " << Label.getName(); cout << "\nMain Color: " << Label.getColor(); cout << "\nPrinting Type: " << Label.getPrintType();

return 0; } //---------------------------------------------------------------------------

Besides representing a list of constant integers, an enumerator can also behave like a small object, making it one of the most commonly used members of objects in C++ Builder applications. As a semicomplete data type, an enumerator can be used to create an integer data type and make it a member of another object. The advantage of using an enumerator is that, unlike a regular integer, an enumerator and its members names are a little more explicit. You will see this technique used on many objects of the Visual Component Library. We have learned that, when defining an enumerator, we can supply the names of its members. Here is an example:
enum TAdhesive { adNone, adRemovable, adNonRemovable };

Once the enumerator is defined, we can declare it as a member of an object where needed. The enumerator becomes a data type. It can be declared as a variable:
TAdhesive Adhesive;

It can also be passed as an argument:


TLabelType(long m, string c, string n, TAdhesive a);

Or it can de used as a return type of a function or a method:


TAdhesive getAdhesive();

These characteristics of an enumerator are exemplified in the new version of the TLabelType object as follows:
//--------------------------------------------------------------------------#ifndef LabelTypeH #define LabelTypeH //---------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#include <iostream> using namespace std; //--------------------------------------------------------------------------enum TPrintCategory { pcInkjet = 1, pcLaser, pcMultiPurpose, pcUnspecified }; enum TAdhesive { adNone, adRemovable, adNonRemovable }; //--------------------------------------------------------------------------class TLabelType { public: TLabelType(); TLabelType(unsigned int m, string n, string c, int t, TAdhesive a); TLabelType(const TLabelType& Label); ~TLabelType(); void setModelNumber(const unsigned int m) { ModelNumber = m; } void setName(const string n) { Name = n; } void setColor(const string c) { Color = c; } void setPrintType(const int i) { PrintType = i; } void setAdhesive(TAdhesive a) { Adhesive = a; } unsigned int getModelNumber() const; string getName() const; string getColor() const; string getPrintType() const; TAdhesive getAdhesive() const;

private: unsigned int ModelNumber; string Name; string Color; int PrintType; TAdhesive Adhesive; }; //--------------------------------------------------------------------------#endif

When implementing the object, if you want to initialize a variable identified by an enumerator, make sure you use a valid name as one of the members of the enumerator. An example would be:
Adhesive = adNonRemovable;

You could be tempted to use a constant integer to initialize such a variable. Here is an example:
Adhesive = 1;

But this is a bad idea. First the use of the enumerator would appear pointless and unprofessional because this would deceive the purpose of using an enumerator. Second, if you initialize the variable using a valid name, the compiler would have the responsibility of finding the corresponding value of the member; if you decide to use a (random) integer, no matter how confident you are, you are running the risk of using a value unrecognized by the enumerator. Thirdly, most compilers would display a warning; and you should not neglect warnings.

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
To implement the functions whose return type or arguments are enumerator, proceed as you would for other regular data types. Here is the source file of the TLabelType object:
#include "LabelType.h" //--------------------------------------------------------------------------TLabelType::TLabelType() : ModelNumber(0), Name("None"), Color("White"), PrintType(3), Adhesive(adNone) { } //--------------------------------------------------------------------------TLabelType::TLabelType(unsigned int m, string n, string c, int t, TAdhesive a) : ModelNumber(m), Name(n), Color(c), PrintType(t), Adhesive(a) { } //--------------------------------------------------------------------------TLabelType::TLabelType(const TLabelType& Label) : ModelNumber(Label.ModelNumber), Name(Label.Name), Color(Label.Color), PrintType(Label.PrintType), Adhesive(Label.Adhesive) { } //--------------------------------------------------------------------------...

//--------------------------------------------------------------------------TAdhesive TLabelType::getAdhesive() const { return Adhesive; } //---------------------------------------------------------------------------

Using the main() function, a test of the program would be as follows:


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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#include <iostream> using namespace std; //--------------------------------------------------------------------------#include "LabelType.h" //---------------------------------------------------------------------------

int main(int argc, char* argv[]) { TLabelType Label;

cout << "A label with default characteristics"; cout << "\nModel Number: " << Label.getModelNumber(); cout << "\nModel Name: cout << "\nMain Color: " << Label.getName(); " << Label.getColor();

cout << "\nPrinting Type: " << Label.getPrintType(); cout << "\nAdhesive Type: " << Label.getAdhesive(); cout << "\n\n";

Label.setModelNumber(475832); Label.setName("Blanc d'Azure"); Label.setColor("Old Sand"); Label.setPrintType(2); Label.setAdhesive(adRemovable);

cout << "Custom Label"; cout << "\nModel Number: " << Label.getModelNumber(); cout << "\nModel Name: cout << "\nMain Color: " << Label.getName(); " << Label.getColor();

cout << "\nPrinting Type: " << Label.getPrintType(); cout << "\nAdhesive Type: " << Label.getAdhesive();

return 0; } //---------------------------------------------------------------------------

Using Enumerators and Classes


1. Start your programming environment. Create a new C++ based Console Application 2. Save the project in a new folder called Student2. Save the first file as Main and the project as ROSH 3. Create a new class and save it as Students 4. Create the header file as follows:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//--------------------------------------------------------------------------#ifndef StudentsH #define StudentsH #include <iostream> //--------------------------------------------------------------------------enum TStudentGender { sgUnspecified, sgMale, sgFemale }; //--------------------------------------------------------------------------class TStudents { public: TStudents(); TStudents(string fn, string ln, int DOB, int MOB, int YOB, int g); TStudents(string fn, string ln); TStudents(int DOB, int MOB, int YOB); TStudents(const TStudents& S); ~TStudents(); void setFirstName(const string f) { FirstName = f; } string getFirstName() const { return FirstName; } void setLastName(const string l) { LastName = l; } string getLastName() const { return LastName; } void setDayOfBirth(const int d) { DayOfBirth = d; } int getDayOfBirth() const { return DayOfBirth; } void setMonthOfBirth(const int m) { MonthOfBirth = m; } int getMonthOfBirth() const { return MonthOfBirth; } void setYearOfBirth(const int y) { YearOfBirth = y; } int getYearOfBirth() const { return YearOfBirth; } void setGender(const int g) { Gender = g; } string getGender() const;

private: string FirstName; string LastName; int DayOfBirth; int MonthOfBirth; int YearOfBirth; int Gender; }; //--------------------------------------------------------------------------#endif

5. Implement the source file as follows:


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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
using namespace std;

#include "Students.h" //---------------------------------------------------------------------------

TStudents::TStudents() : FirstName("John"), LastName("Doe"), DayOfBirth(5), MonthOfBirth(10), YearOfBirth(1988), Gender(0) { } //--------------------------------------------------------------------------TStudents::TStudents(string fn, string ln, int DOB, int MOB, int YOB, int g) : FirstName(fn), LastName(ln), DayOfBirth(DOB), MonthOfBirth(MOB), YearOfBirth(YOB), Gender(g) { } //--------------------------------------------------------------------------TStudents::TStudents(string fn, string ln) : FirstName(fn), LastName(ln), DayOfBirth(1), MonthOfBirth(1), YearOfBirth(1990) { } //--------------------------------------------------------------------------TStudents::TStudents(int DOB, int MOB, int YOB) { FirstName = "Peter"; LastName = "Mukoko"; DayOfBirth = DOB; MonthOfBirth = MOB; YearOfBirth = YOB; } //--------------------------------------------------------------------------TStudents::TStudents(const TStudents& Stud) : FirstName(Stud.FirstName), LastName(Stud.LastName), DayOfBirth(Stud.DayOfBirth), MonthOfBirth(Stud.MonthOfBirth), YearOfBirth(Stud.YearOfBirth), Gender(Stud.Gender)

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ } //--------------------------------------------------------------------------TStudents::~TStudents() { } //--------------------------------------------------------------------------string TStudents::getGender() const { if( Gender == sgMale ) return "Male"; else if( Gender == sgFemale ) return "Female"; else return "Unspecified"; } //---------------------------------------------------------------------------

6. To prepare a test of the program, change the content of the Main.cpp file as follows:
//--------------------------------------------------------------------------#include <iomanip> #include <conio.h> using namespace std; //--------------------------------------------------------------------------#include "Students.h"

//--------------------------------------------------------------------------int main(int argc, char* argv[]) { TStudents S; string FN, LN; int Day, Month, Year, Gdr;

cout << "Enter the student's information\n"; cout << "First Name: "; cin >> FN; cout << "Last Name: "; cin >> LN; cout << "Day of Birth: "; cin >> Day; cout << "Month of Birth: "; cin >> Month; cout << "Year of Birth: "; cin >> Year; cout << "Gender: "; cout << "\n1 - Male" << "\n2 - Female" << "\n3 - Unspecified"

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
<< "\nYour Choice: "; cin >> Gdr;

S.setFirstName(FN); S.setLastName(LN); S.setDayOfBirth(Day); S.setMonthOfBirth(Month); S.setYearOfBirth(Year); S.setGender(Gdr);

system("cls");

cout << "======================================="; cout << "\nStudent Registration"; cout << "\nFull Name: " << S.getFirstName() << " " << S.getLastName(); cout << "\nDate of Birth: " << S.getDayOfBirth() << "/" << S.getMonthOfBirth() << "/" << S.getYearOfBirth(); cout << "\nGender: " << S.getGender();

return 0; } //---------------------------------------------------------------------------

7. To test the program, on the main menu, click Run -> Run. 8. After testing the program, return to your programming environment.

Direct Access of a Member of Another Object


The most basic technique of making one object a member of another is to simply declare it as if it were a (regular) member variable, using the same technique you would for another variable. Suppose you add the following class to the label project:
//--------------------------------------------------------------------------#ifndef LabelDimensionsH #define LabelDimensionsH using namespace std; //--------------------------------------------------------------------------class TDimensions { public: TDimensions(Double L = 0.00, Double W = 0.00);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
~TDimensions(); void setDimensions(const Double L, const Double H); Double getLength() const { return Length; } Double getHeight() const { return Height; } Double Area() const; private: Double Length; Double Height; }; //--------------------------------------------------------------------------#endif

And suppose you implement the class as follows:


//--------------------------------------------------------------------------using namespace std;

#include "LabelDimensions.h" //---------------------------------------------------------------------------

//--------------------------------------------------------------------------TDimensions::TDimensions(Double L, Double W) : Length(L), Height(H) { //TODO: Add your source code here } //--------------------------------------------------------------------------TDimensions::~TDimensions() { //TODO: Add your source code here } //--------------------------------------------------------------------------void TDimensions::setDimensions(const Double L, const Double H) { Length = L; Height = H; } //--------------------------------------------------------------------------Double TDimensions::Area() const { return Length * Height; } //---------------------------------------------------------------------------

Here is an example of making it a member of the TLabelType class:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//--------------------------------------------------------------------------#ifndef LabelTypeH #define LabelTypeH //--------------------------------------------------------------------------#include <iostream> using namespace std; #include "LabelDimensions.h" //--------------------------------------------------------------------------enum TPrintCategory { pcInkjet = 1, pcLaser, pcMultiPurpose, pcUnspecified }; enum TAdhesive { adNone, adRemovable, adNonRemovable }; //--------------------------------------------------------------------------class TLabelType { public: ... TDimensions Dim; private: ... }; //--------------------------------------------------------------------------#endif

When an object B is made a member of another object A, you can access the member variables member object B using the member access operator (.). As a result, you would be using two operators. After declaring the main object, the first operator is used to access the members main object, usually the constructor. The second operator, if used, allows accessing a member dependent object. Here is an example:
//--------------------------------------------------------------------------#include <iomanip> using namespace std; //--------------------------------------------------------------------------#include "LabelType.h" #include "LabelDimensions.h" //---------------------------------------------------------------------------

of the period of the of the

int main(int argc, char* argv[]) { TLabelType LblType;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
string AdhesiveType;

cout << "A label with default characteristics"; cout << setiosflags(ios::fixed) << setprecision(2); cout << "\n Dimensions: " << LblType.Dim.getLength() << " * " << LblType.Dim.getHeight(); cout << "\n Area: " << LblType.Dim.Area(); cout << "\n Model Number: " << LblType.getModelNumber(); cout << "\n Model Name: " << LblType.getName(); cout << "\n Main Color: " << LblType.getColor(); cout << "\n Printing Type: " << LblType.getPrintType(); cout << "\n Adhesive Type: " << LblType.getAdhesive(); cout << "\n\n";

LblType.Dim.setDimensions(4.25, 2.50); LblType.setModelNumber(38946); LblType.setName("Coast Layer"); LblType.setColor("Bone White"); LblType.setPrintType(2); LblType.setAdhesive(adRemovable);

if( LblType.getAdhesive() == adRemovable ) AdhesiveType = "Removable"; else if( LblType.getAdhesive() == adNonRemovable ) AdhesiveType = "Non-Removable"; else AdhesiveType = "None";

cout << "Customer Defined Label"; cout << "\n Dimensions: " << LblType.Dim.getLength() << " * " << LblType.Dim.getHeight(); cout << "\n Area: " << LblType.Dim.Area(); cout << "\n Model Number: " << LblType.getModelNumber(); cout << "\n Model Name: " << LblType.getName(); cout << "\n Main Color: " << LblType.getColor(); cout << "\n Printing Type: " << LblType.getPrintType(); cout << "\n Adhesive Type: " << AdhesiveType;

return 0; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//---------------------------------------------------------------------------

The period operator can also be used when allowing the user to provide the properties of the object. Using this ability, you can design a program to request the needed values.

An Object as a Member Variable


1. Add a new class and save it as Grades 2. To declare one object as a member of another object, add a new class saved as Grades and create its TGrades class as follows:
//--------------------------------------------------------------------------#ifndef GradesH #define GradesH #include "Students.h" //--------------------------------------------------------------------------class TGrades { public: TGrades(); TGrades(double e, double s, double h, double g, double c, double o, double m, double p, double r, double t); ~TGrades(); void setEnglish(const double e) { English = e; } double getEnglish() const { return English; } void setSecondLng(const double s) { SecondLng = s; } double getSecondLng() const { return SecondLng; } void setHistory(const double h) { History = h; } double getHistory() const { return History; } void setGeography(const double g) { Geography = g; } double getGeography() const { return Geography; } void setChemistry(const double c) { Chemistry = c; } double getChemistry() const { return Chemistry; } void setSociology(const double o) { Sociology = o; } double getSociology() const { return Sociology; } void setMath(const double m) { Math = m; } double getMath() const { return Math; } void setCompSc(const double p) { CompSc = p; } double getCompSc() const { return CompSc; } void setMorale(const double a) { Morale = a; } double getMorale() const { return Morale; } void setSports(const double t) { Sports = t; } double getSports() const { return Sports; } double CalcTotal() const; double CalcMean() const;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
TStudents Identification; private: double English; double SecondLng; double History; double Geography; double Chemistry; double Sociology; double Math; double CompSc; double Morale; double Sports; }; //--------------------------------------------------------------------------#endif

3. Implement the TGrades class as follows:


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

using namespace std;

#include "Grades.h" //---------------------------------------------------------------------------

TGrades::TGrades() { English = 0.00; SecondLng = 0.00; History = 0.00; Geography = 0.00; Chemistry = 0.00; Sociology = 0.00; Math = 0.00; CompSc = 0.00; Morale = 0.00; Sports = 0.00; } //--------------------------------------------------------------------------TGrades::TGrades(double e, double s, double h, double g, double c, double o, double m, double p, double r, double t) { English = e;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
SecondLng = s; History = h; Geography = g; Chemistry = c; Sociology = o; Math = m; CompSc = p; Morale = r; Sports = t; } //--------------------------------------------------------------------------TGrades::~TGrades() { //TODO: Add your source code here } //--------------------------------------------------------------------------double TGrades::CalcTotal() const { double Total = English + SecondLng + History + Geography + Chemistry + Sociology + Math + CompSc + Morale + Sports;

return Total; } //--------------------------------------------------------------------------double TGrades::CalcMean() const { return CalcTotal() / 10; } //---------------------------------------------------------------------------

4. To prepare a test of the program, change the Main.cpp file as follows:


//--------------------------------------------------------------------------#include <iomanip> #include <conio.h> using namespace std; //--------------------------------------------------------------------------#include "Grades.h"

//--------------------------------------------------------------------------int main(int argc, char* argv[]) { TGrades G;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
string FN, LN; int Day, Month, Year, Gdr;

cout << "Enter the student's information\n"; cout << "First Name: "; cin >> FN; cout << "Last Name: "; cin >> LN; cout << "Day of Birth: "; cin >> Day; cout << "Month of Birth: "; cin >> Month; cout << "Year of Birth: "; cin >> Year; cout << "Gender: "; cout << "\n1 - Male" << "\n2 - Female" << "\n3 - Unspecified" << "\nYour Choice: "; cin >> Gdr;

G.Identification.setFirstName(FN); G.Identification.setFirstName(FN); G.Identification.setLastName(LN); G.Identification.setDayOfBirth(Day); G.Identification.setMonthOfBirth(Month); G.Identification.setYearOfBirth(Year); G.Identification.setGender(Gdr);

double Language1, Language2, Hist, Geog, Chem, Soc, Math, CompSc, Mor, Sport;

cout << "English: "; cin >> Language1; cout << "2nd Language: "; cin >> Language2; cout << "History: "; cin >> Hist; cout << "Geography: "; cin >> Geog; cout << "Chemistry: "; cin >> Chem; cout << "Sociology: "; cin >> Soc; cout << "Mathematics: "; cin >> Math; cout << "Comp Sciences: "; cin >> CompSc; cout << "Morale: "; cin >> Mor; cout << "Sports: "; cin >> Sport;

G.setEnglish(Language1); G.setSecondLng(Language2); G.setHistory(Hist); G.setGeography(Geog);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
G.setChemistry(Chem); G.setSociology(Soc); G.setMath(Math); G.setCompSc(CompSc); G.setMorale(Mor); G.setSports(Sport);

system("cls");

cout << "======================================="; cout << "\nStudent Registration"; cout << "\nFull Name: " << G.Identification.getFirstName() << " " << G.Identification.getLastName(); cout << "\nDate of Birth: " << G.Identification.getDayOfBirth() << "/" << G.Identification.getMonthOfBirth() << "/" << G.Identification.getYearOfBirth(); cout << "\nGender: " << G.Identification.getGender(); cout << "\n------------------------------------------"; cout << setiosflags(ios::fixed) << setprecision(2); cout << "\n\tEnglish: " << G.getEnglish(); cout << "\n\tLanguage 2: " << G.getSecondLng(); cout << "\n\tHistory: " << G.getHistory(); cout << "\n\tGeography: " << G.getGeography(); cout << "\n\tChemistry: " << G.getChemistry(); cout << "\n\tSociology: " << G.getSociology(); cout << "\n\tMathematics: " << G.getMath(); cout << "\n\tComp Sciences: " << G.getCompSc(); cout << "\n\tMorale: " << G.getMorale(); cout << "\n\tSports: " << G.getSports(); cout << "\n------------------------------------------"; cout << "\n\tTotal: " << G.CalcTotal() << "\tMean: " << G.CalcMean(); cout << "\n=======================================";

return 0; } //---------------------------------------------------------------------------

5. To test the program, on the Debug toolbar, click the Run button . An example would be:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

6. Return to your programming environment.

A Class as a Friend
Like a function, a class can be made a friend of another class. When class A is made a friend of class B, all members of class B are directly accessible to the members of class A; this includes private (and protected) members:

Friendship is not mutual: the fact that class A is made a friend of class B does not imply that class B is made a friend of class A. In other words, the fact that the (private and protected) members of class B are accessible to the members of class A does not mean that the members of class A area accessible to the members of class B.To process an order for labels, suppose you create the following class:
//--------------------------------------------------------------------------#ifndef LabelsH #define LabelsH using namespace std; //--------------------------------------------------------------------------class TLabels {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
public: TLabels(); TLabels(const TLabels& L); ~TLabels(); void ProcessALabel(); void setPrice(const Double p) { Price = p; } Double getPrice() const { return Price; } void ShowReceipt(); private: Double Price; }; //--------------------------------------------------------------------------#endif

And suppose you implement it as follows:


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

using namespace std;

#include "Labels.h" //---------------------------------------------------------------------------

TLabels::TLabels() : Price(0.00) { } //--------------------------------------------------------------------------TLabels::TLabels(const TLabels& L) : Price(L.Price) { } //--------------------------------------------------------------------------TLabels::~TLabels() { } //--------------------------------------------------------------------------void TLabels::ProcessALabel() { // Get the dimensions of the label // Get the label's characteristics } //--------------------------------------------------------------------------void TLabels::ShowReceipt()

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ cout << "Label Order - Receipt"; cout << "\n\tDimensions: "; cout << "\n\tArea: "; cout << "\n\tModel No.: "; cout << "\n\tModel Name: "; cout << "\n\tColor: "; cout << "\n\tAdhesive: "; cout << "\n\tPrice: " << setiosflags(ios::fixed) << setprecision(2) << Price; } //---------------------------------------------------------------------------

To effectively process an order, the new class needs access to the dimensions and the characteristics of the label, which reside in two different classes. Therefore, we will give it unlimited access to the appropriate classes. To make one class a friend of another, in the body of the class that is granting the friendship, type friend class ClassName; The keywords friend and class are required. The ClassName is the name of the class that needs friendship. Here is an example:
//--------------------------------------------------------------------------#ifndef LabelDimensionsH #define LabelDimensionsH using namespace std; //--------------------------------------------------------------------------class TDimensions { friend class TLabels; public: TDimensions(Double L = 0.00, Double W = 0.00); ~TDimensions(); void setDimensions(const Double L, const Double H); Double getLength() const { return Length; } Double getHeight() const { return Height; } Double Area() const; private: Double Length; Double Height; }; //--------------------------------------------------------------------------#endif

A class can be made a friend of as many classes as necessary, as illustrated in the following other example:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//--------------------------------------------------------------------------#ifndef LabelTypeH #define LabelTypeH //--------------------------------------------------------------------------#include <iostream> using namespace std; #include "LabelDimensions.h" //--------------------------------------------------------------------------enum TPrintCategory { pcInkjet = 1, pcLaser, pcMultiPurpose, pcUnspecified }; enum TAdhesive { adNone, adRemovable, adNonRemovable }; //--------------------------------------------------------------------------class TLabelType { friend class TLabels; public: ... string getPrintType() const; TAdhesive getAdhesive() const; private: unsigned int ModelNumber; string Name; string Color; int PrintType; TAdhesive Adhesive; }; //--------------------------------------------------------------------------#endif

Notice that, since a class used to process an order will also specify the dimensions, we do not need a TLabelDimensions member variable anymore. Now that the TLabels class has direct access to the other classes, we restructure it as follows:
//--------------------------------------------------------------------------#ifndef LabelsH #define LabelsH

#include "LabelType.h" #include "LabelDimensions.h" //--------------------------------------------------------------------------class TLabels { public: TLabels(); TLabels(const TLabels& L); ~TLabels();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
void GetLabelDimensions(TDimensions& Dim); void GetLabelCharacteristics(TLabelType& Label); void setPrice(const Double p) { Price = p; } Double getPrice() const { return Price; } void ShowReceipt(const TDimensions& Dim, const TLabelType& Label); private: Double Price; }; //--------------------------------------------------------------------------#endif

To implement these functions, keep in mind that we have access to the private members of the other classes. This means that we can initialize their member or request their values without declaring variables to hold these values. Here is their implementations:
//--------------------------------------------------------------------------#include <iomanip> using namespace std;

#include "Labels.h" //---------------------------------------------------------------------------

TLabels::TLabels() : Price(0.00) { } //--------------------------------------------------------------------------TLabels::TLabels(const TLabels& L) : Price(L.Price) { } //--------------------------------------------------------------------------TLabels::~TLabels() { } //--------------------------------------------------------------------------void TLabels::GetLabelDimensions(TDimensions& Rect) { cout << "Enter dimensions of the label\n"; cout << "Length: "; cin >> Rect.Length; cout << "Height: "; cin >> Rect.Height;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Double A = Rect.Area();

if( A <= 1.00 ) Price = 10.95; else if( A <= 2.625 ) Price = 12.95; else if( A <= 4.15 ) Price = 14.95; else if( A <= 10.00 ) Price = 18.95; else Price = 26.95; } //--------------------------------------------------------------------------void TLabels::GetLabelCharacteristics(TLabelType& Label) { char LabelName[32], LabelColor[32]; int AdhesiveType; int PrtType;

cout << "Enter the characteristics of the label\n"; cout << "Model Number: "; cin >> Label.ModelNumber;

cout << "Type or Name: "; gets(LabelName); cout << "Label Color: "; gets(LabelColor);

cout << "Adhesive Type" << "\n0 - No adhesive" << "\n1 - Removable Adhesive" << "\n2 - Non-Removable Adhesive" << "\nYour Choice: "; cin >> AdhesiveType;

if( AdhesiveType == 1 ) Label.Adhesive = adRemovable; else if( AdhesiveType == 2 ) Label.Adhesive = adNonRemovable; else

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Label.Adhesive = adNone;

cout << "Printing Type" << "\n1 - Inkjet" << "\n2 - Laser" << "\n3 - Multi-Purpose" << "\n4 - Unspecified" << "\nYour Choice: "; cin >> Label.PrintType;

Label.Name = LabelName; Label.Color = LabelColor; } //--------------------------------------------------------------------------void TLabels::ShowReceipt(const TDimensions& Rect, const TLabelType& Label) { TAdhesive Type = Label.getAdhesive();

cout << "================================="; cout << "\n - Pacific Office Store -"; cout << "\n================================="; cout << "\n Label Order - Receipt"; cout << "\n---------------------------------\n"; cout << "\n Dimensions: " << setiosflags(ios::fixed) << setprecision(2) << Rect.getLength() << " * " << Rect.getHeight(); cout << "\n Model No.: " << Label.getModelNumber(); cout << "\n Model Name: " << Label.getName(); cout << "\n Color: " << Label.getColor(); cout << "\n Adhesive: ";

if( Type == adRemovable ) cout << "Removable"; else if( Type == adNonRemovable ) cout << "Non-Removable"; else cout << "None"; cout << "\n Print Type: " << Label.getPrintType(); cout << "\n Price: " << Price; cout << "\n================================="; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//---------------------------------------------------------------------------

The composition of classes performed on our objects allows us now to process an order and display its receipt:
//--------------------------------------------------------------------------#include <iomanip> #include <conio.h> using namespace std; //--------------------------------------------------------------------------#include "Labels.h" //---------------------------------------------------------------------------

int main(int argc, char* argv[]) { TLabels Label; TDimensions Dim; TLabelType Type;

cout << "Welcome to Pacific Office Store\n"; cout << "This machine allows you to create labels\nto the desired " << "dimensions and custom characteristics\n"; Label.GetLabelDimensions(Dim); Label.GetLabelCharacteristics(Type);

system("cls"); Label.ShowReceipt(Dim, Type);

return 0; } //---------------------------------------------------------------------------

Combining Objects
1. To prepare a class that woud handle student and grade registration, add a new class. Save it as GradeReport 2. In the GradeReport.h file, create the foundation of the class as follows:
//--------------------------------------------------------------------------#ifndef GradeReportH #define GradeReportH //--------------------------------------------------------------------------class TGradeReport { public:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
private: }; //--------------------------------------------------------------------------#endif

3. Open the Students.h and declare a friend class as follows:


//--------------------------------------------------------------------------#ifndef StudentsH #define StudentsH #include <iostream> //--------------------------------------------------------------------------enum TStudentGender { sgUnspecified, sgMale, sgFemale }; //--------------------------------------------------------------------------class TStudents { friend class TGradeReport; public: ... private: ... }; //--------------------------------------------------------------------------#endif

4. Open the Grades.h file and declare friend class as follows:


//--------------------------------------------------------------------------#ifndef GradesH #define GradesH #include "Students.h" //--------------------------------------------------------------------------class TGrades { friend class TGradeReport; public: ...

private: ... }; //--------------------------------------------------------------------------#endi

5. To process the registration or the grades, instead of passing the class variables by reference as we have seen already, we will change a little bit by returning the class from the function that will need them (this allows us to test both techniques of returning an object). This is just another way to get the same information. To create the new class, change the content of the GradeReport.h file as

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
follows:
//--------------------------------------------------------------------------#ifndef GradeReportH #define GradeReportH #include <iostream> #include "Students.h" #include "Grades.h" //--------------------------------------------------------------------------struct TGradeInfo { int Level; string MajorCode; string MajorName; }; //--------------------------------------------------------------------------class TGradeReport { public: TGradeReport(); ~TGradeReport(); TStudents Registration(); TGrades GetGrades(); void ShowReport(const TStudents Student, const TGrades Grd); private: TGradeInfo LevelInfo; }; //--------------------------------------------------------------------------#endif

6. To implement the new class, change the GradeReport.cpp as follows:


//--------------------------------------------------------------------------#include <iomanip> using namespace std;

#include "GradeReport.h" //---------------------------------------------------------------------------

TGradeReport::TGradeReport() { } //--------------------------------------------------------------------------TGradeReport::~TGradeReport() {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} //--------------------------------------------------------------------------TStudents TGradeReport::Registration() { TStudents Student; int Gender;

cout << "Enter the student's information\n"; cout << "First Name: "; cin >> Student.FirstName; cout << "Last Name: "; cin >> Student.LastName; cout << "Day of Birth: "; cin >> Student.DayOfBirth; cout << "Month of Birth: "; cin >> Student.MonthOfBirth; cout << "Year of Birth: "; cin >> Student.YearOfBirth; out << "Gender: "; cout << "\n1 - Male" << "\n2 - Female" << "\n3 - Unspecified" << "\nYour Choice: "; cin >> Gender; Student.setGender(Gender);

cout << "Grade Level(6, 5, 4, etc): "; cin >> LevelInfo.Level; cout << "Major Code (A4, F1, G2, etc): "; cin >> LevelInfo.MajorCode; cout << "Major Name (Ex.: American Indian History, SocioMafia):\n"; getline(cin, LevelInfo.MajorName);

return Student; } //--------------------------------------------------------------------------TGrades TGradeReport::GetGrades() { TGrades Grade; double Language1, Language2, Hist, Geog, Chem, Soc, Math, CompSc, Mor, Sport;

cout << "\nEnter Student Grades\n"; cout << "English: "; cin >> Grade.English; cout << "2nd Language: "; cin >> Grade.SecondLng; cout << "History: "; cin >> Grade.History; cout << "Geography: "; cin >> Grade.Geography;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "Chemistry: "; cin >> Grade.Chemistry; cout << "Sociology: "; cin >> Grade.Sociology; cout << "Mathematics: "; cin >> Grade.Math; cout << "Comp Sciences: "; cin >> Grade.CompSc; cout << "Morale: "; cin >> Grade.Morale; cout << "Sports: "; cin >> Grade.Sports;

return Grade; } //--------------------------------------------------------------------------void TGradeReport::ShowReport(const TStudents Student, const TGrades Grade) { cout << "======================================="; cout << "\nStudent Personal Information"; cout << "\nFull Name: " << Student.getFirstName() << " " << Student.getLastName(); cout << "\nDate of Birth: " << Student.getDayOfBirth() << "/" << Student.getMonthOfBirth() << "/" << Student.getYearOfBirth(); cout << "\nGender: " << Student.getGender(); cout << "\nGrade Level: " << LevelInfo.Level; cout << "\nMajor: " << LevelInfo.MajorCode << ": " << LevelInfo.MajorName; cout << "\n---------------------------------------"; cout << setiosflags(ios::fixed) << setprecision(2); cout << "\n\tEnglish: " << Grade.getEnglish(); cout << "\n\t2nd Language: " << Grade.getSecondLng(); cout << "\n\tHistory: " << Grade.getHistory(); cout << "\n\tGeography: " << Grade.getGeography(); cout << "\n\tChemistry: " << Grade.getChemistry(); cout << "\n\tSociology: " << Grade.getSociology(); cout << "\n\tMathematics: " << Grade.getMath(); cout << "\n\tComp Sciences: " << Grade.getCompSc(); cout << "\n\tMorale: " << Grade.getMorale(); cout << "\n\tSports: " << Grade.getSports(); cout << "\n---------------------------------------"; cout << "\n\tTotal: " << Grade.CalcTotal() << "\tMean: " << Grade.CalcMean();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\n======================================="; } //---------------------------------------------------------------------------

7. The main() function can be used simply to call the functions that can take of any needed transaction. As an example, change the Main.cpp file as follows:
//--------------------------------------------------------------------------#include <iomanip> using namespace std; //--------------------------------------------------------------------------#include "Grades.h" #include "Students.h" #include "GradeReport.h"

//--------------------------------------------------------------------------int main(int argc, char* argv[]) { TGradeReport Report; TStudents Student; TGrades Grade;

Student = Report.Registration(); Grade = Report.GetGrades();

system("cls"); Report.ShowReport(Student, Grade);

return 0; } //---------------------------------------------------------------------------

8. Test the program: 9. Return to your programming environment

Inheritance
The ability to use already created objects is one of the strengths of C++. If you have a ready made object, you can construct a new one using the existing properties. Inheritance is the ability to create an object using, or based on, another. The new or inherited object is also said to derive, or be derived from, the other object. There are various ways you can inherit an object: using an operating system object, basing an object on an existing C++ one, or creating an object from a C++ Builder class. To start, you should define an object as complete as possible. This means that it should have functionality, valuable properties, and behaviors that other objects can use with little concerns as to how the object is built, but trusting that it can handle the desired behavior.

Creating the Parent Object


Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
We will create an object that others can inherit from. We will build a brick used in construction. A brick is known by its length, height, and width; but it also has a rectangular base. Therefore, lets build the base first.The header file of TRectangle creates an object with its dimensions as follows:
//--------------------------------------------------------------------------#ifndef RectangleH #define RectangleH //--------------------------------------------------------------------------class TRectangle { public: TRectangle(double L = 0.00, double H = 0.00); TRectangle(const TRectangle& r); ~TRectangle(); void setLength(const double L); void setHeight(const double H); void setDimensions(const double L, const double H); double getLength() const; double getHeight() const; double Perimeter() const; double Area() const; private: double Length; double Height; }; //--------------------------------------------------------------------------#endif

The source file defines the object with its constructors, provides access to its members and calculates the area of the base:
//---------------------------------------------------------------------------

using namespace std;

#include "Rectangle.h" //---------------------------------------------------------------------------

//--------------------------------------------------------------------------TRectangle::TRectangle(double L, double H) : Length(L), Height(H) { } //--------------------------------------------------------------------------TRectangle::TRectangle(const TRectangle& Rect) : Length(Rect.Length), Height(Rect.Height)

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ } //--------------------------------------------------------------------------TRectangle::~TRectangle() { } //--------------------------------------------------------------------------void TRectangle::setLength(const double L) { Length = L; } //--------------------------------------------------------------------------void TRectangle::setHeight(const double H) { Height = H; } //--------------------------------------------------------------------------void TRectangle::setDimensions(const double L, const double H) { setLength(L); setHeight(H); } //--------------------------------------------------------------------------double TRectangle::getLength() const { return Length; } //--------------------------------------------------------------------------double TRectangle::getHeight() const { return Height; } //--------------------------------------------------------------------------double TRectangle::Perimeter() const { return 2 * (Length + Height); } //--------------------------------------------------------------------------double TRectangle::Area() const { return Length * Height; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//---------------------------------------------------------------------------

To test the object, we will use the main() function. To make sure the object can respond, we test it with its default values. Then we supply its dimensions and display it. Finally, we make a copy of the object and test that copy.
//--------------------------------------------------------------------------#include <iomanip> using namespace std; //--------------------------------------------------------------------------#include "Rectangle.h"

//--------------------------------------------------------------------------void RectProperties(const TRectangle& R) { cout << "Characteristics of the rectangle"; cout << setiosflags(ios::fixed) << setprecision(2); cout << "\nLength: " << R.getLength(); cout << "\nHeight: " << R.getHeight(); cout << "\nPerimeter: " << R.Perimeter(); cout << "\nArea: " << R.Area(); } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TRectangle Rect1; double L = 12.125, H = 8.625; // Rectangle with default dimensions TRectangle Rect2(L, H); // Rectangle with supplied dimensions TRectangle Rect3; // Will be used to make/test a copy

cout << "Properties of the rectangle with default values"; RectProperties(Rect1);

cout << "\n\nRectangle with provided dimensions"; RectProperties(Rect2);

Rect3 = Rect2; cout << "\n\nA copy of an existing rectangle"; RectProperties(Rect3);

return 0; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//---------------------------------------------------------------------------

Creating a Parent Object


1. Start a new C++ Console Application. Save the project in a folder called People 2. Save the file as Main and the project as Basis 3. Add a new class and save it as Person 4. To create a base class, change the header file as follows:
//--------------------------------------------------------------------------#ifndef PersonH #define PersonH #include <iostream> //--------------------------------------------------------------------------class TPerson { public: TPerson(string fn = "", string ln = ""); TPerson(const TPerson& P); ~TPerson(); void setFirstName(const string f); string getFirstName() const; void setLastName(const string l); string getLastName() const; private: string FirstName; string LastName; }; //--------------------------------------------------------------------------#endif

5. Implement the source file as follows:


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

using namespace std;

#include "Person.h" //---------------------------------------------------------------------------

//--------------------------------------------------------------------------TPerson::TPerson(string fn, string ln) : FirstName(fn), LastName(ln) { } //---------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
TPerson::TPerson(const TPerson& P) : FirstName(P.FirstName), LastName(P.LastName) { } //--------------------------------------------------------------------------TPerson::~TPerson() { } //--------------------------------------------------------------------------void TPerson::setFirstName(const string f) { FirstName = f; } //--------------------------------------------------------------------------string TPerson::getFirstName() const { return FirstName; } //--------------------------------------------------------------------------void TPerson::setLastName(const string l) { LastName = l; } //--------------------------------------------------------------------------string TPerson::getLastName() const { return LastName; } //---------------------------------------------------------------------------

6. To find out whether the new class work, change the Main.cpp file as follows:
//--------------------------------------------------------------------------#include <iostream> using namespace std; //--------------------------------------------------------------------------#include "Person.h"

//--------------------------------------------------------------------------void ShowInfo(const TPerson& Pers) { cout << "\nFull Name: " << Pers.getFirstName() << " " << Pers.getLastName(); }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//--------------------------------------------------------------------------int main(int argc, char* argv[]) { TPerson P("John", "Landis");

cout << "Personal Information"; ShowInfo(P);

return 0; } //---------------------------------------------------------------------------

7. Test the application and return to your programming environment.

Inheriting an Object
Once you have a defined object, you can apply its behavior as the starting point of another object. The basic syntax on inheriting from an object is: structORclass NewObject : AccessLevel ParentObject; The word structORclass will be replaced by struct or class depending on the object type you are trying to create. The NewObject element represents the name of the object you are creating. The colon (:) is read is based on. It lets the compiler know that the new object gets its starting behavior and properties from another object. The word AccessLevel specifies whether the object will use the public or private (or protected) level of access. The most common inheritance, which is also the most we will study, is the public inheritance. If you are creating an object whose parent is a structure, you can usually omit this access level because a structure is public by default. Otherwise, you should specify the level of access. The ParentObject is the name of the object that the new object is based or is inheriting from. When inheriting from another object, the new object is considered a child. To get the properties of the parent object, you should declare an instance of the parent. This instance will provide access to the members of the original object. The new object will not have access to the private members of the parent.

As we now have a good working rectangle, we will use it as the base of our brick. The header file of TBox creates an object whose base is the TRectangle object.
//--------------------------------------------------------------------------#ifndef BoxH #define BoxH #include "Rectangle.h" //--------------------------------------------------------------------------class TBox : public TRectangle { public: TBox(double L = 0.00, double H = 0.00, double W = 0.00); TBox(const TBox& B);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
~TBox(); void setWidth(const double W); void setDimensions(const double Length, const double Height, const double Width); double getWidth() const { return Width; } double TotalArea() const; double Volume() const; private: double Width; }; //--------------------------------------------------------------------------#endif

The source file is used to define the object. It makes sure that the new object has access to the desired properties of the parent. This is done using the access methods of the parent object called from the new constructors:
//---------------------------------------------------------------------------

using namespace std;

#include "Box.h" //---------------------------------------------------------------------------

TBox::TBox(double L, double H, double W) : TRectangle(L, H), Width(W) { } //--------------------------------------------------------------------------TBox::~TBox() { //TODO: Add your source code here } //--------------------------------------------------------------------------void TBox::setWidth(const double W) { if( Width < 0.00 ) Width = 0.00; else Width = W; } //--------------------------------------------------------------------------void TBox::setDimensions(const double L, const double H, const double W) {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
setLength(L); setHeight(H); setWidth(W); } //--------------------------------------------------------------------------double TBox::TotalArea() const { double Face1 = getLength() + getHeight(); double Face2 = getHeight() + getWidth(); double Face3 = getLength() + getWidth();

return (2 * Face1) + (2 * Face2) + (2 * Face3); } //--------------------------------------------------------------------------double TBox::Volume() const { return getLength() * getHeight() * getWidth(); } //---------------------------------------------------------------------------

To test the new object, we will use the main() function. First, we will declare a Box without arguments, which means we will display it with the default dimensions. Second, we will test the Box with supplied dimensions:
//--------------------------------------------------------------------------#include <iomanip> using namespace std; //--------------------------------------------------------------------------#include "Rectangle.h" #include "Box.h"

//--------------------------------------------------------------------------void RectProperties(const TRectangle& R) { ... } //--------------------------------------------------------------------------void BoxProperties(const TBox& B) { cout << "Characteristics of the box"; cout << setiosflags(ios::fixed) << setprecision(2); cout << "\nLength: " << B.getLength(); cout << "\nHeight: " << B.getHeight(); cout << "\nWidth: " << B.getWidth();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\nArea: " << B.TotalArea(); cout << "\nVolume: " << B.Volume(); } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TBox RedBox; cout << "A Box with default values"; BoxProperties(RedBox); cout << "\n\n";

TBox GrayBox(6.55, 5.25, 5.75); cout << "Properties of the Box with dimensions"; BoxProperties(GrayBox);

return 0; } //---------------------------------------------------------------------------

The protected Access Level


The TBox object we created based on the TRectangle class is not very impressive. For one thing, the TBox is using the same features as any other object in order to access the member variables of its parents. This does not provide any privileged access for a child of an object. C++ provides a solution to this problem: a special relationship between an inherited object and its parent. In the past, we learned that the public level allows the client of a class to access any member of the public section of the class. We also learned to hide other members by declaring them in the private section, which prevents the clients of class from accessing such variables. You can create a special access level that allows only the children of a class to have access to certain members of the parent class. This new access level is called protected and created with that keyword. The box we created and inherited from the TRectangle object needs to be able to initialize a parallelepiped rectangle with the length, height, and the self-added width. To allow this relationaship, you would change the TRectangle class as follows:
//--------------------------------------------------------------------------#ifndef RectangleH #define RectangleH //--------------------------------------------------------------------------class TRectangle { public: TRectangle(double L = 0.00, double H = 0.00); TRectangle(const TRectangle& r); ~TRectangle(); void setLength(const double L); void setHeight(const double H);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
void setDimensions(const double L, const double H); double getLength() const; double getHeight() const; double Perimeter() const; double Area() const; protected: double Length; double Height; }; //--------------------------------------------------------------------------#endif

Since only the access level of the member variables has changed, nothing needs to be done in the implementation of the class. On the other hands, by making the member variables of the TRectangle class protected, the TBox class and its public members now have access to their parents protected members. This allows us the change the source file of the TBox object as follows:
//---------------------------------------------------------------------------

using namespace std;

#include "Box.h" //---------------------------------------------------------------------------

TBox::TBox(double L, double H, double W) : TRectangle(L, H), Width(W) { } //--------------------------------------------------------------------------TBox::TBox(const TBox& B) : Width(B.Width) { Length = B.Length; Height = B.Height; } //--------------------------------------------------------------------------TBox::~TBox() { //TODO: Add your source code here } //--------------------------------------------------------------------------void TBox::setWidth(const double W) { if( Width < 0.00 ) Width = 0.00;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
else Width = W; } //--------------------------------------------------------------------------void TBox::setDimensions(const double L, const double H, const double W) { setLength(L); setHeight(H); setWidth(W); } //--------------------------------------------------------------------------double TBox::TotalArea() const { double Face1 = Length + Height; double Face2 = Height + Width; double Face3 = Length + Width;

return (2 * Face1) + (2 * Face2) + (2 * Face3); } //--------------------------------------------------------------------------double TBox::Volume() const { return Length * Height * Width; } //---------------------------------------------------------------------------

As you can see, the derived class now has access to the member variables of the parent class and can use them to safely perform the needed calculations.

Inheriting Objects
1. To create a protected access level on the parent object, make the following change in the Person.h file:
//--------------------------------------------------------------------------#ifndef PersonH #define PersonH #include <iostream> //--------------------------------------------------------------------------class TPerson { public: TPerson(string fn = "", string ln = ""); TPerson(const TPerson& P); ~TPerson();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
void setFirstName(const string f); string getFirstName() const; void setLastName(const string l); string getLastName() const; protected: string FirstName; string LastName; private: }; //--------------------------------------------------------------------------#endif

2. Add a new class and save it as Student 3. To derive an object from another, change the header file as follows:
#define StudentH #include "Person.h" //--------------------------------------------------------------------------class TStudent : public TPerson { public: TStudent(); TStudent(string fn, string ln, int DOB, int MOB, int YOB, int g); TStudent(string fn, string ln); TStudent(int DOB, int MOB, int YOB); TStudent(const TStudent& S); ~TStudent(); void setDayOfBirth(const int d) { DayOfBirth = d; } int getDayOfBirth() const { return DayOfBirth; } void setMonthOfBirth(const int m) { MonthOfBirth = m; } int getMonthOfBirth() const { return MonthOfBirth; } void setYearOfBirth(const int y) { YearOfBirth = y; } int getYearOfBirth() const { return YearOfBirth; } void setGender(const int g) { Gender = g; } string getGender() const; private: int DayOfBirth; int MonthOfBirth; int YearOfBirth; int Gender; }; //--------------------------------------------------------------------------#endif

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
4. To initialize the class using the constructor(s) of its base class, implement the new object as follows:
//--------------------------------------------------------------------------using namespace std;

#include "Student.h" //---------------------------------------------------------------------------

TStudent::TStudent() : TPerson("John", "Doe"), DayOfBirth(1), MonthOfBirth(1), YearOfBirth(1990), Gender(0) { } //--------------------------------------------------------------------------TStudent::TStudent(string fn, string ln, int DOB, int MOB, int YOB, int g) : TPerson(fn, ln), DayOfBirth(DOB), MonthOfBirth(MOB), YearOfBirth(YOB), Gender(g) { } //--------------------------------------------------------------------------TStudent::TStudent(string fn, string ln) : TPerson(fn, ln), DayOfBirth(1), MonthOfBirth(1), YearOfBirth(1990) { } //--------------------------------------------------------------------------TStudent::TStudent(int DOB, int MOB, int YOB) : TPerson("", ""), DayOfBirth(DOB), MonthOfBirth(MOB), YearOfBirth(YOB) { } //--------------------------------------------------------------------------TStudent::TStudent(const TStudent& Stud) : TPerson(Stud.FirstName, Stud.LastName), DayOfBirth(Stud.DayOfBirth), MonthOfBirth(Stud.MonthOfBirth), YearOfBirth(Stud.YearOfBirth), Gender(Stud.Gender) { } //--------------------------------------------------------------------------TStudent::~TStudent()

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
{ } //--------------------------------------------------------------------------string TStudent::getGender() const { if( Gender == 1 ) return "Male"; else if( Gender == 2 ) return "Female"; else return "Unspecified"; } //--------------------------------------------------------------------------

5. To prepare the program for a test, change the Main.cpp file as follows:
//--------------------------------------------------------------------------#include <iostream> using namespace std; //--------------------------------------------------------------------------#include "Student.h"

//--------------------------------------------------------------------------void ShowInfo(const TStudent& S) { cout << "\nFull Name: " << S.getFirstName() << " " << S.getLastName(); cout << "\nDate of Birth: " << S.getDayOfBirth() << "/" << S.getMonthOfBirth() << "/" << S.getYearOfBirth(); cout << "\nGender: " << S.getGender(); } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TStudent P;

P.setFirstName("Hermine"); P.setLastName("Akono"); P.setDayOfBirth(12); P.setMonthOfBirth(5); P.setYearOfBirth(1988); P.setGender(2);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "Personal Information"; ShowInfo(P);

return 0; } //---------------------------------------------------------------------------

6. Implement the Student.cpp class as follows:


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

using namespace std;

#include "Student.h" //---------------------------------------------------------------------------

TStudent::TStudent() : TPerson("John", "Doe"), DayOfBirth(1), MonthOfBirth(1), YearOfBirth(1990), Gender(0) { } //--------------------------------------------------------------------------TStudent::TStudent(string fn, string ln, int DOB, int MOB, int YOB, int g) : TPerson(fn, ln), DayOfBirth(DOB), MonthOfBirth(MOB), YearOfBirth(YOB), Gender(g) { } //--------------------------------------------------------------------------TStudent::TStudent(string fn, string ln) : TPerson(fn, ln), DayOfBirth(1), MonthOfBirth(1), YearOfBirth(1990) { } //--------------------------------------------------------------------------TStudent::TStudent(int DOB, int MOB, int YOB) : TPerson("", ""), DayOfBirth(DOB), MonthOfBirth(MOB), YearOfBirth(YOB) { }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//--------------------------------------------------------------------------TStudent::TStudent(const TStudent& Stud) : TPerson(Stud.FirstName, Stud.LastName), DayOfBirth(Stud.DayOfBirth), MonthOfBirth(Stud.MonthOfBirth), YearOfBirth(Stud.YearOfBirth), Gender(Stud.Gender) { } //--------------------------------------------------------------------------TStudent::~TStudent() { } //--------------------------------------------------------------------------string TStudent::getGender() const { if( Gender == 1 ) return "Male"; else if( Gender == 2 ) return "Female"; else return "Unspecified"; } //--------------------------------------------------------------------------

7. To prepare a test, change the Main.cpp file as follows:


//--------------------------------------------------------------------------#include <iostream> using namespace std; //--------------------------------------------------------------------------#include "Student.h"

//--------------------------------------------------------------------------void ShowInfo(const TStudent& S) { cout << "\nFull Name: " << S.getFirstName() << " " << S.getLastName(); cout << "\nDate of Birth: " << S.getDayOfBirth() << "/" << S.getMonthOfBirth() << "/" << S.getYearOfBirth(); cout << "\nGender: " << S.getGender(); } //--------------------------------------------------------------------------int main(int argc, char* argv[]) {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
TStudent P;

P.setFirstName("Hermine"); P.setLastName("Akono"); P.setDayOfBirth(12); P.setMonthOfBirth(5); P.setYearOfBirth(1988); P.setGender(2);

cout << "Personal Information"; ShowInfo(P);

return 0; } //---------------------------------------------------------------------------

8. Test the program and return to your programming environment

Multiple Inheritance
The most common inheritance consists of an object deriving its foundation from another object. This is referred to as single inheritance. C++ allows an object to be based on more than one object. This is called refered to as multiple inheritance.

When an object is based on many other objects, it benefits from the variables of those objects. It has direct access to the public and protected members of each parent object. To apply a multiple inheritance, specify each class on the right side of the : operator.

Performing Multiple Inheritance


1. Add a new class to your project and save it as Address 2. In the Address.h file, create a TAddress class as follows:
//--------------------------------------------------------------------------#ifndef AddressH #define AddressH #include <iostream> //--------------------------------------------------------------------------class TAddress { public:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
TAddress(string a = "123 Main Street #A", string c = "City Ville", string s = "MD", string z = "20900"); TAddress(const TAddress& d); ~TAddress(); void setAddress(const string a) { Address = a; } string getAddress() const { return Address; } void setCity(const string c) { City = c; } string getCity() const { return City; } void setState(const string s) { State = s; } string getState() const { return State; } void setZIPCode(const string z) { ZIPCode = z; } string getZIPCode() const { return ZIPCode; } protected: string Address; string City; string State; string ZIPCode; }; //--------------------------------------------------------------------------#endif

3. Implement the TAddreass class as follows:


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

using namespace std;

#include "Address.h" //---------------------------------------------------------------------------

TAddress::TAddress(string a, string c, string s, string z) : Address(a), City(c), State(s), ZIPCode(z) { } //--------------------------------------------------------------------------TAddress::TAddress(const TAddress& d) : Address(d.Address), City(d.City), State(d.State), ZIPCode(d.ZIPCode) { } //--------------------------------------------------------------------------TAddress::~TAddress() {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} //---------------------------------------------------------------------------

4. Add a new class and save it as Staff 5. To perform a multiple inheritance, in the Staff.h file, create a TStaff class as follows:
//--------------------------------------------------------------------------#ifndef StaffH #define StaffH #include <iostream> #include "Person.h" #include "Address.h" //--------------------------------------------------------------------------class TStaff : public TPerson, public TAddress { public: TStaff(); TStaff(string fn, string ln, string a, string c, string s, string z, double L, char e, int m); TStaff(const TStaff& S); ~TStaff(); void setSalary(const double s) { Salary = s; } double getSalary() const; void setEmplStatus(const char e) { EmploymentStatus = e; } string getEmploymentStatus() const; void setMaritalStatus(const int m) { MaritalStatus = m; } string getMaritalStatus() const; protected: double Salary; char EmploymentStatus; int MaritalStatus; }; //--------------------------------------------------------------------------#endif

6. Implement the TStaff class as follows:


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

using namespace std;

#include "Staff.h" //---------------------------------------------------------------------------

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

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
TStaff::TStaff() { } //--------------------------------------------------------------------------TStaff::TStaff(string fn, string ln, string a, string c, string s, string z, double L, char e, int m) : TPerson(fn, ln), TAddress(a, c, s, z), Salary(L), EmploymentStatus(e), MaritalStatus(m) { } //--------------------------------------------------------------------------TStaff::TStaff(const TStaff& S) : Salary(S.Salary), EmploymentStatus(S.EmploymentStatus), MaritalStatus(S.MaritalStatus) { } //--------------------------------------------------------------------------TStaff::~TStaff() { } //--------------------------------------------------------------------------double TStaff::getSalary() const { if( Salary < 12.42 ) return 12.42; else return 12.42; } //--------------------------------------------------------------------------string TStaff::getEmploymentStatus() const { string EStatus;

switch(EmploymentStatus) { case 'f': case 'F': EStatus = "Full-Time"; break;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
case 'p': case 'P': EStatus = "Parti-Time"; break; case 'c': case 'C': EStatus = "Contractor"; break; case 's': case 'S': EStatus = "Seasonal"; break; default: EStatus = "Unknown"; }

return EStatus; } //--------------------------------------------------------------------------string TStaff::getMaritalStatus() const { string MStatus; switch(MaritalStatus) { case 1: MStatus = "Single"; break; case 2: MStatus = "Married"; break; case 3: MStatus = "Widow"; break; case 4: MStatus = "Divorc"; break; default: MStatus = "Not Specified"; }

return MStatus; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//---------------------------------------------------------------------------

7. Change the Main.cpp file as follows:


//--------------------------------------------------------------------------#include <iostream> using namespace std; //--------------------------------------------------------------------------#include "Staff.h"

//--------------------------------------------------------------------------void ShowInfo(const TStaff& S) { cout << "\nFull Name: " << S.getFirstName() << " " << S.getLastName(); cout << "\nAddress: " << S.getAddress() << "\n " << S.getCity() << " " << S.getState() << " " << S.getZIPCode(); cout << "\nEmployment: " << S.getEmploymentStatus(); cout << "\nSalary: $" << S.getSalary(); cout << "\nMarital St: " << S.getMaritalStatus(); } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TStaff Empl;

Empl.setFirstName("Mark"); Empl.setLastName("Azzuri"); Empl.setAddress("12432 Lockwood Drive #D12"); Empl.setCity("Hyattsville"); Empl.setState("MD"); Empl.setZIPCode("20740"); Empl.setSalary(18.05); Empl.setEmplStatus('F'); Empl.setMaritalStatus(1);

cout << "Personal Information"; ShowInfo(Empl);

return 0; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//---------------------------------------------------------------------------

8. Test the program and return to your programming environment 9. To allow the user to process hiring, change the Main.cpp file as follows:
//--------------------------------------------------------------------------#include <iostream> using namespace std; //--------------------------------------------------------------------------#include "Staff.h"

//--------------------------------------------------------------------------void NewEmployee(TStaff& Employee) { string FirstName, LastName, Address, City, State, ZIPCode; double Salary; char EmplStatus; int MStatus;

cout << "First Name: "; cin >> FirstName; cout << "Last Name: "; cin >> LastName; cout << "Address: "; getline(cin, Address); cout << "City: "; getline(cin, City); cout << "State: "; getline(cin, State); cout << "ZIP Code: "; cin >> ZIPCode; cout << "Hourly Salary: $"; cin >> Salary; cout << "Employment Status" << "\nf - Full-Time" << "\np - Part-Time" << "\nc - Contractor" << "\ns - Seasonal" << "\nYour Choice: "; cin >> EmplStatus; cout << "Marital Status" << "\n1 - Single" << "\n2 - Married" << "\n3 - Widow" << "\n4 - Divorc" << "\nStatus: "; cin >> MStatus;

Employee.setFirstName(FirstName); Employee.setLastName(LastName); Employee.setAddress(Address); Employee.setCity(City); Employee.setState(State);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
Employee.setZIPCode(ZIPCode); Employee.setSalary(Salary); Employee.setEmplStatus(EmplStatus); Employee.setMaritalStatus(MStatus); } //--------------------------------------------------------------------------void ShowInfo(const TStaff& S) { cout << "\nFull Name: " << S.getFirstName() << " " << S.getLastName(); cout << "\nAddress: " << S.getAddress() << "\n " << S.getCity() << " " << S.getState() << " " << S.getZIPCode(); cout << "\nEmployment: " << S.getEmploymentStatus(); cout << "\nSalary: $" << S.getSalary(); cout << "\nMarital St: " << S.getMaritalStatus(); } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TStaff Empl;

cout << "Enter information about the new hire\n"; NewEmployee(Empl);

system("cls"); cout << "Personal Information"; ShowInfo(Empl);

return 0; } //---------------------------------------------------------------------------

10. Test the program and return to your programming environment.

Previous

Copyright 2000-2005 FunctionX, Inc.

Next

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

Polymorphism and Abstraction


Polymorphism
In an inheritance scenario, a parent class is configured to provide its child with the basic foundation the child needs. Although a child can implement a new behavior not available on the parent object, sometimes a child object will need a customized implementation of a behavior that has already been configured with its parent. That is what happens for example when inheriting a sphere from a circle class. Both have a characteristic called Area but the area is calculated differently on each shape.

Inheritance Review
1. Create a new C++ Console Application in a folder called Polymorphism 2. Save the first file as Main and the project as Polymorphism 3. Add a new class and save it as Circle 4. Create a TCircle class in the Circle.h file as follows:
//--------------------------------------------------------------------------#ifndef CircleH #define CircleH //--------------------------------------------------------------------------class TCircle { public: TCircle(double r = 0.00); ~TCircle(); void setRadius(const double r) { Radius = r; } double getRadius() const { return Radius; } double Area() const; void ShowCharacteristics() const; protected: double Radius; }; //--------------------------------------------------------------------------#endif

5. Implement the TCircle class in the Circle.cpp file as follows:


//--------------------------------------------------------------------------#include <iomanip> using namespace std; #include "Circle.h" //--------------------------------------------------------------------------const double PI = 3.14159; //---------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
TCircle::TCircle(double r) : Radius(r) { } //--------------------------------------------------------------------------TCircle::~TCircle() { } //--------------------------------------------------------------------------double TCircle::Area() const { return Radius * Radius * PI; } //--------------------------------------------------------------------------void TCircle::ShowCharacteristics() const { cout << "Circle Characteristics"; cout << setiosflags(ios::fixed) << setprecision(2); cout << "\nRadius: " << getRadius(); cout << "\nArea: " << Area(); } //---------------------------------------------------------------------------

6. Add a new class and save it as Sphere 7. To create a new TSphere class based on the TCircle class, lay its foundation in the Sphere.h file as follows:
//--------------------------------------------------------------------------#ifndef SphereH #define SphereH #include "Circle.h" //--------------------------------------------------------------------------class TSphere : public TCircle { public: TSphere(double x); ~TSphere() {} double Area() const; double Volume() const; void ShowCharacteristics() const; private: }; //---------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#endif

8. Implement the new class as follows:


//--------------------------------------------------------------------------#include <iomanip> using namespace std; #include "Sphere.h" //--------------------------------------------------------------------------const double PI = 3.14159; //--------------------------------------------------------------------------TSphere::TSphere(double n) : TCircle(n) { } //--------------------------------------------------------------------------double TSphere::Area() const { return 4 * PI * Radius * Radius; } //--------------------------------------------------------------------------double TSphere::Volume() const { return 4 * PI * Radius * Radius * Radius / 3; } //--------------------------------------------------------------------------void TSphere::ShowCharacteristics() const { cout << "Circle Characteristics"; cout << setiosflags(ios::fixed) << setprecision(2); cout << "\nRadius: " << getRadius(); cout << "\nArea: " << Area(); cout << "\nVolume: " << Volume(); } //---------------------------------------------------------------------------

9. To inherit another class, add a new class and save it as Cylinder 10. Create the TCylinder class based on TCircle in the Cylinder.h file as follows:
//--------------------------------------------------------------------------#ifndef CylinderH #define CylinderH #include "Circle.h" //---------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
class TCylinder : public TCircle { public: TCylinder(double r, double h); ~TCylinder() {} void setHeight(const double h) { Height = h; } double getHeight() const { return Height; } double BaseArea() const; double LateralArea() const; double Area() const; double Volume() const; void ShowCharacteristics() const; private: double Height; }; //--------------------------------------------------------------------------#endif

11. Implement the new class in its source file as follows:


//--------------------------------------------------------------------------#include <iomanip> using namespace std;

#include "Cylinder.h" //--------------------------------------------------------------------------const double PI = 3.14159; //--------------------------------------------------------------------------TCylinder::TCylinder(double x, double y) : TCircle(x), Height(y) { } //--------------------------------------------------------------------------double TCylinder::BaseArea() const { return TCircle::Area(); } //--------------------------------------------------------------------------double TCylinder::LateralArea() const { double Circ = Radius * 2 * PI; return Circ * Height;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} //--------------------------------------------------------------------------double TCylinder::Area() const { double Base = TCircle::Area(); double Lateral = LateralArea(); return (2 * Base) + Lateral; } //--------------------------------------------------------------------------double TCylinder::Volume() const { double Base = TCircle::Area(); return Base * Height; } //--------------------------------------------------------------------------void TCylinder::ShowCharacteristics() const { cout << "Circle Characteristics"; cout << setiosflags(ios::fixed) << setprecision(2); cout << "\nRadius: " << getRadius(); cout << "\nHeight: " << getHeight(); cout << "\nBase Area: " << BaseArea(); cout << "\nLateral Area: " << LateralArea(); cout << "\nArea: " << Area(); cout << "\nVolume: " << Volume(); } //---------------------------------------------------------------------------

12. To prepare a test, change the main() function in the Main.cpp file as follows:
//--------------------------------------------------------------------------#include <iostream> using namespace std; //--------------------------------------------------------------------------#include "Circle.h" #include "Sphere.h" #include "Cylinder.h"

int main(int argc, char* argv[]) { TCircle e(12.55);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
TSphere s(22.25); TCylinder c(34.05, 28.35);

e.ShowCharacteristics(); cout << "\n\n"; s.ShowCharacteristics(); cout << "\n\n"; c.ShowCharacteristics();

return 0; } //---------------------------------------------------------------------------

13. To test the program, press F9. 14. We can also dynamically declare the objects and access them as pointers. To see an example, change the main() function as follows:
//--------------------------------------------------------------------------#include <iostream> using namespace std; //--------------------------------------------------------------------------#include "Circle.h" #include "Sphere.h" #include "Cylinder.h"

int main(int argc, char* argv[]) { TCircle *e = new TCircle(12.55); TSphere *s = new TSphere(16.15); TCylinder *c = new TCylinder(14.25, 10.85);

e->ShowCharacteristics(); cout << "\n\n"; s->ShowCharacteristics(); cout << "\n\n"; c->ShowCharacteristics();

return 0;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} //---------------------------------------------------------------------------

15. Test the program. When studying inheritance, we learned that there is a special bond between an inherited class and its parent. Not only does the child object have access to the public members of a class but also the child, based on this relationship, has direct access to the members of the protected section (the child is a protg) of the parent. The program above shows us that, in order to access a class members, we can just declare an instance of the class and use either the member access operator . or the pointer access operator ->. If there is such a good relationship between a class and its children, is it possible to access a member of a child object using an instance of the parent? We will declare only an instance of the parent class, TCircle, and try to access its child using such a variable. 16. Change the main() function as follows:
//--------------------------------------------------------------------------#include <iostream> using namespace std; //--------------------------------------------------------------------------#include "Circle.h" #include "Sphere.h" #include "Cylinder.h"

int main(int argc, char* argv[]) { TSphere *s = new TSphere(15.32); TCylinder *c = new TCylinder(36.08, 20.24);

TCircle *e = s; e->ShowCharacteristics(); cout << "\n\n"; e = c; e->ShowCharacteristics();

return 0; } //---------------------------------------------------------------------------

17. Test the program. Notice that, although the pointer variable *e has been initialized with variables *s and *c, only the characteristics of the circle are displayed.

Virtual Functions
A virtual function is a function that makes sure that, in an inheritance scenario, the right function is called regardless of the expression that calls the function. The last three classes we have used have two functions called Area() and ShowCharacteristics() each. Let us consider the member

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
function ShowCharacteristics() that is present in all three classes. If we need an instance of the parent class to call the right member function, in this case Area, we must declare ShowCharacteristics () in the parent class as virtual.

Declaring a Virtual Function


1. Click the Circle.h tab and change the declaration of the Area() function as follows:
//--------------------------------------------------------------------------#ifndef CircleH #define CircleH //--------------------------------------------------------------------------class TCircle { public: TCircle(double r = 0.00); ~TCircle(); void setRadius(const double r) { Radius = r; } double getRadius() const { return Radius; } double Area() const; virtual void ShowCharacteristics() const; protected: double Radius; }; //--------------------------------------------------------------------------#endif

2. Test the program again. Notice that, this time, even though an instance of the TCircle class made the call, the characteristics of the assigned variables display. 3. Return to your programming environment. 4. Since the Area() function is present on the parent as well as the inherited classes, make it virtual in the base class as follows:
//--------------------------------------------------------------------------#ifndef CircleH #define CircleH //--------------------------------------------------------------------------class TCircle { public: TCircle(double r = 0.00); ~TCircle(); void setRadius(const double r) { Radius = r; } double getRadius() const { return Radius; } virtual double Area() const; virtual void ShowCharacteristics() const; protected:

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
double Radius; }; //--------------------------------------------------------------------------#endif

5. Test the program. Notice that the right functions, as far as their having been assigned to the base class instance goes, are called. Even though you can use polymorphism to help the compiler identify which function is being called, if you want to access the same function of the base class, you can qualify it with the scope resolution operator ::. As you can see, a function with the same name can be declared in both a base and a derived classes. This allows a derived class to define its custom definition of the function. Because the derived class re-writes the same function, the derived class is said to override the function. A function can be overridden only if it is virtual. A function can be virtual only if carries the same name, the same return type, and the same type(s) of argument(s) if any.

Virtual Destructors
Consider a case where you have created a class that is derived from another class. When you dynamically call the inherited class using an instance of the base class (as done in the last example), during the closing of the program, the destructor of the child class is called first, followed by the destructor of the base class. If you dynamically declare an instance of the base class and then invoke the children of the class, you need to make sure that each destructor and the right destructor of the classes that was used is called to destroy the class; this is safe measure to avoid memory leak. This aspect of C++ programming is taken care of by declaring the destructor of the base class as virtual. Whenever the destructor of the parent class is declared virtual, the destructor of an inherited class is also virtual. This ensures that, the program closes, all of the destructors of the base class and its children that were used are called, providing a safe claim of the memory that was used. To declare a destructor as virtual, type the virtual keyword on its left, in the body of the class. Here is an example:
//--------------------------------------------------------------------------#ifndef CircleH #define CircleH //--------------------------------------------------------------------------class TCircle { public: TCircle(double r = 0.00); virtual ~TCircle(); void setRadius(const double r) { Radius = r; } double getRadius() const { return Radius; } double Area() const; virtual void ShowCharacteristics() const; protected: double Radius; }; //--------------------------------------------------------------------------#endif

Abstract Classes
Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
An abstract class is a class whose role is only meant to lay a foundation for those classes that would need a common behavior or similar characteristics. Therefore, an abstract class is used only as a base class for inheritance. A class is made abstract by declaring at least one its member functions as a pure virtual function. Only a virtual function can be made pure. The syntax of declaring a pure function is:
virtual ReturnType FunctionName() = 0;

The virtual keyword is required to make sure that a (any) child of this class can implement this function as it deems fit. The ReturnType is the data type that the function will return. The FunctionName is an appropriate name for the function. The = 0 is required. It lets the compiler know that this function is a pure virtual function. When a function has been declared as pure virtual, you do not need to implement it. Instead, each inherited class of an abstract class must provide its own implementation of the pure member function. When creating an abstract class, you can declare all of its member functions as pure. Here is an example:
//--------------------------------------------------------------------------struct TTent { virtual int WhatIsTheCapacity() = 0; virtual double TentArea() = 0; virtual double TentVolume() = 0; virtual char* TextureColor() = 0; }; //---------------------------------------------------------------------------

In this case, the class does not need a source file or any implementation because none of its member functions will be implemented. An abstract base class can also have a mix of pure and non-pure functions. Here is an example:
//--------------------------------------------------------------------------struct TTent { virtual int WhatIsTheCapacity() = 0; virtual double TentArea() = 0; virtual double TentVolume() = 0; virtual char* TextureColor() = 0; // Pure virtual function virtual char* TextureName(); // Virtual function int ShapeType(); // Regular member function }; //---------------------------------------------------------------------------

In this case, as we have done with the other classes so far, you must implement the non-pure functions in the base and let the inherited classes implement their own version(s) of the pure virtual function(s).

Implementing Abstract Classes


1. Create a new C++ Console Application and save it in a folder called Polygons 2. Save the class as Main and the project as RegPolygons 3. Add a new class and save it as Polygon

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
4. On the Status Bar, click the Polygon.h tab and create a regular class as follows:
//--------------------------------------------------------------------------#ifndef PolygonH #define PolygonH //--------------------------------------------------------------------------namespace Shapes { class TPolygon { public: TPolygon(int s = 0, char *n = "", double r = 0.00); virtual ~TPolygon(); void setNbrOfSides(const int n); int getNbrOfSides() const { return NbrOfSides; } void setPolyName(const char *n); char * getPolyName() const { return PolyName; } void setRadius(const double r); double getRadius() const { return Radius; } double CentralAngle() const; double InteriorAngle() const; protected: int NbrOfSides; char *PolyName; double Radius; }; } //--------------------------------------------------------------------------#endif

5. Click the Polygon.cpp tab and implement the member functions as follows:
//--------------------------------------------------------------------------#include <iostream> using namespace std; #include "Polygon.h" //---------------------------------------------------------------------------

//--------------------------------------------------------------------------namespace Shapes { TPolygon::TPolygon(int s, char *n, double r) {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
//TODO: Add your source code here NbrOfSides = s; Radius = r; setPolyName(n); } //--------------------------------------------------------------------------TPolygon::~TPolygon() { //TODO: Add your source code here delete [] PolyName; } //--------------------------------------------------------------------------void TPolygon::setNbrOfSides(const int n) { // Avoid a negative number of sides. It wouldn't make sense. // This program considers only regular polygons. // The minimum number of sides is 3, which corresponds to an // equilateral triangle if( n < 3 ) NbrOfSides = 0; else if( n < 4 ) NbrOfSides = 3; // Equilateral Triangle else if( n == 4 ) NbrOfSides = 4; // Square else if( n == 5 ) NbrOfSides = 5; // Pentagon else if( n == 6 ) NbrOfSides = 6; // Hexagon else if( n == 7 || n == 8 ) NbrOfSides = 8; // Octagon else if( n == 9 || n == 10 ) NbrOfSides = 10;// Decagon else //if( n == 11 || n == 12 ) NbrOfSides = 12;// Dodecagon } //--------------------------------------------------------------------------void TPolygon::setPolyName(const char * n) { //TODO: Add your source code here PolyName = new char[strlen(n) + 1]; strcpy(PolyName, n);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
} //--------------------------------------------------------------------------void TPolygon::setRadius(const double r) { //Avoid a negative radius. It wouldn't make sense if( r < 0 ) Radius = 0.00; else Radius = r; } //--------------------------------------------------------------------------double TPolygon::CentralAngle() const { return 360 / NbrOfSides; } //--------------------------------------------------------------------------double TPolygon::InteriorAngle() const { return (NbrOfSides - 2) * 180 / NbrOfSides; } //--------------------------------------------------------------------------} //---------------------------------------------------------------------------

6. Prepare the main() function for a test as follows:


//--------------------------------------------------------------------------#include <iostream> #include <iomanip> using namespace std; //--------------------------------------------------------------------------#include "Polygon.h"

int main(int argc, char* argv[]) { Shapes::TPolygon *Pol = new Shapes::TPolygon; Pol->setRadius(15.55); Pol->setNbrOfSides(25); Pol->setPolyName("Unknown");

cout << "Shape Characteristics"; cout << setiosflags(ios::fixed) << setprecision(2);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\nName: " << Pol->getPolyName(); cout << "\nSides: " << Pol->getNbrOfSides(); cout << "\nRadius: " << Pol->getRadius(); cout << "\nCentral Angle: " << Pol->CentralAngle() << "*"; cout << "\nInterior Angle: " << Pol->InteriorAngle();

return 0; } //---------------------------------------------------------------------------

7. Test the program. Return to your programming environment. 8. To add some pure virtual function and qualify the class as abstract, change the TPolygon class creation as follows:
//--------------------------------------------------------------------------#ifndef PolygonH #define PolygonH //--------------------------------------------------------------------------namespace Shapes { class TPolygon { public: TPolygon(int s = 0, char *n = "", double r = 0.00); virtual ~TPolygon(); void setNbrOfSides(const int n); int getNbrOfSides() const { return NbrOfSides; } void setPolyName(const char *n); char * getPolyName() const { return PolyName; } void setRadius(const double r); double getRadius() const { return Radius; } double CentralAngle() const; double InteriorAngle() const; virtual double Side() = 0; virtual double Apothem() = 0; virtual double Perimeter() = 0; double Area(); virtual void ShapeCharacteristics() = 0; protected: int NbrOfSides; char *PolyName;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
double Radius; }; } //--------------------------------------------------------------------------#endif

9. To implement the newly added Area() member function, add it to the Polygon.cpp file as follows:
//--------------------------------------------------------------------------#include <iostream> using namespace std; #include "Polygon.h" //---------------------------------------------------------------------------

//--------------------------------------------------------------------------namespace Shapes { TPolygon::TPolygon(int s, char *n, double r) { ... } //--------------------------------------------------------------------------... //--------------------------------------------------------------------------double TPolygon::Area() { double p = Perimeter(); double r = Apothem(); return p * r / 2; } //--------------------------------------------------------------------------} //---------------------------------------------------------------------------

10. To test the program, press F9. 11. Read the errors that you receive. As you can see, you are not allowed to declare an instance of an abstract class: 12. Return to your programming environment. 13. Add a new class and save it as Triangle 14. In the Triangle.h file, derive a new TTriangle class from the TPolygon class as follows:
//--------------------------------------------------------------------------#ifndef TriangleH #define TriangleH

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
#include "Polygon.h" //--------------------------------------------------------------------------class TTriangle : public Shapes::TPolygon { public: // We use two constructors so that the user can initialize // either by not specifying anything or by providing the radius TTriangle(); TTriangle(double r); ~TTriangle(); virtual double Side(); virtual double Apothem(); virtual double Perimeter(); double Height(); virtual void ShapeCharacteristics(); protected: private: }; //--------------------------------------------------------------------------#endif

15. Implement the class in the Triangle.cpp source file as follows:


//--------------------------------------------------------------------------#include <iostream> #include <iomanip> #include <math.h> using namespace std;

#include "Triangle.h" //---------------------------------------------------------------------------

//--------------------------------------------------------------------------TTriangle::TTriangle() { // If the constructor is empty, at least we know the number of sides // and the name of this polygon setNbrOfSides(3); setPolyName("Equilateral Triangle"); setRadius(getRadius()); } //---------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
TTriangle::TTriangle(double r) { setNbrOfSides(3); setPolyName("Equilateral Triangle"); setRadius(r); } //--------------------------------------------------------------------------TTriangle::~TTriangle() { } //--------------------------------------------------------------------------double TTriangle::Side() { return Radius * sqrt(3); } //--------------------------------------------------------------------------double TTriangle::Apothem() { return Radius / 2; } //--------------------------------------------------------------------------double TTriangle::Perimeter() { double S = Side(); return 3 * S; } //--------------------------------------------------------------------------double TTriangle::Height() { return Apothem() + Radius; } //--------------------------------------------------------------------------void TTriangle::ShapeCharacteristics() { cout << "Shape Characteristics"; cout << "\nName: " << getPolyName(); cout << "\nSides: " << getNbrOfSides(); cout << "\nRadius: " << getRadius(); cout << "\nCentral Angle: " << CentralAngle(); cout << "\nInterior Angle: " << InteriorAngle(); cout << setiosflags(ios::fixed) << setprecision(2);

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\nApothem: " << Apothem(); cout << "\nHeight: " << Height(); cout << "\nPerimeter: " << Perimeter(); cout << "\nArea: " << Area(); } //---------------------------------------------------------------------------

16. To prepare a test, change the Main.cpp file as follows:


//--------------------------------------------------------------------------#include <iostream> using namespace std; //--------------------------------------------------------------------------#include "Triangle.h"

int main(int argc, char* argv[]) { TTriangle *Tri = new TTriangle;

Tri->setRadius(15.55); Tri->ShapeCharacteristics();

return 0; } //---------------------------------------------------------------------------

17. Test the program and return to your programming environment. 18. Add a new class and save it as Square 19. In the Square.h file, create a regular polygon of a square based on the TPolygon class as follows:
//--------------------------------------------------------------------------#ifndef SquareH #define SquareH #include "Polygon.h" //--------------------------------------------------------------------------class TPolySquare : public Shapes::TPolygon { public: TPolySquare(); TPolySquare(double r); ~TPolySquare() {} virtual double Side();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
virtual double Apothem(); virtual double Perimeter(); virtual void ShapeCharacteristics(); protected: private: }; //--------------------------------------------------------------------------#endif

20. Implement the TPolySquare class as follows:


//--------------------------------------------------------------------------#include <iostream> #include <iomanip> #include <math.h> using namespace std; //---------------------------------------------------------------------------

#include "Square.h"

//--------------------------------------------------------------------------TPolySquare::TPolySquare() { // If the constructor is empty, at least we know the number of sides // and the name of this polygon setNbrOfSides(4); setPolyName("Square"); setRadius(getRadius()); } //--------------------------------------------------------------------------TPolySquare::TPolySquare(double r) { setNbrOfSides(4); setPolyName("Square"); setRadius(r); } //--------------------------------------------------------------------------double TPolySquare::Side() { return Radius * sqrt(2); } //---------------------------------------------------------------------------

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
double TPolySquare::Apothem() { return sqrt(2) * Radius / 2; } //--------------------------------------------------------------------------double TPolySquare::Perimeter() { double S = Side(); return 4 * S; } //--------------------------------------------------------------------------void TPolySquare::ShapeCharacteristics() { cout << "Shape Characteristics"; cout << "\nName: " << getPolyName(); cout << "\nSides: " << getNbrOfSides(); cout << "\nRadius: " << getRadius(); cout << setiosflags(ios::fixed) << setprecision(0); cout << "\nCentral Angle: " << CentralAngle(); cout << "\nInterior Angle: " << InteriorAngle(); cout << setiosflags(ios::fixed) << setprecision(2); cout << "\nApothem: " << Apothem(); cout << "\nPerimeter: " << Perimeter(); cout << "\nArea: " << Area(); } //---------------------------------------------------------------------------

21. Add a new class and save it as Hexagon 22. Create a THexagon object derived from the TPolygon class as follows:
//--------------------------------------------------------------------------#ifndef HexagonH #define HexagonH #include "Polygon.h" //--------------------------------------------------------------------------class THexagon : public Shapes::TPolygon { public: THexagon(); THexagon(double r); ~THexagon() {} virtual double Side();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
virtual double Apothem(); virtual double Perimeter(); virtual void ShapeCharacteristics(); protected: private: }; //--------------------------------------------------------------------------#endif

23. Implement the THexagon class as follows:


//--------------------------------------------------------------------------#include <iostream> #include <iomanip> #include <math.h> using namespace std; #include "Hexagon.h"

//--------------------------------------------------------------------------THexagon::THexagon() { // If the constructor is empty, at least we know the number of sides // and the name of this polygon setNbrOfSides(6); setPolyName("Hexagon"); setRadius(getRadius()); } //--------------------------------------------------------------------------THexagon::THexagon(double r) { setNbrOfSides(6); setPolyName("Hexagon"); setRadius(r); } //--------------------------------------------------------------------------double THexagon::Side() { return Radius; } //--------------------------------------------------------------------------double THexagon::Apothem() {

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
return sqrt(3) * Radius / 2; } //--------------------------------------------------------------------------double THexagon::Perimeter() { double S = Side(); return 6 * S; } //--------------------------------------------------------------------------void THexagon::ShapeCharacteristics() { cout << "Shape Characteristics"; cout << "\nName: " << getPolyName(); cout << "\nSides: " << getNbrOfSides(); cout << "\nRadius: " << getRadius(); cout << setiosflags(ios::fixed) << setprecision(0); cout << "\nCentral Angle: " << CentralAngle(); cout << "\nInterior Angle: " << InteriorAngle(); cout << setiosflags(ios::fixed) << setprecision(2); cout << "\nApothem: " << Apothem(); cout << "\nPerimeter: " << Perimeter(); cout << "\nArea: " << Area(); } //---------------------------------------------------------------------------

24. Before testing the program, change the Main.cpp file as follows:
//--------------------------------------------------------------------------#include <iostream> using namespace std; //--------------------------------------------------------------------------#include "Triangle.h" #include "Square.h" #include "Hexagon.h"

//--------------------------------------------------------------------------int main(int argc, char* argv[]) { TTriangle *Tri = new TTriangle; Tri->setRadius(15.55); Tri->ShapeCharacteristics();

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "\n\nNew Shape";

TPolySquare *Sq = new TPolySquare(22.36); Sq->ShapeCharacteristics();

cout << "\n\nNew Shape";

clrscr(); THexagon *Hx = new THexagon; Hx->setRadius(36.08); Hx->ShapeCharacteristics();

return 0; } //---------------------------------------------------------------------------

25. Test the program and return to your programming environment

Value Casting
Introduction
We have been introduced to declaring variables using specific data types. After declaring a value and initializing it, you may want the value to change type without redefining it. This is required in some cases where you already have a value, probably produced by one variable, while another variable declared with a different data type. This means that you would need to convert a value from one type into another type. For example, you may have declared a variable using a double data type but you need the value of that variable to be used as an int. Transferring a value from one type to another is referred to as casting. There are two broad types of casting available in C++: C's old school of casting and the C++ standards.

C How To Cast a Value


C, the parent of C++ supports value casting by specifying the type of value you want an existing one to have. To do this, you use the following formula:
(DataType)Expression

Based on this formula, in the parentheses, enter the type of data you want the existing or resulting value to have. The DataType factor can be any of the data types we saw above. The Expression factor can be a constant value. Here is an example:
#include <iostream> using namespace std;

int main() { cout << "Number: " << (int)3.14159 << "\n";

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

return 0; }

Notice that the value to convert is a floating-point number. If the conversion is successful, the new value would be conform to the type in parentheses. For example, the above code would produce:
Number: 3

Here is another version of the above program:


#include <iostream> using namespace std;

int main() { int number;

number = (int)3.14159; cout << "Number: " << number << "\n";

return 0; }

The Expression factor can also be the result of a calculation. In this case, you should include the whole expression is its own parentheses. The Expression factor of our formula can also be the name of a variable that holds a value. Here is an example:
#include <iostream> using namespace std;

int main() { double price = 258.85; int number;

cout << "Price? $" << price << "\n";

number = (int)price; cout << "Number: " << number << "\n";

return 0; }

This would produce:


Price? $258.85 Number: 258

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

C++ Casting
C++ provides its own support of value casting using variable keywords so you can specify the type of conversion you want. One of the keywords used is static_cast and the formula is:
static_cast<DataType>(Expression)

In this formula, the static_cast keyword, the <, the >, and the parentheses are required. The DataType factor should be an existing data type such as those we have reviewed in this lesson. The Expression factor can be a constant value. Here is an example that converts a floatingpoint number to an integer:
#include <iostream> using namespace std;

int main() { cout << "Number: " << static_cast<int>(3.14159) << "\n";

return 0; }

You can also assign the resulting value to a variable before using it:
#include <iostream> using namespace std;

int main() { int number = static_cast<int>(3.14159);

cout << "Number: " << number << "\n";

return 0; }

The value to convert can also be the result of a calculation. The value can also be originating from an existing variable whose value you want to convert to a new type. Here is an example:
#include <iostream> using namespace std;

int main() { double PI = 3.14159; int number;

number = static_cast<int>(PI);

cout << "PI = " << PI << endl;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "Number = " << number << "\n";

return 0; }

This would produce:


PI = 3.14159 Number = 3

Variable Scope
Introduction
In the previous lesson, to declare a variable, we proceeded inside of the main() function. Such a variable could be used only inside of the square brackets of main(). In some cases, you may want to declare a variable that can be accessed from one section of the code. The section of code in which a variable can be accessed is referred to as its scope.

Local Variables
If you declare a variable inside of a function such as main(), that function can be accessed only from that function. Consider the following example:
#include <iostream> using namespace std;

int main() { double number = 3.14159; cout << "Number = " << number << "\n";

return 0; }

Such a variable is referred to as local because it is declared in a function. In reality, a local scope is defined by a beginning opening curly bracket "{" and a closing curly bracket "}". Everything between these brackets belongs to a local scope. Once you have declared such a variable, you cannot declare another variable in the same scope and that bears the same name. Consider the following example:
#include <iostream> using namespace std;

int main() { double number = 3.14159; cout << "Number = " << number << "\n";

double number = 2.98;

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in
cout << "Number = " << number << "\n";

return 0; }

This would produce a "redefinition" error and the program would not compile, even if the second declaration uses a different data type. As one type of solution to this kind of problem, C++ allows you to create a "physical" scope. To do this, you can use curly brackets to delimit the scope of a particular variable. Here is an example:
#include <iostream> using namespace std;

int main() { { double number = 3.14159; cout << "Number = " << number << "\n"; }

double number = 2.98; cout << "Number = " << number << "\n";

return 0; }

This would produce:


Number = 3.14159 Number = 2.98

In the code, notice that we delimit only the first declaration. Indeed, you can delimit each scope if you want:
#include <iostream> using namespace std;

int main() { { double number = 3.14159; cout << "Number = " << number << "\n"; }

{ double number = 2.98; cout << "Number = " << number << "\n"; }

Content Downloaded from www.functionx.com

Created By www.ebooktutorials.blogspot.in

return 0; }

Previous

Copyright 2000-2005 FunctionX, Inc.

Content Downloaded from www.functionx.com

You might also like