Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
26 views

Functionx CPP Tutorials

Uploaded by

borade.vijay
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Functionx CPP Tutorials

Uploaded by

borade.vijay
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 878

C++ Tutorial - FunctionX

Keywords
bool
break
else
for
inline
static

References
Anonymous
Classes
Comments
FunctionX | FunctionX Press | C++ Builder | Visual C++ | C# | C# Builder | Visual C# | Win32 | SQL Server Inheritance
Introduction to C++
This is the C++ references of our References General
Introduction to Variables series of FunctionX tutorials. The site Examples
is organized as follows: The top right section The Simplest
Using Variables is used as a Program
reference and
C++ Operations Toolbar If-Else
provides various
examples of Condition
The top toolbar
Functions Arguments
displays some of the programs and
Control Statements other tutorials we functions. By Value
provide. Passing
Mathematics
Constructing Expressions Arguments
Lessons
Introduction to Arrays This is a new section A Simple
The left section featuring math
displays a list of Class
Pointers functions that can be An Object As
lessons that provide useful in a program.
Strings step-by-step Argument
explanations of the C+ Products A Class
Exception Handling + language topics. Member
An electronic book Variable
Introduction to Classes Keywords
(ebook) version with
The keywords section Constructor
updated material of
Constructing Classes Initializer
highlights the major this site is available
Combining Objects points to remember for purchase. Class Nesting
about a reserved word Array of
Composition and of the C++ language. Features Objects
Inheritance
Examples Guest Book. String Data
Polymorphism and
We created and are Entry
Abstraction Links
still adding examples. A Simple List
Operator Overloading These are usually Car Rental
small programs that File
Exceptions and Classes implement a particular Processing
or more than one
(FILE)
topic, showing how the
C++ language is used. Clearing the
screen
Multiple
Choice
Question

http://192.168.16.242/cts/tutorials/functionx/cpp/index.htm (1 of 2)11/20/2006 3:54:37 PM


C++ Tutorial - FunctionX

Mathematics
Absolute
An electronic book (ebook) of this site, better arranged with additional
material is available for purchase. Value
Calculation
Free Compilers: Square Root
Calculation
Greatest
Dev-C++: This is a free compiler from Bloodshed. The registration costs
Common
$20 which is used to help develop the compiler. I think that this is good
compiler for a beginner. If you register and pay $20, I will not receive a Divisor 1
cent from it. Greatest
Borland C++ 5.5: This compiler is provided by Borland. Common
Divisor 2
Installing the Borland C++ compiler Sum of a
Range of
Values
Minimum
Value
Maximum
Value

Contact Copyright © 2000-2003 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/index.htm (2 of 2)11/20/2006 3:54:37 PM


C++ Tutorial - Introduction

Introduction to C++
Introduction to Computers

A computer is a machine that receives instructions and renders 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 you gave, and what you expect the result to be.

As a machine, the computer cannot figure out what you want (or what any of us wants, for that
matter). The computer doesn't think (regardless of what you have heard before). Since the
computer doesn't think, it doesn't make mistakes.

Computer programming is the art of writing instructions (programs) that ask the computer to do something (compute) 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.

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (1 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

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 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 right-clicks 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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (2 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

C++ is a huge language. It provides a set of instructions that you give to the computer to perform an operation and give you
a result. The language is so huge that it uses various sets of instructions from different parts to do its work. Some of these
instructions come in forms of files that you simply "put" in your program. These instructions or files are in the form of
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 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 appropriate and recognizable names.

The first library we will be interested in is called the iostream library. It asks the computer to display stuff on the monitor you
are looking at.

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.

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:
http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (3 of 32)11/20/2006 3:54:47 PM
C++ Tutorial - Introduction

#include <iostream.h>

#include <stdio.h>

C++ Instructions

C++ works by giving (separate) instructions to the computer. These instructions can be treated as assignments. In this book,
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 a function, its 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 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.h>

main(){}

C++ Projects

C++ is the computer language we are going to learn 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.

Creating a Project

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (4 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

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++ Standard’s 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.

Creating and Executing a Dev-C++ 4 Application


1. Start Dev-C++ 4

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (5 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (6 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (7 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (8 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (9 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

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++ Builder (Console) Applications


1. To create a console application in Borland C++ Builder, from the main menu, click File -> New (or File -> new -> Other):

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (10 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (11 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction
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.h>

#include <conio.h>

#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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (12 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

1. I am using Red Hat Linux 7.2.


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
6. In the text editor, type the following:

#include <iostream.h>

int main()

cout << “C++ is fun!!!\n”;

return 0;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (13 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (14 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (15 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

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.

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (16 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (17 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction
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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (18 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

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

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++ Console Applications

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (19 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

1. Start Microsoft Visual C++.


2. On the main menu of Microsoft Visual C++ or Microsoft Visual Studio, click File -> New...
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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (20 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

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
15. From what we have learned so far, change the contents of the file as follows:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (21 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

#include <iostream.h>

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


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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (22 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (23 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (24 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

#include <iostream.h>

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.

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 book is written as a (general) reference towards the C++ language. To learn C++,
you of course need a C++ compiler, and we described above how to create a C++ project with some of the most
commonly used compilers or programming environments on the market. 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:

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (25 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

From now on, you will sometimes be asked to create a project. Follow the instructions of your compiler as we have
seen above.

Data Output: An Introduction

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

int main()

cout << "Computer Programming With C++";

return 0;

Comments

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (26 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

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

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (27 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

// The exo.cpp program

// Include the ostream library

#include <iostream.h>

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

Escape Sequences
C++ allows you to use escape sequences to make the compiler do something such as getting to the next line, performing a
TAB action, producing a quick sound (beep). When you write your program, you include the (right) escape sequence and C++
will take care of the rest.Various escape sequences behave differently, but they are always written with a backslash (\)
followed by a particular letter or character. Computers and compilers that follow the American Standard Code Information
Interchange (ASCII) (pronounce aski) recognize these escape sequences that have a corresponding ASCII value.

Here are the mostly used escape sequences:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (28 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

Escape
Sequence Name ASCII value Description
\a Bell (alert) 007 Makes a sound from the computer
\b Backspace 008 Takes the cursor back
\t Horizontal Tab 009 Takes the cursor to the next tab stop
\n New line 010 Takes the cursor to the beginning of the next line
\v Vertical Tab 011 Performs a vertical tab
\f Form feed 012
Carriage
\r 013 Causes a carriage return
return
\" Double Quote 034 Displays a quotation mark (")
\' Apostrophe 039 Displays an apostrophe (')
\? Question mark 063 Displays a question mark
\\ Backslash 092 Displays a backslash (\)
\0 Null 000 Displays a null character

Whenever you use any of these characters, if they are used inside of a sentence, then you can just include them; if they are
stand-alone, then include them in single or double quotes.

The most popular escape sequences you will be using are the new line (\n) and the horizontal tab (\t). The new line can also
be substituted with endl and the result will be the same.

Here is a simple example:

Here is another use of the escape sequences:

// Study of Escape Sequences

#include <iostream.h>

main()

// Skip the next line

cout << "\n";

// Create some space with double \n

cout << "Here are some companies and their products\n\n";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (29 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction
cout << "Company\t\tSoftware\n";

cout << "Microsoft\tVisual C++\n";

cout << "Borland\t\tC++ Builder\n";

cout << "Corel\t\tWord Perfect\n";

// Another list

cout << "\n\nHere are a few countries and their continents\n\n";

cout << "Continent\tCountry\tCapital\n";

cout << "America\t\tMexico\tMexico City\n";

cout << "Europe\t\tItaly\tRome\n";

cout << "Africa\t\tLybia\tTripoli\n";

cout << "Asia\t\tIndia\tNew Delhi\n";

// Another kind of New Line

cout << endl;

Here a run of the program:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (30 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction

Here are some companies and their products


Company Software
Microsoft Visual C++
Borland C++ Builder
Corel Word Perfect

Here are a few countries and their continents


Continent Country Capital
America Mexico Mexico City
Europe Italy Rome
Africa Libya Tripoli
Asia India New Delhi

Press any key to continue

Instead of typing a lot of cout operators on various lines, you can use one for a whole paragraph as long as you start each new cout line with << without a semi-colon
on the preceding line.
Here is another version of our program:

// Study of Escape Sequences

#include <iostream.h>

main()

// Skip the next line

cout << "\n";

// Create some space with double \n

cout << "Here are some companies and their products\n\n"

<< "Company\t\tSoftware\n"

<< "Microsoft\tVisual C++\n"

<< "Borland\t\tC++ Builder\n"

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (31 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction
<< "Corel\t\tWord Perfect\n";

// Another list

cout << "\n\nHere are a few countries and their continents\n\n"

<< "Continent\tCountry\tCapital\n"

<< "America\t\tMexico\tMexico City\n"

<< "Europe\t\tItaly\tRome\n"

<< "Africa\t\tLybia\tTripoli\n"

<< "Asia\t\tIndia\tNew Delhi\n";

// Another kind of New Line

cout << endl;

Introduction Copyright © 2000-2003 FunctionX Next

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson01.htm (32 of 32)11/20/2006 3:54:47 PM


C++ Tutorial - Introduction to Variables

Introduction to Variables

Identifiers and Variables


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 user’s 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 makes 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
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 syntax 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
● Should not be longer than 32 characters (although allowed)

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (1 of 25)11/20/2006 3:54:53 PM


C++ Tutorial - Introduction to Variables

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 and C++ Reserved Words


auto do goto signed union
break double if sizeof unsigned
case else int static void
char enum long struct volatile
const extern register switch while
continue float return typedef
default for short

Some of these words are used by KDevelop or could come in conflict with various libraries. Therefore, avoid using these
additional words:

C++ Reserved Words


asm dynamic_cast new static_cast typeid
bool explicit operator string typename
catch false private template union
class friend protected this using
cin inline public throw virtual
const_cast interrupt register true wchar_t
cout mutable reinterpret_cast try
delete namespace

Avoid starting the name of a variable with two underscores; sometimes (most of the time), the compiler would think that you
are trying to use one of the words reserved for the compiler.

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 book, a name will:

● Start in uppercase, whether it is a variable, a function, a structure, or a class. In some situations, a name will start with
an underscore, when needed. Examples are Country, Printer, _Number
● Start each element of its combined words 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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (2 of 25)11/20/2006 3:54:53 PM


C++ Tutorial - Introduction to Variables

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.

The cin Operator


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:

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 people the computer,
then to people who want to interact with the machine.

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.

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (3 of 25)11/20/2006 3:54:53 PM


C++ Tutorial - Introduction to Variables

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.

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*100 (= 0*1, which is 0); 1 is 1*100 (=1*1,
which is 1); 2 is 2*100 (=2*1, which is 2), and 9 is 9*100 (= 9*1, which is 9). Between 10 and 99, a number is represented
by left-digit * 101 + right-digit * 100. For example, 32 = 3*101 + 2*100 = 3*10 + 2*1 = 30 + 2 = 32. In the same way, 85
= 8*101 + 5*100 = 8*10 + 5*1 = 80 + 5 = 85. Using the same logic, you can get any number in the decimal system.
Examples are:

2751 = 2*103 + 7*102 + 5*101 + 1*100 = 2*1000 + 7*100 + 5*10 + 1 = 2000 + 700 + 50 + 1 = 2751

67048 = 6*104 + 7*103 + 0*102 + 4*101 + 8*100 = 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, we
will separate each thousand fraction with a comma. Our number would become 279,174,394,327. We will 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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (4 of 25)11/20/2006 3:54:53 PM


C++ Tutorial - Introduction to Variables

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.

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.

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (5 of 25)11/20/2006 3:54:53 PM


C++ Tutorial - Introduction to Variables

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.

A Nibble
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.

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 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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (6 of 25)11/20/2006 3:54:53 PM


C++ Tutorial - Introduction to Variables

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 24 (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 24 = 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:

Decimal Hexadecimal Binary


0 0 0000
1 1 0001
2 2 0010
3 3 0011
4 4 0100
5 5 0101
6 6 0110
7 7 0111
8 8 1000
9 9 1001
10 A 1010
11 B 1011
12 C 1100
13 D 1101
14 E 1110
15 F 1111

Table of Numeric Conversions

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (7 of 25)11/20/2006 3:54:53 PM


C++ Tutorial - Introduction to Variables

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 Hexadecimal Binary


Minimum 0 0x0 0000
Maximum 15 0xf 1111

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.

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (8 of 25)11/20/2006 3:54:53 PM


C++ Tutorial - Introduction to Variables

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 Hexadecimal Binary


Minimum 0 0x0 0000
Maximum 255 0xff 1111 1111

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

main()

cout << 'a';

Character Variables

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (9 of 25)11/20/2006 3:54:53 PM


C++ Tutorial - Introduction to 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, 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.h>

main()

char Gender = 'm';

cout << "Member Gender: " << Gender;

cout << endl;

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

main()

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (10 of 25)11/20/2006 3:54:53 PM


C++ Tutorial - Introduction to Variables

signed char Gender = 'm';

cout << "Member Gender: " << Gender;

cout << endl;

You can also declare a positive character as unsigned char. Here is an example:

#include <iostream.h>

main()

char Pick = 'r';

char NewLine = 'n';

unsigned char Lotus('x’);

cout << "Pick " << Pick;

cout << NewLine;

cout << "Lotus Sound" << Lotus;

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

main()

char Satisfaction, Answer;

signed char AgeCategory, Size;

cout << "From A to Z, enter a character as your level of satisfaction: ";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (11 of 25)11/20/2006 3:54:53 PM


C++ Tutorial - Introduction to Variables

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 << "\nSatisfaction: " << Satisfaction;

cout << "\nAge category: " << AgeCategory;

cout << "\nYour answer: " << Answer;

cout << "\nYour size: " << Size;

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.

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

main()

cout << "Sydney\nAustralia\n";

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (12 of 25)11/20/2006 3:54:53 PM


C++ Tutorial - Introduction to Variables

Escape ASCII
Name Description
Sequence value
\a Bell (alert) 007 Makes a sound from the computer
\b Backspace 008 Takes the cursor back
\t Horizontal Tab 009 Takes the cursor to the next tab stop
\n New line 010 Takes the cursor to the beginning of the next line
\v Vertical Tab 011 Performs a vertical tab
\f Form feed 012
\r Carriage return 013 Causes a carriage return
\" Double Quote 034 Displays a quotation mark (")
\' Apostrophe 039 Displays an apostrophe (')
\? Question mark 063 Displays a question mark
\\ Backslash 092 Displays a backslash (\)
\0 Null 000 Displays a null character

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

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (13 of 25)11/20/2006 3:54:53 PM


C++ Tutorial - Introduction to Variables

A Word

Representing a Word
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*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

= 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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (14 of 25)11/20/2006 3:54:53 PM


C++ Tutorial - Introduction to Variables

1111 1111 1111 1111


ffff
= 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.h>

main(int argc, char* argv[])

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

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.

#include <iostream.h>

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (15 of 25)11/20/2006 3:54:53 PM


C++ Tutorial - Introduction to Variables

main()

unsigned short Shirts;

unsigned short Pants;

unsigned short Dresses;

unsigned short Ties;

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 << "\nCurrent Order"

<< "\n\tShirts: " << Shirts

<< "\n\tPants: " << Pants

<< "\n\tDresses: " << Dresses

<< "\n\tTies: " << Ties

<< "\n\n";

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.

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (16 of 25)11/20/2006 3:54:53 PM


C++ Tutorial - Introduction to Variables

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:

2n-1 230 229 228 227 226 225 224


etc 1,073,741,824 536,870,912 268,435,456 134,217,728 67,108,864 33,554,432 16,777,216

223 222 221 220 219 218 217 216


8,388,608 4,194,304 2,097,152 1,048,576 524,288 262,144 131,072 65,536

215 214 213 212 211 210 29 28


32,768 16,384 8,192 4,096 2,048 1,024 512 256

27 26 25 24 23 22 21 20
128 64 32 16 8 4 2 1

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (17 of 25)11/20/2006 3:54:53 PM


C++ Tutorial - Introduction to Variables

1*231+1*230+1*229 + 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.h>

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (18 of 25)11/20/2006 3:54:53 PM


C++ Tutorial - Introduction to Variables

cout << "\nOn a cartesian system, point A is located at";

cout << "\n\tX = " << CoordX;

cout << "\n\tY = " << CoordY;

cout << "\n\tZ = " << CoordZ;

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:

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

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: ";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (19 of 25)11/20/2006 3:54:54 PM


C++ Tutorial - Introduction to Variables

cin >> YearOfBirth;

cout << "\nStudent's Date of Birth: "

<< DayOfBirth << "/" << MonthOfBirth << "/" << YearOfBirth;

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

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;

Enumerations

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (20 of 25)11/20/2006 3:54:54 PM


C++ Tutorial - Introduction to Variables

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

main()

enum PizzaSize {psSmall, psMedium, psLarge, psJumbo};

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (21 of 25)11/20/2006 3:54:54 PM


C++ Tutorial - Introduction to Variables

cout << "The small pizza has a value of " << psSmall << endl;

cout << "The medium pizza has a value of " << psMedium << endl;

cout << "The large pizza has a value of " << psLarge << endl;

cout << "The jumbo pizza has a value of " << psJumbo << endl;

To assign your own values to the list, you could change the enumeration as follows:

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

To get the starting as you want, change the enumeration as follows:

#include <iostream.h>

main()

enum PizzaSize {psSmall = 4, psMedium, psLarge, psJumbo};

cout << "The small pizza has a value of " << psSmall << endl;

cout << "The medium pizza has a value of " << psMedium << endl;

cout << "The large pizza has a value of " << psLarge << endl;

cout << "The jumbo pizza has a value of " << psJumbo << endl;

This would produce:

The small pizza has a value of 4


The medium pizza has a value of 5
The large pizza has a value of 6
The jumbo pizza has a value of 7
Press any key to continue...

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (22 of 25)11/20/2006 3:54:54 PM


C++ Tutorial - Introduction to Variables

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 small pizza has a value of 2


The medium pizza has a value of 3
The large pizza has a value of 14
The jumbo pizza has a value of -5
Press any key to continue...

Floating Numbers

Floating-Point Variables
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:

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

main()

float Side, Perimeter, Area;

cout << "Enter the side of the square: ";

cin >> Side; Perimeter = Side * 4;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (23 of 25)11/20/2006 3:54:54 PM


C++ Tutorial - Introduction to Variables

Area = Side * Side;

cout << "Characteristics of the square:";

cout << "\nSide: " << Side;

cout << "\nPerimeter: " << Perimeter;

cout << "\nArea: " << Area;

Double-Precision Numbers

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

Here is an example:

#include <iostream.h>

main()

float Side, Perimeter, Area;

cout << "Enter the side of the square: ";

cin >> Side; Perimeter = Side * 4;

Area = Side * Side;

cout << "Characteristics of the square:";

cout << "\nSide: " << Side;

cout << "\nPerimeter: " << Perimeter;

cout << "\nArea: " << Area;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (24 of 25)11/20/2006 3:54:54 PM


C++ Tutorial - Introduction to Variables

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

Here is an example that uses the long double data type:

#include <iostream.h>

main()

long double radius = 15.625, Radius = 18.125;

long double area, Area, TotalArea;

Area = Radius * Radius * 3.14159;

area = radius * radius * 3.14159;

TotalArea = Area - area;

cout << "Properties of the plate";

cout << "\nExternal Radius: " << Radius;

cout << "\nInternal Radius: " << radius;

cout << "\nArea: " << TotalArea;

Previous Copyright © 1998-2003 FunctionX Next

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson02.htm (25 of 25)11/20/2006 3:54:54 PM


C++ Tutorial - Using Variables

Using Variables

Techniques of Using Variables


References

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. The syntax of creating or declaring a reference is:

DataType &RefernceName = VariableName;

To declare a reference, type the variable’s 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 wants to know what variable you are referring to. Here is an example:

#include <iostream.h>

main()

int Number = 228;

int &Nbr = Number;

The ampersand operator between the data type and the reference can assume one of three positions as followed:

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.

Once a reference has been initialized, it holds the same value as the variable it is pointing to. You can then display the value
of the variable using either of both:

#include <iostream.h>

main()

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (1 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

int Number = 228;

int & Nbr = Number;

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

cout << "Its reference = " << Nbr << "\n\n";

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (2 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

In the way, you can use either a reference or the variable it is referring to, to request the variable’s value from the user. Here
is an example:

#include <iostream.h>

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

The typedef Type Definition


Some of the variables we have used so far and some others we will learn further with arrays, pointers, and objects can be
simplified and reduced to a new one-word identifier. C++ allows you to define a new variable using typedef. Indeed, typedef
is not a new or other data type. It provides a technique of redefining or renaming any of the known data types. The syntax of
using the typedef is:

typedef DataType NewName;

The typedef keyword is required to let the compiler know that you are creating a new identifier. The DataType is any of those
we have learned so far. It could be an int, an unsigned int, a char, a double, etc. An example of declaring a typedef is:

typedef int NumberOfStudents;

In this case, NumberOfStudents is just a new name for an int. It can be used as a new identifier exactly as if you were using
an int. Here is an example that redefines an int data type:

#include <iostream.h>

int main()

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (3 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

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 identifiers using typedef:

typedef unsigned int UINT;

typedef unsigned char UCHAR;

typedef unsigned long ULONG;

typedef long double LONGDOUBLE;

Constants

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (4 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

A constant is a value that does not change. There are various categories of constants you will be using in your programs. To
make their management easier, these constant values have been categorized and defined in particular libraries. Throughout
this book, you will be using them.

The algebraic numbers you have been using all the time 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 const 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 to display a constant value in C++. To simply display it using the cout << extractor,
you can use 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.

#include <iostream.h>

int main()

cout << 28;

cout << "\nStudent Age: " << 14;

cout << "\n\n";

return 0;

The safest technique of using a constant is to give it a name. This allows you to manage it from one standpoint. For example,
if you plan to use a number such as 3.14 that represents PI, you can simply use the constant 3.14. Imagine you want to use
3.14 in various sections of the program such as in different functions. 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.

There are two main techniques used to create constant values. The old way, which was used with the C language and 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 word 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. The
definition of the constant does not end with a semi-colon. Examples of declaring constants are:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (5 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

#define AGE 12 // AGE represents the constant integer 12

#define ANSWER ‘y’

#define MAXSTUDENTS 35

#define PI 3.14159 // PI represents 3.14159

Another technique of creating a constant is by using the const keyword. The syntax of using 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 what kind of variable it is. If you do not 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 learned. 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;

Another category of constants are those that are part of the C++ compiler. Those constants have names they can be
recognized with. For example, the minimum value of the short integer is 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.h>

#include <limits.h>

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (6 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

return 0;

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 INT_MAX LONG_MAX SCHAR_MAX SHRT_MAX


CHAR_MAX INT_MIN LONG_MIN SCHAR_MIN SHRT_MIN
CHAR_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


DBL_EPSILON FLT_EPSILON LDBL_EPSILON
DBL_MANT_DIG FLT _MANT_DIG LDBL_MANT_DIG
DBL_MAX FLT _MAX LDBL_MAX
DBL_MAX_10_EXP FLT_MAX_10_EXP LDBL_MAX_10_EXP
DBL_MAX_EXP FLT _MAX_EXP LDBL_MAX_EXP
DBL_MIN FLT _MIN LDBL_MIN
DBL_MIN_10_EXP FLT_MIN_10_EXP LDBL_MIN_10_EXP
DBL_MIN_EXP FLT _MIN_EXP LDBL_MIN_EXP
FLT_RADIX

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.

Introduction to 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 referred to.

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (7 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

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. A namespace contains 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 the cout extractor operator.
Here is an example:

#include <iostream.h>

namespace Mine

int a;

int main()

Mine::a = 140;

cout << "Value of a = " << Mine::a;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (8 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

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

namespace InterestAndDiscount

double Principal;

double Rate;

int Time;

int main()

InterestAndDiscount::Principal = 3250;

InterestAndDiscount::Rate = 0.1225; // =12.25%

InterestAndDiscount::Time = 2;

cout << "Loan Processing";

cout << "\nPrincipal: $" << InterestAndDiscount::Principal;

cout << "\nRate: " << InterestAndDiscount::Rate*100 << "%";

cout << "\nTime: " << InterestAndDiscount::Time << " years";

return 0;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (9 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

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

namespace InterestAndDiscount

double Principal;

double Rate;

int Time;

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::Time;

cout << "\nLoan Processing";

cout << "\nPrincipal: $" << InterestAndDiscount::Principal;

cout << "\nRate: " << InterestAndDiscount::Rate << "%";

cout << "\nTime: " << InterestAndDiscount::Time << " years";

return 0;

Here is an example of running the program:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (10 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

Interest and Discount

Principal: $12500

Rate (example 8.75): 7.25

Number of Years: 10

Interest Calculation

Principal: $12500.00

Rate: 7.25%

Time: 10 years

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

namespace InterestAndDiscount

double Principal;

double Rate;

int Time;

int main()

double Interest;

double MaturityValue;

cout << "Interest and Discount\n";

cout << "Principal: $";

cin >> InterestAndDiscount::Principal;

cout << "Rate (example 8.75): ";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (11 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

cin >> InterestAndDiscount::Rate;

cout << "Number of Years: ";

cin >> InterestAndDiscount::Time;

Interest = InterestAndDiscount::Principal *

(InterestAndDiscount::Rate/100) *

InterestAndDiscount::Time;

MaturityValue = InterestAndDiscount::Principal + Interest;

cout << "\nLoan Processing";

cout << "\nPrincipal: $" << InterestAndDiscount::Principal;

cout << "\nRate: " << InterestAndDiscount::Rate << "%";

cout << "\nTime: " << InterestAndDiscount::Time << " years";

cout << "\nInterest: $" << Interest;

cout << "\nMaturity Value: $" << MaturityValue << "\n\n";

return 0;

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

namespace InterestAndDiscount

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (12 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

double Principal;

double Rate;

int Time;

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

Interest = Principal * (Rate/100) * Time;

MaturityValue = Principal + Interest;

cout << "\nLoan Processing";

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

cout << "\nRate: " << Rate << "%";

cout << "\nTime: " << Time << " years";

cout << "\nInterest: $" << Interest;

cout << "\nMaturity Value: $" << MaturityValue << "\n\n";

return 0;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (13 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

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%

Time: 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.

Combining Namespaces
Using Various Namespaces
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 Time;

double Interest;

double Discount;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (14 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

double MaturityValue;

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

namespace InterestAndDiscount

double Principal;

double Rate;

int Time;

double Interest;

double Discount;

double MaturityValue;

namespace BuyAndSell

double OriginalPrice;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (15 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

double TaxRate;

double TaxAmount;

double Discount;

double DiscountAmount;

double NetPrice;

int main()

InterestAndDiscount::Principal = 12500; // $

InterestAndDiscount::Rate = 8.25; // %

InterestAndDiscount::Time = 5; // Years

InterestAndDiscount::Discount = InterestAndDiscount::Rate / 100;

InterestAndDiscount::Interest = InterestAndDiscount::Principal *

InterestAndDiscount::Discount *

InterestAndDiscount::Time;

InterestAndDiscount::MaturityValue = InterestAndDiscount::Principal +

InterestAndDiscount::Interest;

cout << "Interest Calculation";

cout << "\nPrincipal: $" << InterestAndDiscount::Principal

<< "\nRate: " << InterestAndDiscount::Rate << "%"

<< "\nDiscount: " << InterestAndDiscount::Discount

<< "\nTime: " << InterestAndDiscount::Time << " years"

<< "\nInterest: $" << InterestAndDiscount::Interest

<< "\nMaturity Value: $" << InterestAndDiscount::MaturityValue;

BuyAndSell::OriginalPrice = 250; // $

BuyAndSell::TaxRate = 16.00; // %

BuyAndSell::Discount = 20.00; // %

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (16 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

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:

#include <iostream.h>

namespace InterestAndDiscount

double Principal;

double Rate;

int Time;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (17 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

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

Time = 5; // Years

Discount = Rate / 100;

Interest = Principal * Discount * Time;

MaturityValue = Principal + Interest;

cout << "Interest Calculation";

cout << "\nPrincipal: $" << Principal

<< "\nRate: " << Rate << "%"

<< "\nDiscount: " << Discount

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (18 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

<< "\nTime: " << Time << " 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";

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

namespace InterestAndDiscount

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (19 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

. . .

namespace BuyAndSell

. . .

int main()

using namespace InterestAndDiscount;

. . .

cout << "Interest Calculation";

cout << "\nPrincipal: $" << Principal

<< "\nRate: " << Rate << "%"

<< "\nDiscount: " << Discount

<< "\nTime: " << Time << " years"

<< "\nInterest: $" << Interest

<< "\nMaturity Value: $" << MaturityValue;

using namespace BuyAndSell;

. . .

return 0;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (20 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

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 can 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.h>

namespace InterestAndDiscount

. . .

namespace BuyAndSell

. . .

int main()

using namespace InterestAndDiscount;

Principal = 12500; // $

Rate = 8.25; // %

Time = 5; // Years

InterestAndDiscount::Discount = Rate / 100;

Interest = Principal * InterestAndDiscount::Discount * Time;

MaturityValue = Principal + Interest;

cout << "Interest Calculation";

cout << "\nPrincipal: $" << Principal

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (21 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

<< "\nRate: " << Rate << "%"

<< "\nDiscount: " << InterestAndDiscount::Discount

<< "\nTime: " << Time << " 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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (22 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

double OriginalPrice;

double TaxRate;

double TaxAmount;

double Discount;

double DiscountAmount;

double NetPrice;

long ItemNumber;

bool QualifyForDiscount;

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

namespace BuyAndSell

double OriginalPrice;

double TaxRate;

double TaxAmount;

double Discount;

double DiscountAmount;

double NetPrice;

namespace ItemID

long ItemNumber;

bool QualifyForDiscount;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (23 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

int main()

BuyAndSell::OriginalPrice = 780.50;

BuyAndSell::TaxRate = 7.55;

BuyAndSell::Discount = 25; // %

BuyAndSell::ItemID::ItemNumber = 641238;

BuyAndSell::ItemID::QualifyForDiscount = true;

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 << "\nDiscount Category: " << BuyAndSell::ItemID::QualifyForDiscount;

cout << "\nOriginal Price: $" << BuyAndSell::OriginalPrice;

cout << "\nDiscount: $" << BuyAndSell::DiscountAmount;

cout << "\nTax Rate: " << BuyAndSell::TaxRate;

cout << "\nTax Amount $" << BuyAndSell::TaxAmount;

cout << "\nNet Price: $" << BuyAndSell::NetPrice << "\n\n";

return 0;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (24 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

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 you
want. Here is an example:

#include <iostream.h>

namespace BuyAndSell

double OriginalPrice;

double TaxRate;

double TaxAmount;

double Discount;

double DiscountAmount;

double NetPrice;

namespace ItemID

long ItemNumber;

bool QualifyForDiscount;

namespace DateSold

int Month;

int Day;

int Year;

int main()

. . .

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (25 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

BuyAndSell::ItemID::DateSold::Month = 10;

BuyAndSell::ItemID::DateSold::Day = 18;

BuyAndSell::ItemID::DateSold::Year = 2002;

. . .

return 0;

You can also use the using namespace routine by calling each namespace using its complete name:

#include <iostream.h>

namespace BuyAndSell

double OriginalPrice;

double TaxRate;

double TaxAmount;

double Discount;

double DiscountAmount;

double NetPrice;

namespace ItemID

long ItemNumber;

bool QualifyForDiscount;

namespace DateSold

int Month;

int Day;

int Year;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (26 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

int main()

using namespace BuyAndSell;

using namespace BuyAndSell::ItemID;

using namespace BuyAndSell::ItemID::DateSold;

OriginalPrice = 780.50;

TaxRate = 7.55;

Discount = 25; // %

ItemNumber = 641238;

QualifyForDiscount = true;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (27 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

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 iomanip list ostream streambuf


bitset ios locale queue string
complex iosfwd map set typeinfo
deque iostream memory sstream utility
exception istream new stack valarray
fstream iterator numeric stdexcept vector
functional limits

The following additional libraries can be used to include C header files into a C++ program:

cassert cios646 csetjmp cstdio ctime


cctype climits csignal cstdlib cwchar
cerrno clocale cstdarg cstring cwctype
cfloat cmath cstddef

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;

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.

Introduction to Strings

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (28 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

Arrays 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 double-quotes. 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;

main()

char University[] = "University of the District of Columbia";

char Faculty[]("Computer sciences");

cout << "Welcome to the Student Orientation Program.\n";

cout << "For your studies, we have selected:\n";

cout << "Institution: " << University << "\n";

cout << "Faculty: " << Faculty << "\n";

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (29 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

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;

To request a group of words using an array, use one of the following functions:

cin.getline( VariableName, Dimension);


cin.getline(VariableName, Dimension, Delimeter);

To use the array variables, change the content of the file as follows:

#include <iostream>

using namespace std;

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: ";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (30 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

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 << "\nCPAP Invoice # 1202";

cout << "\nCustomer Name: " << FirstName << " " << LastName;

cout << "\nAddress: " << Address;

cout << "\nJob Performed: " << JobPerformed;

cout << "\n\n";

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (31 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

main()

string FirstName, LastName;

cout << "Enter first name: ";

cin >> FirstName;

cout << "Enter last name: ";

cin >> LastName;

cout << "\n\nFull Name: " << FirstName << " " << LastName << "\n\n";

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;

main()

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (32 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

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

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;

main()

string FirstName, LastName;

cout << "Welcome to College Park Auto-Parts\n";

cout << "Enter the following information about the customer's.\n";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (33 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

cout << "First Name: ";

cin >> FirstName;

cout << "Last Name: ";

cin >> LastName;

cout << "\n\nCPAP Invoice # 1202";

cout << "\nCustomer Name: " << FirstName << " " << LastName << "\n\n";

When requesting a string made of various words, such as an address, you can use the getline() function as follows:

#include <iostream>

#include <string>

using namespace std;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (34 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Using Variables

getline(cin, JobPerformed);

cout << "\n\nCPAP Invoice # 1202";

cout << "\nCustomer Name: " << FirstName << " " << LastName;

cout << "\nAddress: " << Address;

cout << "\nJob Performed: " << JobPerformed << "\n\n";

Previous Copyright © 1998-2003 FunctionX Next

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson03.htm (35 of 35)11/20/2006 3:55:00 PM


C++ Tutorial - Operations and Expressions

Operations and Expressions


Unary Operators

Introduction
An operation is an action performed on one or more variables either to modify the value held by one or both of the variables
or to produce a new value by combining variables. Therefore, an operation is performed using at least one symbol and one
value. The symbol used in an operation is called an operator. A variable or a value involved in an operation is called an
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.

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 -5 -4 -3 -2 -1 1 2 3 4 5 6 +∞
0
-∞ -6 -5 -4 -3 -2 -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;

main()

int Number = +802;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (1 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

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.

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;

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 &

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (2 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

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;

main()

int Number = 46;

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

This would produce:

&Number = 0012FED4

Unary Operators: The Reference Operator &


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 variable’s 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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (3 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

#include <iostream>

using namespace std;

main()

int Number = 228;

int &Nbr = Number;

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.

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;

main()

int Number = 228;

int & Nbr = Number;

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

cout << "Its reference = " << Nbr << "\n\n";

return 0;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (4 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

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;

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 variable’s value from the
user. Here is an example:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (5 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

#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";

return 0;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (6 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

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;

main()

double Period = 155.50;

int SizeOf = sizeof Period;

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

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;

main()

char iChar;

unsigned char uChar;

signed char sChar;

int iInt;

short int sInt;

unsigned int uInt;

unsigned short int uShortInt;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (7 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

long int LInt;

unsigned long int uLongInt;

float iFloat;

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

This would produce:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (8 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

The sizeof operator used on a variable

Identifier Memory Size

in Bytes

----------------------------------

char 1

unsigned char 1

signed char 1

int 4

short int 2

unsigned int 4

unsigned short int 2

long int 4

unsigned long int 4

float 4

double 8

long double 8

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

#include <iostream>

using namespace std;

main()

char iChar;

unsigned char uChar;

signed char sChar;

int iInt;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (9 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

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

Algebraic Operators

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (10 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

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

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>

using namespace std;

main()

// Get the sum of two values

cout << "244 + 835 = " << 244 + 835;

cout << "\n\n";

Here is the result:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (11 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

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;

main()

int a = 244;

int b = 835;

// Get the sum of a and b

cout << a << " + " << b << " = " << a + b;

cout << "\n\n";

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;

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (12 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

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

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;

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

The following program shows the non-associativity of the subtraction operation:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (13 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

// Non-associativity of the subtraction operation

#include <iostream>

using namespace std;

main()

// Addition associativity

cout << "128 + 42 + 5 = " << 128 + 42 + 5;

cout << "\n5 + 42 + 128 = " << 5 + 42 + 128;

cout << "\n";

// Subtraction non-associativity

cout << "\n128 - 42 - 5 = " << 128 - 42 - 5;

cout << "\n5 - 42 - 128 = " << 5 - 42 - 128;

cout << "\n\n";

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.

The Multiplication

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (14 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

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;

main()

float a, b;

// Multiple of a and b.

cout << "\nType two values: ";

cin >> a >> b;

cout << a << " * " << b << " = " << a * b;

cout << "\n\n";

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (15 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

// Program used to get half of a number.

#include <iostream>

using namespace std;

main()

float a;

// Get a number from the user.

cout << "\nType a number: ";

cin >> a;

cout << " Half of " << a << " is " << a / 2 << "\n\n";

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;

main()

int Players = 26;

int YourPlayers;

// When the game starts, how many players will wait?.

cout << "\nOut of " << Players << " players, "

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (16 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

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

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 unpredictible
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 addion 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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (17 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

// Using parentheses

#include <iostream>

using namespace std;

main()

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

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

This would produce:

154 - 12) + 8 = 150

154 - (12 + 8) = 134

As you can see, using the parentheses controls how the whole operation would proceeds 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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (18 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

#include <iostream>

using namespace std;

main()

int Value = 12;

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

Value = Value + 1;

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

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;

main()

int Value = 12;

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

Value++;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (19 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

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;

main()

int Value = 12;

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

Value++;

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

Value++;

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

Value++;

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

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (20 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

#include <iostream>
using namespace std;

main()
{
int Value = 12;

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


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

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;

main()
{
int Value = 12;

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


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

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

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


Value = Value - 1;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (21 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

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


}

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;

main()
{
int Value = 8;

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


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

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;

main()
{
int Value = 8;

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


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

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

main()
{
int Value = 8;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (22 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

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;

main()
{
double Value = 12.75;
double NewValue;

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


NewValue = Value + 2.42;
cout << "Value = " << NewValue << endl;
}

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;

main()
{
double Value = 12.75;

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


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

This would produce:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (23 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

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;

main()
{
double Value = 12.75;

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


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

This would produce:

Value = 12.75
Value = 8.33

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (24 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

Bit ~Bit
1 0
0 1

Consider a number with a byte value such as 248. In Appendix C, we define how to convert numbers from one system to
another (this could be a good time to review or study Appendix C). 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 1 1 1 1 0 0 0
~Value 0 0 0 0 0 1 1 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 Bit2 Bit1 & Bit2


0 0 0
1 0 0
0 1 0
1 1 1

Imagine you have two byte values represented as 187 and 242. Based on Appendix C, 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). Let’s compare these two values bit by bit, using the bitwise AND operator:

Binary Decimal
N1 1 0 1 1 1 0 1 1 187
N2 1 1 1 1 0 0 1 0 242
N1 & N2 1 0 1 1 0 0 1 0 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;
}

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (25 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

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 Bit2 Bit1 | Bit2


0 0 0
1 0 1
0 1 1
1 1 1

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

Binary Decimal
N1 1 0 1 1 1 0 1 1 187
N2 1 1 1 1 0 0 1 0 242
N1 | N2 1 1 1 1 1 0 1 1 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;
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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (26 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

Bit1 Bit2 Bit1 ^ Bit2


0 0 0
1 0 1
0 1 1
1 1 0

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

Binary Decimal
N1 1 0 1 1 1 0 1 1 187
N2 1 1 1 1 0 0 1 0 242
N1 ^ N2 0 1 0 0 1 0 0 1 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 <<

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (27 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

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” Value’s bits to the left by the number of ConstantInteger. The number of
ConstantInteger bits on the left side of Value 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 1 0 1 0 1 0
42 Shifted to the left by 2 bits << 2
0 0 1 0 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.

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (28 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

Variable Casting: An Introduction

A compiler has the duty of rendering good results, but sometimes it cannot; it might figure out what is going on in your
program. This means sometimes you have to be explicit. When performing operations on variables of different types, you
need to tell the compiler what form of result you are expecting. For example, you can ask the compiler to convert a variable
or result from one type to another, otherwise the compiler might just "make up its own mind". And most of the time you will
not like it.

Value casting consists of converting the type of data that the value is holding into another type. There are two main
techniques available in C++: the old but still working C fashion and the safer C++ alternative.

C Casting
The C language casts a value using one of the following syntaxes:

DataType(Expression)
(DataType)Expression

Here is an example

// Examples of converting variables from and to different identifiers

#include <iostream>

using namespace std;

main()

int i, iInt;

char a, aChar;

long g;

float f;

double d, dDouble;

// Assign values

i = 65;

a = 'r';

g = 241;

f = 2.06;

d = 122.448;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (29 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

cout << "The integer " << i << " converted to a character "

<< "is " << char(i) << "\n";

cout << "The character " << a << " converted to an integer "

<< "is " << int(a) << "\n";

cout << "The long integer " << g << " converted to a character "

<< "is " << char(g) << "\n";

cout << "The float value " << f << " converted to an integer "

<< "is " << (int)f << "\n";

cout << "The double value " << d << " converted to a character "

<< "is " << (char)d << "\n";

cout << "\n\n";

iInt = g + i;

aChar = i + a;

dDouble = d + g;

cout << "The long integer " << g << " + " << " the integer "

<< i << " converted to an integer " << "is "

<< int(iInt) << "\n";

cout << "The long integer " << g << " + " << " the integer "

<< i << " converted to a character " << "is "

<< char(iInt) << "\n";

cout << "The integer " << i << " + " << " the character "

<< a << " converted to an integer " << "is "

<< int(aChar) << "\n";

cout << "The integer " << i << " + " << " the character "

<< a << " converted to a character " << "is "

<< (char)aChar << "\n";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (30 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

cout << "The integer " << i << " * " << " the character "

<< a << " converted to an integer " << "is "

<< double(d * a) << "\n";

cout << "The double " << d << " / " << " the character "

<< a << " converted to an integer " << "is "

<< int(d / a) << "\n";

cout << "The double " << d << " + " << " the long integer "

<< g << " converted to an integer " << "is "

<< (int)dDouble << "\n";

cout << "\n\n";

This would produce:

The integer 65 converted to a character is A

The character r converted to an integer is 114

The long integer 241 converted to a character is ±

The float value 2.06 converted to an integer is 2

The double value 122.448 converted to a character is z

The long integer 241 + the integer 65 converted to an integer is 306

The long integer 241 + the integer 65 converted to a character is 2

The integer 65 + the character r converted to an integer is -77

The integer 65 + the character r converted to a character is •

The integer 65 * the character r converted to an integer is 13959.1

The double 122.448 / the character r converted to an integer is 1

The double 122.448 + the long integer 241 converted to an integer is 363

Operator Precedence and Direction

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (31 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

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.

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.

Name Operator Direction Precedence


Parentheses () Left -> Right 1
Post-increment ++ Left -> Right 2
Post-decrement -- Left -> Right 2
Address & Right -> Left 2
Bitwise NOT ~ Right -> Left 2
Typecast (type) Right -> Left 2
Logical NOT ! Right -> Left 2
Negation - Right -> Left 2
Plus Sign + Right -> Left 2
Pre-increment ++ Right -> Left 2
Pre-decrement -- Right -> Left 2
Size of data sizeof Right -> Left 2
Modulus % Left -> Right 3
Multiplication * Left -> Right 3
Division / Left -> Right 3
Addition + Left -> Right 4
Subtraction - Left -> Right 4
Bitwise Shift Left << Left -> Right 5
Bitwise Shift Right >> Left -> Right 5
Less Than < Left -> Right 6
Less Than or Equal <= Left -> Right 6
Greater Than > Left -> Right 6
Greater Than or Equal >= Left -> Right 6
Equal == Left -> Right 7
Not Equal != Left -> Right 7
Bitwise AND & Left -> Right 8
Bitwise XOR ^ Left -> Right 9
Bitwise OR | Left -> Right 10
Logical AND && Left -> Right 11
Logical OR || Left -> Right 12
Condition Expression ?: Right -> Left 13
Assignment = Right -> Left 14
Additive Assignment += Right -> Left 14
Subtractive Assignment -= Right -> Left 14
Multiplicative Assignment *= Right -> Left 14
Divisional Assignment /= Right -> Left 14
Modulating Assignment %= Right -> Left 14
Left Shift Assignment >>= Right -> Left 14
Right Shift Assignment <<= Right -> Left 14

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (32 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Operations and Expressions

AND Assignment &= Right -> Left 14


XOR Assignment |= Right -> Left 14
OR Assignment ^= Right -> Left 14
Comma , Left -> Right 15

Previous Copyright © 2002 FunctionX Next

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson04.htm (33 of 33)11/20/2006 3:55:09 PM


C++ Tutorial - Introduction to Functions

Introduction to Functions
A Function as an Assignment
A function is an assignment or a task you are asking C++ to perform for the functionality of your program. There are two
kinds of functions: those supplied to you and those you will be writing. The functions that are supplied to you are usually in
three categories: those built-in the operating system, those written in C++ (they are part of the C++ language), and those
supplied with your programming environment. The use of these functions is the same regardless of the means you get them;
you should know what a function looks like, how to create one, what functions are already available, where they are located,
and what a particular function does, how and when to use it.

Function Definition
In order to create and use your function, you must let the compiler know. Letting the compiler know about your function
means you “declare” it. The syntax of declaring a function is:

ReturnType FunctionName (Needs);

In English, an assignment, considered a function, is made of three parts: its purpose, its needs, and the expectation.

Return Value
The purpose of a function identifies what the function is meant to do. When a function has carried its assignment, it provides
a result. For example, if a function is supposed to calculate the area of a square, the result would be the area of a square.
The result of a function used to get a student’s first name would be a word representing a student’s first name. The result of
a function is called a return value. A function is also said to return a value.

There are two forms of expectations you will have from a function: a specific value or a simple assignment. If you want the
function to perform an assignment without giving you back a result, such a function is qualified as void and would be declared
as

void FunctionName(Needs);

A return value, if not void, can be any of the data types we have studied so far. This means that a function can return a char,
an int, a float, a double, a bool, or a string. Here are examples of declaring functions by defining their return values:

double FunctionName(Needs);
char FunctionName(Needs);
bool FunctionName(Needs);
string FunctionName(Needs);

Function Names

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (1 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

A function name follows the same rules we have applied to our variables so far. In addition, use a name that specifies what
the function is expected to do. Usually, a verb is appropriate for a function that performs an action; an example would be
add, start, assign, play, etc.

The names of most functions in this book will start in uppercase. Therefore, the above names would be: Add, Start, Assign,
Play.

If the assignment of a function is a combination of words, such as converting a temperature from Celsius to Fahrenheit, start
the name of the function with a verb and append the necessary words each starting in uppercase (remember that the name
of a function is in one word). Examples include ConvertToFahrenheit, CalculateArea, LoadFromFile, etc. Some functions will
not include a verb. They can simply represent a word such as Width, Index, New. They can also be a combination of words;
examples include DefaultName, BeforeConstruction, or MethodOfAssignment. Here are examples of function names

double CalculateArea(Needs);
char Answer(Needs);
bool InTheBox(Needs);
string StudentName(Needs);

Arguments – Parameters
In order to carry its assignment, a function might be supplied something. For example, when a function is used to calculate
the area of a square, you have to supply the side of the square, then the function will work from there. On the other hand, a
function used to get a student’s first name may not have a need; its job would be to supply or return something.

Some functions have needs and some do not. The needs of a function are provided between parentheses. These needs could
be as varied as possible. If a function does not have a need, leave its parentheses empty.

In some references, instead of leaving the parentheses empty, the programmer would write void. In this book, if a function
does not have a need, we will leave its parentheses empty.

Some functions will have only one need, some others will have many. A function’s need is called an Argument. If a function
has a lot of needs, these are its arguments.

The argument is a valid variable and is defined by its data type and a name. For example, if a function is supposed to
calculate the area of a square and it is expecting to receive the side of the square, you can declare it as

double CalculateArea(double Side);

A function used to get a student’s first name could be declared as:

string FirstName();

Here are examples of declaring functions; some take arguments, some don’t:

double CalculateArea(double Side);


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

Defining Functions

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (2 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

In order to use a function in your program, you have to let the compiler know what the function does. Sometimes (depending
on where the function is located in your program), you will not have to declare the function before using it; but you must
always tell the compiler what behavior you are expecting.

We have seen that the syntax of declaring a function was:

ReturnType FunctionName(Arguments);

To let the compiler know what the function is meant to do, you have to “define” it; which also means describing its behavior.
The syntax of defining a function is:

ReturnType FunctionName(Needs) {Body}

You define a function using the rule we applied with the main() function. Define it starting with its return value (if none, use
void), followed by the function name, its argument (if any) between parentheses, and the body of the function. Once you
have defined a function, other functions can use it.

Function Body
As an assignment, a function has a body. The body of the function describes what the function is supposed to do. The body
starts with an opening curly bracket “{“ and ends with a closing curly bracket “}”. Everything between these two symbols
belongs to the function. From what we have learned so far, examples of functions would be:

double CalculateArea(double Side) {};


char Answer() {};

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (3 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

Calling Functions
One of the main reasons of using various functions in your program is to isolate assignments; this allows you to divide the
jobs among different entities so that if something is going wrong, you might easily know where the problem is. Functions
trust each other, so much that one function does not have to know HOW the other function performs its assignment. One
function simply needs to know what the other function does, and what that other function needs.

Once a function has been defined, other functions can use the result of its assignment. Imagine you define two functions A
and B.

If Function A needs to use the result of Function B, function A has to use the name of function B. This means that Function A
has to “call” Function B:

When calling one function from another function, provide neither the return value nor the body, simply type the name of the
function and its list of arguments, if any. For example, to call a function named Welcome() from the main() function, simply
type it, like this:

main()

Message(); // Calling the Message() function

The compiler treats the calling of a function depending on where the function is declared with regards to the caller. You can
declare a function before calling it. Here is an example:

#include <iostream>

using namespace std;

void Message()

cout << "This is C++ in its truest form.";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (4 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

main()

Message(); // Calling the Message() function

If a function is defined after its caller, you must declare it prior to calling it. Here is an example:

#include <iostream.h>

main()

void Message();

cout << "We will start with the student registration process.";

Message(); // Calling the Message() function

void Message()

cout << "Welcome to the Red Oak High School.";

To use any of the functions that ship with the compiler, first include the library in which the function is defined, then call the
necessary function. Here is an example that calls the getchar() function:

#include <iostream>

#include <stdio.h>

using namespace std;

main()

cout << "This is C++ in its truest form...\n\n";

getchar();

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (5 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

Techniques of Returning a Value


void Functions
A function that does not return a value is declared and defined as void. Here is an example:

void Introduction()

cout << "This program is used to calculate the areas of some shapes.\n"

<< "The first shape will be a square and the second, a rectangle.\n"

<< "You will be requested to provide the dimensions and the program "

<< "will calculate the areas";

Any function could be a void type as long as you are not expecting it to return a specific value. A void function with a more
specific assignment could be used to calculate and display the area of a square. Here is an example:

void SquareArea()

double Side;

cout << "\nEnter the side of the square: ";

cin >> Side;

cout << "\nSquare characteristics:";

cout << "\nSide = " << Side;

cout << "\nArea = " << Side * Side;

When a function is of type void, it cannot be displayed on the same line with the cout extractor and it cannot be assigned to a
variable (since it does not return a value). Therefore, a void function can only be called.

Returning a Value

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (6 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

If you declare a function that is returning anything (a function that is not void), the compiler will need to know what value the
function returns. The return value must be the same type declared. The value is set with the return keyword.

If a function is declared as a char, make sure it returns a character (only one character). Here is an example:

char Answer()

char a;

cout << "Do you consider yourself a reliable employee (y=Yes/n=No)? ";

cin >> a;

return a;

A good function can also handle a complete assignment and only hand a valid value to other calling functions. Imagine you
want to process member’s applications at a sports club. You can define a function that would request the first and last names;
other functions that need a member’s full name would request it from such a function without worrying whether the name is
complete. The following function is in charge of requesting both names. It returns a full name that any desired function can
use:

string GetMemberName()

string FName, LName, FullName;

cout << "New Member Registration.\n";

cout << "First Name: ";

cin >> FName;

cout << "Last Name: ";

cin >> LName;

FullName = FName + " " + LName;

return FullName;

The return value can also be an expression. Here is an example:

double SquareArea(double Side)

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (7 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

return (Side * Side);

A return value could also be a variable that represents the result. Here is example:

double SquareArea(double Side)

double Area;

Area = Side * Side;

return Area;

If a function returns a value (other than void), a calling function can assign its result to a local variable like this:

Major = GetMajor();

Here is an example:

#include <iostream>

using namespace std;

int GetMajor()

int Choice;

cout << "\n1 - Business Administration";

cout << "\n2 - History";

cout << "\n3 - Geography";

cout << "\n4 - Education";

cout << "\n5 - Computer Sciences";

cout << "\nYour Choice: ";

cin >> Choice;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (8 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

return Choice;

main()

int Major;

cout << "Welcome to the student orientation program.";

cout << "Select your desired major:";

Major = GetMajor();

cout << "You select " << Major; cout << "\n";

You can also directly display the result of a function using the cout operator. In this case, after typing cout and its <<
operator, type the function name and its arguments names, if any.

So far, the compiler was displaying a warning because our main() function was not returning anything. In C++, a function
should always display a return type, otherwise, make it void. If you declare a function without a return type, by default, the
compiler considers that such a function should return an integer. Therefore, the main() function we have used so far should
return an integer as follows:

#include <iostream>

using namespace std;

main()

cout << "This is C++ in its truest form...\n\n";

return 0;

Strictly stated, the main() function can return any integer, which simply indicates that the program has ended. Returning 0
means that the program has terminated successfully. Since the main() function now returns an integer, you should indicate
this on its declared line. A better version of the above main() function would be:

#include <iostream>

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (9 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

using namespace std;

int main()

cout << "This is C++ in its truest form...\n\n";

return 0;

Techniques of Passing Arguments


In order to perform its assignment, a function may need arguments. Any function that wants to use the result of another
function must supply the other function’s required arguments, if any. When declaring a function that uses arguments, specify
each argument with a data type and a name.

Passing Arguments by Value


To use a function inside of another function, that is, to call a function from another function, specify the name of the function
and its list of arguments (if any) inside of parentheses; only the name of each argument is needed. You can declare a
function like this:

float GetHours(string FullName);

To call such a function from another, you would use:

GetHours(FullName);

Here is an example:

#include <iostream>

#include <string>

using namespace std;

string GetName()

string FirstName, LastName, FN;

cout << "Employee's First Name: ";

cin >> FirstName;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (10 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

cout << "Employee's Last Name: ";

cin >> LastName;

FN = FirstName + " " + LastName;

return FN;

int main()

string FullName;

double Hours;

double GetHours(string FullName);

FullName = GetName();

Hours = GetHours(FullName);

cout << "\nEmployee's Name: " << FullName;

cout << "\nWeekly Hours: " << Hours << " hours\n\n";

return 0;

double GetHours(string FullName)

double Mon, Tue, Wed, Thu, Fri, TotalHours;

cout << endl << FullName << "'s Weekly Hours\n";

cout << "Monday: "; cin >> Mon;

cout << "Tuesday: "; cin >> Tue;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (11 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

cout << "Wednesday: "; cin >> Wed;

cout << "Thursday: "; cin >> Thu;

cout << "Friday: "; cin >> Fri;

TotalHours = Mon + Tue + Wed + Thu + Fri;

return TotalHours;

Here is an example of running the program:

Employee's First Name: Frank

Employee's Last Name: Dassault

Frank Dassault's Weekly Hours

Monday: 8.00

Tuesday: 8.50

Wednesday: 9.00

Thursday: 8.00

Friday: 8.00

Employee's Name: Frank Dassault

Weekly Hours: 41.5 hours

Press any key to continue...

When declaring a function, the compiler does not require that you supply a name for each argument, it only needs to know
what type of argument(s) and how many arguments a function takes. This means that the GetHours() function could have
been declared as

float GetHours(string);

Furthermore, the compiler does not care about the name you give an argument when declaring a function. Imagine you want
to write a function that would calculate an item’s purchase price based on the item’s store price added the tax. The tax rate is
a percentage value. This means that a tax rate set at 7.50% in C++ terms is equal to 0.075 (because 7.50/100 = 0.075).
The tax amount collected on a purchase is taken from an item’s price; its formula is:

TaxRate
Tax Amount = Item Price *
100

The formula of calculating the final price of an item is:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (12 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (13 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

The final price is: 133.192

Press any key to continue...

Passing Arguments by Reference


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

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

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

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

Here are examples of passing some arguments by reference:

void Area(double &Side); // The argument is passed by reference


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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (14 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

float Hours, Rate, Wage;

void Earnings(float h, float r);

cout << "Enter the total Weekly hours: ";

cin >> Hours;

cout << "Enter the employee's hourly rate: ";

cin >> Rate;

cout << "\nIn the main() function,";

cout << "\n\tWeekly Hours = " << Hours;

cout << "\n\tSalary = $" << Rate;

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

cout << "\nCalling the Earnings() function";

Earnings(Hours, Rate);

cout << "\n\nAfter calling the Earnings() function, "

<< "in the main() function,";

cout << "\n\tWeekly Hours = " << Hours;

cout << "\n\tSalary = " << Rate;

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

return 0;

void Earnings(float ThisWeek, float Salary)

cout << "\n\nIn the Earnings() function,";

cout << "\n\tWeekly Hours = " << ThisWeek;

cout << "\n\tSalary = " << Salary;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (15 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

cout << "\n\tWeekly Salary= " << ThisWeek * Salary;

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

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

void Earnings(float ThisWeek, float Salary)

ThisWeek = 42;

cout << "\n\nIn the Earnings() function,";

cout << "\n\tWeekly Hours = " << ThisWeek;

cout << "\n\tSalary = " << Salary;

cout << "\n\tWeekly Salary= " << ThisWeek * Salary;

If you test the program with a weekly hours value of 35.50 and a salary of 8.50, you would notice that the weekly salary is
different inside of the Earnings() function but is kept the same in main(), before and after the Earnings() function. As an
example of passing an argument by reference, you could modify the declaration of the Earnings() function inside of the main
() function as follows:

void Earnings(float &h, float r);

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

void Earnings(float &ThisWeek, float Salary)

ThisWeek = 42;

cout << "\n\nIn the Earnings() function,";

cout << "\n\tWeekly Hours = " << ThisWeek;

cout << "\n\tSalary = " << Salary;

cout << "\n\tWeekly Salary= " << ThisWeek * Salary;

Default Arguments
http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (16 of 37)11/20/2006 3:55:30 PM
C++ Tutorial - Introduction to Functions

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (17 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

double Discount = 15; // That is 25% = 25

FinalPrice = CalculateNetPrice(Discount);

cout << "\nFinal Price = " << FinalPrice << "\n\n";

return 0;

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

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

#include <iostream>

using namespace std;

double CalculateNetPrice(double DiscountRate = 25)

double OrigPrice;

cout << "Please enter the original price: ";

cin >> OrigPrice;

return OrigPrice - (OrigPrice * DiscountRate / 100);

int main()

double FinalPrice;

FinalPrice = CalculateNetPrice();

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (18 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (19 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

return 0;

Here is the result produced:

Original Price: $245.55

Discount Rate: 25%

Tax Amount: $5.75

Final Price: $184.22

Press any key to continue...

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

● If a function takes two arguments, you can declare it with default values. If you want to provide a default value for only
one of the arguments, the argument that would have a default value must be the second in the list. Here is an example:

double CalculatePrice(double Tax, double Discount = 25);

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

#include <iostream>

using namespace std;

double CalculateNetPrice(double Tax, double Discount = 25)

double OrigPrice;

cout << "Enter the original price of the item: ";

cin >> OrigPrice;

double DiscountValue = OrigPrice * Discount / 100;

double TaxValue = Tax / 100;

double NetPrice = OrigPrice - DiscountValue + TaxValue;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (20 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

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.

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.

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (21 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

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: ";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (22 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (23 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

double Base, Height, Radius;

cout << "Enter the dimensions of the Rectangle\n";

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

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

cout << "\nMoment of inertia with regard to the X axis: ";

cout << "I = " << MomentOfInertia(Base, Height) << "mm";

cout << "\n\nEnter the radius: "; cin >> Radius;

cout << "Moment of inertia of a semi-circle with regard to the X axis: ";

cout << "I = " << MomentOfInertia(Radius) << "mm\n\n";

return 0;

Here are the formulas to calculate the moment of inertia of a triangle:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (24 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (25 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

double Base = 7.74, Height = 14.38, Radius = 12.42;

cout << "Rectangle\n"

<< "Moment of inertia with regard to the X axis: ";

cout << "I = " << MomentOfInertia(Base, Height) << "mm\n\n";

cout << "Semi-Circle\n"

<< "Moment of inertia with regard to the X axis: ";

cout << "I = " << MomentOfInertia(Radius) << "mm\n\n";

cout << "Enter the dimensions of the triangle\n";

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

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

cout << "\nTriangle\n" << "Moment of inertia with regard to the X axis: ";

cout << "I = " << MomentOfInertia(Base, Height, 1) << "mm\n\n";

return 0;

Constant Arguments

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (26 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

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

To let the compiler know that the value of an argument must stay constant, use the const keyword before the data type of
the argument. For example, if you declare a function like void Area(const string Side), the Area() is not supposed to modify
the value of the Side argument. Consider a function that is supposed to calculate and return the perimeter of a rectangle if it
receives the length and the width from another function, namely main(). Here is a program that would satisfy the operation
(notice the Perimeter() function that takes two arguments):

int main()

float Length, Width;

cout << "Rectangle dimensions.\n";

cout << "Enter the length: ";

cin >> Length;

cout << "Enter the width: ";

cin >> Width;

cout << "\nThe perimeter of the rectangle is: " << Perimeter(Length, Width);

cout << "\n\n";

return 0;

As you can see, the Perimeter() function does not change the values of the length or the width. To make the length and the
width arguments constant, you would change the declaration of the Perimeter() function as follows:

float Perimeter(const float l, const float w);

You can make 0, just one, or more arguments constants, and there is no order on which arguments can be made constant.

Here is an example

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (27 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

#include <iostream>

using namespace std;

// Rectangle

double MomentOfInertia(const double b, const double h)

return b * h * h * h / 3;

// Semi-Circle

double MomentOfInertia(const double R)

const double PI = 3.14159;

return R * R * R * R * PI/ 8;

// Triangle

double MomentOfInertia(const double b, const double h, int)

return b * h * h * h / 12;

int main()

double Base = 7.74, Height = 14.38, Radius = 12.42;

cout << "Rectangle\n"

<< "Moment of inertia with regard to the X axis: ";

cout << "I = " << MomentOfInertia(Base, Height) << "mm\n\n";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (28 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

cout << "Semi-Circle\n"

<< "Moment of inertia with regard to the X axis: ";

cout << "I = " << MomentOfInertia(Radius) << "mm\n\n";

cout << "\nTriangle\n"

<< "Moment of inertia with regard to the X axis: ";

cout << "I = " << MomentOfInertia(Base, Height, 1) << "mm\n\n";

return 0;

Passing Arguments by Constant Reference


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

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

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

double CalculateNetPrice(const double& Tax)

double Original;

const double Discount = 25;

Original = GetOriginalPrice();

double DiscountValue = Original * Discount / 100;

double TaxValue = Tax / 100;

double NetPrice = Original - DiscountValue + TaxValue;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (29 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

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%

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (30 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

const double Discount = 25;

double Price;

double Original;

void Receipt(const double& Orig, const double& Taxation,

const double& Dis, const double& Final);

GetOriginalPrice(Original);

Price = CalculateNetPrice(Original, TaxRate, Discount);

Receipt(Original, TaxRate, Discount, Price);

cout << "\n\n";

return 0;

void Receipt(const double& Original, const double& Tax,

const double& Discount, const double& FinalPrice)

cout << "\nReceipt";

cout << "\nOriginal Price: $" << Original;

cout << "\nTax Rate: " << Tax << "%";

cout << "\nDiscount Rate: " << Discount << "%";

cout << "\nFinal Price: $" << FinalPrice;

Inline Functions

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (31 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

When you call a function B() from a function A(), function A() sends a request and must get to Function B(). Whenever your
program includes a small function, C++ allows you to include such a function where it is being called. When function B() calls
function A(), instead of sending a request fo funtion A(), the compiler would include a copy of function A() into funtion B()
where it is being called. Such a function (function A()) is qualified inline.

To create a function as inline, use the inline keyword when declaring the function as well as when defining it. Here is an
example that makes use of an inline function:

#include <iostream>

using namespace std;

inline void Area(float Side)

cout << "The area of the square is " << Side * Side;

int main()

float s;

cout << "Enter the side of the square: ";

cin >> s;

Area(s);

cout << "\n\n";

return 0;

Static Variables

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (32 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

Consider the following program:

#include <iostream>

using namespace std;

void Starter(int y)

double a = 112.50;

double b = 175.25;

a = a / y;

b = b + 2;

cout << "y = " << y << endl;

cout << "a = " << a << endl;

cout << "b = " << b << endl;

cout << "b / a = " << b / a << "\n\n";

int main()

Starter(2);

Starter(2);

Starter(2);

Starter(2);

return 0;

When executed, this program would produce:

y = 2

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (33 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

a = 56.25

b = 177.25

b / a = 3.15111

y = 2

a = 56.25

b = 177.25

b / a = 3.15111

y = 2

a = 56.25

b = 177.25

b / a = 3.15111

y = 2

a = 56.25

b = 177.25

b / a = 3.15111

Press any key continue..

The Starter() function receives one argument passed when it is called. The called function also receives the same argument
every time. Looking at the result, the argument passed to the function and the local variables declared inside of the called
function keep the same value every time the function is called. That is, when the Starter() function is exited, the values
remain the same.

We know that, when a function is defined, any variable declared locally belongs to the function and its influence cannot
expand beyond the presence of the function. If you want a locally declared variable to keep its changed value when its host
function is exited, declare such a variable as static.

To declare a static variable, type the keyword static on the left of the variable’s data type. For example, if you plan to declare
a Radius variable as static in an Area() function, you could write:

double Area(){ static double Radius;}

You should always initialize a static variable before using it; that is, when declaring it. To make the local variables of our
Starter() function static, we can declare them as follows:

void Starter(int y)

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (34 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

static double a = 112.50;

static double b = 175.25;

a = a / y;

b = b + 2;

cout << "y = " << y << endl;

cout << "a = " << a << endl;

cout << "b = " << b << endl;

cout << "b / a = " << b / a << "\n\n";

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

y = 2

a = 56.25

b = 177.25

b / a = 3.15111

y = 2

a = 28.125

b = 179.25

b / a = 6.37333

y = 2

a = 14.0625

b = 181.25

b / a = 12.8889

y = 2

a = 7.03125

b = 183.25

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (35 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

b / a = 26.0622

Press any key continue...

Notice that, this time, each local variable keeps its newly changed value when the function exits. Since a function’s argument
can receive different values as the function is called different times, we can test our program by passing different values to its
argument as follows:

#include <iostream>

using namespace std;

void Starter(int y)

static double a = 112.50;

static double b = 175.25;

a = a / y;

b = b + 2;

cout << "y = " << y << endl;

cout << "a = " << a << endl;

cout << "b = " << b << endl;

cout << "b / a = " << b / a << "\n\n";

int main()

Starter(2);

Starter(5);

Starter(14);

Starter(25);

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (36 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Introduction to Functions

return 0;

The current version of the program would produce:

y = 2

a = 56.25

b = 177.25

b / a = 3.15111

y = 5

a = 11.25

b = 179.25

b / a = 15.9333

y = 14

a = 0.803571

b = 181.25

b / a = 225.556

y = 25

a = 0.0321429

b = 183.25

b / a = 5701.11

Press any key continue..

Previous Copyright © 2000-2003 FunctionX, Inc. Next

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson05.htm (37 of 37)11/20/2006 3:55:30 PM


C++ Tutorial - Control Statements

Conditional Statements
Logical Operations
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 value 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.

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (1 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

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

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (2 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

Value 2 = 0

Comparison of Value1 == 15 produces 1

Press any key to continue

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

#include <iostream.h>

int main()

int Value1 = 250;

int Value2 = 32;

int Value3 = !Value1;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (3 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

// 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.h>

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 !=

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (4 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

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.

Here is an example:

#include <iostream.h>

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (5 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

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

int main()

int Value1 = 15;

int Value2 = (Value1 < 24);

cout << "Value 1 = " << Value1 << "\n";

cout << "Value 2 = " << Value2 << "\n\n";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (6 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

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:

Value1 <= Value2

The <= operation performs a comparison as any of the last two. If both Value1 and VBalue2 hold the same value, 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.h>

int main()

int Value1 = 15;

int Value2 = (Value1 <= 24);

cout << "Value 1 = " << Value1 << "\n";

cout << "Value 2 = " << Value2 << "\n\n";

return 0;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (7 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (8 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

Here is a summary table of the logical operators we have studied:

Operator Meaning Example Opposite


== Equality to a == b !=
!= Not equal to 12 != 7 ==
< Less than 25 < 84 >=
<= Less than or equal to Cab <= Tab >
> Greater than 248 > 55 <=
>= Greater than or equal to Val1 >= Val2 <

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.

Let’s 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.h>

int main()

char Answer;

cout << "Do you consider yourself a hot-tempered individual? ";

cin >> Answer;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (9 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

return 0;

Some of the answers a user would type are y, yes, Y, Yes, YES, n, N, no, No, NO, I don’t 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
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.

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (10 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

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. Let’s 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 Boolean Value

The light is green true

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (11 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (12 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (13 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

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

int main()

int Number;

cout << "Enter a non zero number: ";

cin >> Number;

if(Number)

cout << "\nYou entered " << Number << endl;

cout << endl;

return 0;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (14 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

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 Boolean Value

The light is green true

The light is green 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 Boolean Value

The light is green true

The light is not green 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:

Boolean
Color Statement Symbol
Value

The light is green true P

The light is not green false !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:

Boolean Integer
Color Statement
Value Value

The light is green true 1

The light is not green false 0

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (15 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

Otherwise: if…else
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.h>

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. This is performed using the syntax:

if(Condition)
Statement1;
else
Statement2;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (16 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

The above program would better be written as:

#include <iostream.h>

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (17 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

The Conditional Operator (?:)


The conditional operator behaves like a simple if…else 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.h>

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: if…else if and if…else if…else

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (18 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

The previous conditional formula is used to execute one of two alternatives. Sometimes, your 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) if(Condition1)
Statement1; Statement1;
else if(Condition2) else if(Condition2)
Statement2; Statement2;
else else if(Condition3)
Statement-n; 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.h>

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (19 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

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 (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.h>

int main()

int Number;

cout << "Type a number between 1 and 3: ";

cin >> Number;

switch (Number)

case 1:

cout << "\nYou typed 1.";

case 2:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (20 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

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

int main()

int Number;

cout << "Type a number between 1 and 3: ";

cin >> Number;

switch (Number)

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (21 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

case 1:

cout << "\nYou typed 1.";

case 2:

cout << "\nYou typed 2.";

case 3:

cout << "\nYou typed 3.";

default:

cout << endl << Number << " is out of the requested range.";

return 0;

Counting and Looping


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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (22 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (23 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

An example would be:

#include <iostream.h>

int main()

int Number;// = 0;

while( Number <= 12 )

cout << "Number " << Number << endl;

Number++;

return 0;

The do...while Statement

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (24 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

The do…while statement uses the following syntax:

do Statement while (Condition);

The do…while 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 do…while statement must end
with a semicolon.

Another version of the counting program seen previously would be:

#include <iostream.h>

int main()

int Number = 0;

do

cout << "Number " << Number++ << endl;

while( Number <= 12 );

return 0;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (25 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

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 do…while 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.h>

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (26 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

#include <iostream.h>

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

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 variable’s 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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (27 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Control Statements

#include <iostream.h>

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-2003 FunctionX. Inc. Next

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson06.htm (28 of 28)11/20/2006 3:55:42 PM


C++ Tutorial - Constructing Expressions

Constructing Expressions
Accessories for Conditional Statements
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 do…while statement to wait for the user to sit down;
but as the do…while 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.h>

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!!!";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (1 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

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?

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

int main()

char SittingDown;

do {

cout << "Are you sitting down now(y/n)? ";

cin >> SittingDown;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (2 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

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

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?";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (3 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

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 == '1')

cout << "\nGreat.\nNow we will start the next exercise.";

else

cout << "\nWell, it looks like you are getting tired...";

else

cout << "\nWe had enough today";

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

return 0;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (4 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (5 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

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...";

else

cout << "\nWe had enough today";

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

return 0;

The break Statement

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (6 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

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

int main()

char Letter = 'd';

while( Letter <= 'n' )

cout << "Letter " << Letter << endl;

break;

return 0;

The break statement can also be used in a do…while 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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (7 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

#include <iostream.h>

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;

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (8 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

#include <iostream.h>

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (9 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

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

enum TEmploymentStatus { esFullTime, esPartTime, esContractor, esNS };

int main()

int EmplStatus;

cout << "Employee's Contract Status: ";

cout << "\n0 - Full Time | 1 - Part Time"

<< "\n2 - Contractor | 3 - Other"

<< "\nStatus: ";

cin >> EmplStatus;

cout << endl;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (10 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (11 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

return 0;

The continue Statement


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, do…while
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.h>

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

cout << "Number: ";

cin >> posNumber;

// If the number typed is not positive, ignore it

if( posNumber < 0 )

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (12 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

continue;

// Add each number to the sum

Sum += posNumber;

// Display the sum

cout << "\nSum of the numbers you entered = " << Sum << "\n\n";

return 0;

The goto Statement


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

int main()

for(int Count = 0; Count <= 12; ++Count)

cout << "Count " << Count << endl;

if( Count == 5 )

goto MamaMia;

MamaMia:

cout << "Stopped at 5";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (13 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

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:

Color Statement Boolean Value

The light is green true

The light is green 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 Boolean Value

The light is green true

The light is not green 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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (14 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

Boolean
Color Statement Symbol
Value

The light is green true P

The light is not green false !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:

Boolean Integer
Color Statement
Value Value

The light is green true 1

The light is not green false 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.h>

int main()

int Position;

cout << "Specify your position:\n"

<< "1 - Sitting Down\n"

<< "2 - Standing Up\n"

<< "3 - Laying Down\n";

cin >> Position;

if( Position == 1 )

cout << "\nNow, position your back as vertically as you can.\n";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (15 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

return 0;

That program allows the user to give one of three answers; and you might do something depending on the user’s 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.h>

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

int main()

int SittingDown;

cout << "Are you sitting down (1=Yes/0=No)? ";

cin >> SittingDown;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (16 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

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

Let’s segment these expressions and give each a name. The first statement will be called L. Therefore,

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 D B
true true 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?

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (17 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

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 D L && D B
true true true TRUE

When the traffic light is not red, regardless of the light’s 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 D L && D B
false true false 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 D L && D B
true false false 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 D L && D B
false false false FALSE

From our tables, the law is broken only when the light is red AND a driver drives through it. This produces:

L D L && D B
true true true TRUE
false true false FALSE
true false false FALSE
false false false FALSE

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 item’s size. Such a program could be written (or started) as follows:

#include <iostream.h>

int main()

int PizzaSize;

cout << "Select your pizza size";

cout << "\n1=Small | 2=Medium";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (18 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (19 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

} while( SittingDown != 'y' && SittingDown != 'Y' );

cout << "Wonderful!!!";

return 0;

Logical Disjunction: OR
Let’s 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 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 H T
true true 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. Let’s 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 H T
true Don't Care 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 H T
Don't Care true 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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (20 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

S H T
true true 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 H S || H T
true true true TRUE
false true true TRUE
true false true TRUE
false false false 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 hot-
tempered program can be restructured as follows:

#include <iostream.h>

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (21 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (22 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

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

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

#define Or ||

#define And &&

char GetPosition()

char Position;

do {

cout << "Are you sitting down now(y/n)? ";

cin >> Position;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (23 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (24 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

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

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...";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (25 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

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

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (26 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

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

#define Or ||

#define And &&

string GetPosition()

char Position;

cout << "Are you sitting down now(y/n)? ";

cin >> Position;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (27 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (28 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

#include <iostream.h>

#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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (29 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

#include <iostream.h>

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

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (30 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (31 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

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

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...";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (32 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Constructing Expressions

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-2003 FunctionX Next

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson07.htm (33 of 33)11/20/2006 3:55:54 PM


C++ Tutorial - Arrays

Introduction to Arrays
Introduction to Arrays

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (1 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

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 an Array Elements

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 3rd member of the array, you would type Distance[4]. 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>

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (2 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

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;

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 << "Distance 1: " << Distance[0] << endl;

cout << "Distance 2: " << Distance[1] << endl;

cout << "Distance 3: " << Distance[2] << endl;

cout << "Distance 4: " << Distance[3] << endl;

cout << "Distance 5: " << Distance[4] << endl;

return 0;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (3 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

This would produce:

Distance 1: 44.14

Distance 2: 720.52

Distance 3: 96.08

Distance 4: 468.78

Distance 5: 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 << "Distance 1: " << Distance[0] << endl;

cout << "Distance 2: " << Distance[1] << endl;

cout << "Distance 3: " << Distance[2] << endl;

cout << "Distance 4: " << Distance[3] << endl;

cout << "Distance 5: " << Distance[4] << endl;

return 0;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (4 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (5 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (6 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

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>

using namespace std;

int main()

const int NumberOfItems = 5;

double Distance[NumberOfItems];

cout << "Distance 1: " << Distance[0] << endl;

cout << "Distance 2: " << Distance[1] << endl;

cout << "Distance 3: " << Distance[2] << endl;

cout << "Distance 4: " << Distance[3] << endl;

cout << "Distance 5: " << Distance[4] << endl;

return 0;

This would produce:

Distance 1: -9.25596e+061

Distance 2: -9.25596e+061

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (7 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

Distance 3: -9.25596e+061

Distance 4: -9.25596e+061

Distance 5: -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 << "Distance 1: " << Distance[0] << endl;

cout << "Distance 2: " << Distance[1] << endl;

cout << "Distance 3: " << Distance[2] << endl;

cout << "Distance 4: " << Distance[3] << endl;

cout << "Distance 5: " << Distance[4] << endl;

return 0;

This would produce:

Distance 1: 44.14

Distance 2: 720.52

Distance 3: 96.08

Distance 4: 0

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (8 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

Distance 5: 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;

cout << "Distance 4: " << Distance[3] << endl;

cout << "Distance 5: " << Distance[4] << endl;

cout << "Distance 6: " << Distance[5] << endl;

cout << "Distance 7: " << Distance[6] << endl;

cout << "Distance 8: " << Distance[7] << 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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (9 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

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 1st and the 4th 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";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (10 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

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

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (11 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

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

Press any key to continue

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (12 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

int Numbers[] = {8, 25, 36, 44, 52, 60, 75, 89};

int Find;

int i, m = 8;

cout << "Enter a number to search: ";

cin >> Find;

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

Press any key to continue

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (13 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (14 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

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;

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (15 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (16 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

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;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (17 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (18 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

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

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)

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (19 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (20 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

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 necessary when defining the function. Therefore, the above function can be declared as
follows:

#include <iostream>

using namespace std;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (21 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (22 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

Country\Data Map Flag Area (sq km) Population

United States 9,629,091 272,639,608

Cameroon 475,440 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 two-dimensional
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:

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (23 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

#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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (24 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

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:

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)

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (25 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Arrays

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-2003 FunctionX, Inc. Next

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson08.htm (26 of 26)11/20/2006 3:56:06 PM


C++ Tutorial - Pointers

Introduction to Pointers
An Overview of Pointers

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.

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

int main()

int Value;

cout << "Value lives at "

<< &Value;

cout << "\n\n";

return 0;

After executing the program, you could get:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson09.htm (1 of 21)11/20/2006 3:56:36 PM


C++ Tutorial - Pointers

Value lives at: 0x0065FDF4

Press any key to continue


.

Definition

Unfortunately, I will explain later on "WHY" use pointers. This is because we first need to know WHAT a pointer is, HOW to
declare it inside of a function, and HOW to use it. Pointers are not particularly useful when declared and used inside of one
function. They show their capabiliities 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:

DateType * 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

DateType* PointerName;
DateType * PointerName;
DateType *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:

DateType* Pointer1, Pointer2;

Only the first variable is a pointer, the second is a regular variable. If you want to declare different variables, you use:

DateType* Pointer1, *Pointer2;

Or

DateType* Pointer1;
DateType* 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.h>

int main()

int Value;

int *Pointer;

cout << "Value lives at " << &Value << "\n";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson09.htm (2 of 21)11/20/2006 3:56:36 PM


C++ Tutorial - Pointers

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

Press any key to continue


.

Initializing a Pointer

The reason 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.h>

int main()

int Value = 12;

int *Pointer = &Value;

cout << "Value lives at: " << Value << "\n";

cout << "Pointer lives at: " << *Pointer;

cout << "\n\n";

return 0;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson09.htm (3 of 21)11/20/2006 3:56:36 PM


C++ Tutorial - Pointers

The program would produce:

Value lives at: 12


Pointer lives at: 12

Press any key to continue

This program could also have the pointer initialized as:

#include <iostream.h>

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

int main()

int Value;

int *Pointer;

Pointer = &Value;

Value = 26;

cout << "Value = " << Value << "\n";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson09.htm (4 of 21)11/20/2006 3:56:36 PM


C++ Tutorial - Pointers

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

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson09.htm (5 of 21)11/20/2006 3:56:36 PM


C++ Tutorial - Pointers

#include <iostream.h>

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

*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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson09.htm (6 of 21)11/20/2006 3:56:36 PM


C++ Tutorial - Pointers

Operations on Pointers

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

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

int main()

int Students;

int *ptrStudents;

ptrStudents = &Students;

cout << "Number of students: ";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson09.htm (7 of 21)11/20/2006 3:56:36 PM


C++ Tutorial - Pointers

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

Press any key to continue

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

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson09.htm (8 of 21)11/20/2006 3:56:36 PM


C++ Tutorial - Pointers

#include <iostream.h>

int main()

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson09.htm (9 of 21)11/20/2006 3:56:36 PM


C++ Tutorial - Pointers

#include <iostream.h>

int main()

int Boys;

int Girls;

int Total;

int *ptrBoys;

int *ptrGirls;

int *ptrTotal;

ptrBoys = &Boys;

ptrGirls = &Girls;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson09.htm (10 of 21)11/20/2006 3:56:36 PM


C++ Tutorial - Pointers

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

Press any key to continue

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.

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 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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson09.htm (11 of 21)11/20/2006 3:56:36 PM


C++ Tutorial - Pointers

#include <iostream.h>

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

Press any key to continue

To pass arguments to a function, you can make the following changes:

#include <iostream.h>

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson09.htm (12 of 21)11/20/2006 3:56:36 PM


C++ Tutorial - Pointers

cout << "\n\nAfter calling Deposit(), within main():\n";

cout << "\tShirts = " << Shirts << endl;

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

Press any key to continue

To pass pointer arguments, use the asterisks when declaring the function, and use the ampersand & when calling the function. Here is
an example:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson09.htm (13 of 21)11/20/2006 3:56:36 PM


C++ Tutorial - Pointers

#include <iostream.h>

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;

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()"

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson09.htm (14 of 21)11/20/2006 3:56:36 PM


C++ Tutorial - Pointers

<< "\n\tShirts = " << s

<< "\n\tPants = " << p;

void Pickup(int *sht, int *pt)

*sht = 26;

*pt = 17;

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

After calling Deposit(), within main():

Shirts = 12

Pants = 5

Within Pickup()

Shirts = 26

Pants = 17

After calling Pickup(), within main():

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson09.htm (15 of 21)11/20/2006 3:56:36 PM


C++ Tutorial - Pointers

Shirts = 26

Pants = 17

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

int main()

int StudentAge = 12;

cout << "Student age = " << StudentAge << endl;

cout << endl;

return 0;

Now, let's add a pointer and try to access it without initializing it:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson09.htm (16 of 21)11/20/2006 3:56:36 PM


C++ Tutorial - Pointers

#include <iostream.h>

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

int main()

int StudentAge = 12;

int* Age;

Age = &StudentAge;

cout << "Student age = " << StudentAge << endl;

cout << "*Age = " << *Age << endl;

cout << endl;

return 0;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson09.htm (17 of 21)11/20/2006 3:56:36 PM


C++ Tutorial - Pointers

To illustrate that an un-initialized variable has an address (although empty), you can change the file as follows:

#include <iostream.h>

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

int main()

int StudentAge;

int *Age;

Age = &StudentAge;

cout << "Student age = " << StudentAge << endl;

cout << "*Age = " << *Age << endl;

*Age = 15;

cout << "Student age = " << StudentAge << endl;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson09.htm (18 of 21)11/20/2006 3:56:36 PM


C++ Tutorial - Pointers

cout << "*Age = " << *Age << endl;

cout << "\n";

return 0;

This results in:

Student age = -858993460

*Age = -858993460

Student age = 15

*Age = 15

Press any key to continue

To dynamically allocate memory, you assign the pointer with the new keyword followed by the appropriate identifier:

#include <iostream.h>

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 = " << *Age << endl;

cout << "\n";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson09.htm (19 of 21)11/20/2006 3:56:36 PM


C++ Tutorial - Pointers

return 0;

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 = " << *Age << endl;

cout << "\n";

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;

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson09.htm (20 of 21)11/20/2006 3:56:36 PM


C++ Tutorial - Pointers

delete Age;

cout << "\n";

return 0;

Previous Copyright © 2000-2003 FunctionX, Inc. Next

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson09.htm (21 of 21)11/20/2006 3:56:36 PM


C++ Tutorial - Strings

Arrays of Characters and C-Strings


Arrays of Characters

Introduction
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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (1 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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>

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (2 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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

cout << "\nFull Name: " << FirstName << " " << MI << ". " << LastName;

return 0;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (3 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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: ";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (4 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

cin.getline(Title, 40);

cout << "Publisher: ";

cin.getline(Publisher, 50);

cout << "\nBook Information";

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (5 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (6 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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;

Country = "Republique d'Afrique du Sud";

cout << "Country Name: " << Country << "\n\n";

return 0;

Dynamic Arrays of Characters

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (7 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (8 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (9 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (10 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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;

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (11 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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

cout << "Countries Names";

cout << "\nCountry 1: " << Country[0];

cout << "\nCountry 2: " << Country[1];

cout << "\nCountry 3: " << Country[2];

cout << "\nCountry 4: " << Country[3];

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (12 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (13 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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:

#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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (14 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (15 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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)

cout << "Countries Names";

for(int i = 0; i < n; ++i)

cout << "\nCountry " << i + 1 << ": " << S[i];

int main()

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (16 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (17 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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
http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (18 of 31)11/20/2006 3:56:47 PM
C++ Tutorial - Strings

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (19 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (20 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (21 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

The strcpy Function


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;

strcpy(CarName2, CarName1);

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (22 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (23 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

cout << "\nSecond Car: " << CarName2;

strncpy(CarName2, CarName1, 8);

cout << "\n\nAfter using strncpy() for 8 characters";

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (24 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (25 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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

The result of comparing Stanley and Stanley is 0

The strncmp() Function

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (26 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (27 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (28 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

using namespace std;

int main()

char CustomerAddress[] = "4812 LOCKWOOD Drive #F04";

cout << "Customer Address: " << CustomerAddress << endl;

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 function’s 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()

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (29 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

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

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 null-terminated 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 Used to Display Character Used to Display


Floating-point
s A string f
value
c A character d An integer

Previous Copyright © 2000-2003 FunctionX, Inc. Next

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (30 of 31)11/20/2006 3:56:47 PM


C++ Tutorial - Strings

Copyright © 1999 FunctionX -- Webmaster

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson10.htm (31 of 31)11/20/2006 3:56:47 PM


C++ Tutorials - Exception Handling

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 doesn’t 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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (1 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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
somebody’s 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 can’t 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 program’s 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.
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 try’s 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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (2 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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(...)

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (3 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

cout << "\n";

return 0;

If you run this program and type a positive integer for the student’s age, the program would respond by displaying the
student age. That’s 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>

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (4 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

// 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 student’s age from the user. As we know, everybody’s 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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (5 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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

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 doesn’t 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. Let’s 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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (6 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (7 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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: ";

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (8 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (9 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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 doesn’t 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
didn’t 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)

case '+':

Result = Operand1 + Operand2;

break;

case '-':

Result = Operand1 - Operand2;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (10 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (11 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

#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 '*':

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (12 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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;

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (13 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

#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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (14 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (15 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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 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 can’t, 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: ";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (16 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (17 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

// 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 int n)

cout << "\nBad Operation: Division by " << n << " not allowed\n\n";

catch(const char n)

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (18 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (19 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

cout << "This program allows you to perform an operation on two numbers\n";

try {

cout << "To proceed, enter\n";

cout << "First Number: "; cin >> Number1;

cout << "An 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 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 '+':

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (20 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

Result = Operand1 + Operand2;

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (21 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (22 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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 '-':

Value = Oper1 - Oper2;

break;

case '*':

Value = Oper1 * Oper2;

break;

case '/':

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (23 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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 << "To proceed, enter\n";

cout << "First Number: "; cin >> Number1;

cout << "An 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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (24 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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)

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (25 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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 '+':

Value = Oper1 + Oper2;

break;

case '-':

Value = Oper1 - Oper2;

break;

case '*':

Value = Oper1 * Oper2;

break;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (26 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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 << "To proceed, enter\n";

cout << "First Number: "; cin >> Number1;

cout << "An 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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (27 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (28 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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;

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)

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (29 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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

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 )

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (30 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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

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

try {

cout << "To proceed, enter two numbers: ";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (31 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (32 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

#include <iostream.h>

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (33 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

// 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 doesn’t 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:

#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 << "To proceed, enter\n";

cout << "First Number: "; cin >> Number1;

cout << "An Operator: "; cin >> Operator;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (34 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

cout << "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";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (35 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (36 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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;

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (37 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (38 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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 doesn’t 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 doesn’t 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;

cout << "This program allows you to perform an operation on two numbers\n";

try {

cout << "To proceed, enter\n";

cout << "First Number: "; cin >> Number1;

cout << "An Operator: "; cin >> Operator;

cout << "Second Number: "; cin >> Number2;

Operand1 = Validate(Number1);

Operand2 = Validate(Number2);

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (39 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (40 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (41 of 42)11/20/2006 3:57:04 PM


C++ Tutorials - Exception Handling

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-2003 FunctionX, Inc. Next

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson11.htm (42 of 42)11/20/2006 3:57:04 PM


C++ Tutorial - Introcution to Classes

Introduction to Classes
Programmer-Defined Objects
The data types we have applied so far to our variables were used to identify individual items. To create more advanced and
complete objects, C++ allows you to group these identifiers and create a newly defined object.

Introduction
An object, such as a CD Player, a printer, a car, etc, is built from assembling various parts. In the same way, C++ allows you
to group various variables and create a new object called a class.

Imagine a company that manufactures shoe boxes hires you to write a program that would help design and identify those
shoe boxes. A shoe box is recognized for its dimensions (length, width, height), color, and shoe size that a particular box can
contain, etc. The variables that characterize such an object could be:

double Length, Width, Height;


char Color;
float ShoeSize;

And the program that defines a shoe box object could be:

#include <iostream>

#include <iomanip>

#include <string>

using namespace std;

int main()

// Define the characteristics of a shoe box

// The following characteristics are COMPLETELY random

double Length(12.55), Width(6.32), Height(8.74);

string Color("Yellow Stone");

float ShoeSize = 10.50;

// Display the characteristics of the shoe box

cout << "Characteristics of this shoe box";

cout << setiosflags(ios::fixed) << setprecision(2);

cout << "\n\tLength = " << Length << "\n\tWidth = " << Width

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (1 of 24)11/20/2006 3:57:12 PM


C++ Tutorial - Introcution to Classes

<< "\n\tHeight = " << Height << "\n\tVolume = " << Length * Width * Height

<< "\n\tColor = " << Color << "\n\tSize = " << ShoeSize << "\n\n";

return 0;

The program would produce:

Characteristics of this shoe box

Length = 12.55

Width = 6.32

Height = 8.74

Volume = 693.22

Color = Yellow Stone

Size = 10.50

Press any key to continue...

Unless dealing with one shoe box, this program would be rudimentary to run for each object. The solution is to create an
object called box that groups everything that characterizes the object.

Creating a Class
To create a class, use the class keyword followed by a name for the object. Like any other declared variable, the class
declaration ends with a semi-colon. The name of a class follows the rules we have applied so far for variable and function
names. To declare a class called ShoeBox, you would type the following:

class ShoeBox;

As a name that represents a group of items, a class has a body that would be used to define the items that compose it. The
body of a class starts with an opening curly bracket "{" and ends with a closing one "}". Therefore, another way to create a
class is:

class ClassName{};

This could also be created as:

class ClassName {
};

or

class ClassName
{
};

Either of these techniques produces the same effect.

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (2 of 24)11/20/2006 3:57:12 PM


C++ Tutorial - Introcution to Classes

Since a class is built from combining other identifiers, you will list each variable inside of the body of the class. Each item that
composes the class is represented as a complete variable declared with a data type and a name. As a variable, each
declaration must end with a semi-colon.

Continuing with our shoe box object, you could create it using the class as follows:

class ShoeBox

double Length, Width, Height;

char Color[12];

float ShoeSize;

};

The items that compose a class are called members of the class.

Accessing a Class
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 functions 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. The others are in the private section. If you
do not specify these sections, all of the members of a class are considered private. For example, all of the members of the
previously defined ShoeBox class are private.

Using the public and private sections, our shoe box object can be created as:

class ShoeBox

public:

double Length, Width, Height;

string Color;

private:

float ShoeSize;

};

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (3 of 24)11/20/2006 3:57:12 PM


C++ Tutorial - Introcution to Classes

The public and private keywords are referenced by their access level because they control how much access a variable allows.
You can create as many public sections or as many private sections as you want. For example, the above class could be
created as:

class ShoeBox

public:

double Length, Width, Height;

public:

string Color;

double Volume;

private:

float ShoeSize;

private:

char Material;

string Color;

};

When creating a class with different public and private sections, all of the declared variables under an access level keyword
abide by the rules of that access level. The fact that you use different public sections does not by any means warrant 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.

A variable that is declared in a class is called a member of the class. Once the class has been defined, you can use it as an
individual variable.

Declaring a Class
After defining a class, you can declare it as a variable using the same syntax we have used for any other variable. A class is
declared using its name followed by a name for the defined variable and ending with a semi-colon. For example, our ShoeBox
class can be declared as follows:

ShoeBox Shake;

When an object has been declared, you can access any of its members using the member access operator ".". First, type the
name of the object variable, followed by a period, followed by the name of the member you want to access. For example, to
access the member Length of the above class, you would write:

Shake.Length;

Using this syntax, you can display the value of a class member:

cout << Shake.Length;

or you can request its value from the user, using the cin operator. Here is an example:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (4 of 24)11/20/2006 3:57:12 PM


C++ Tutorial - Introcution to Classes

cin >> Shake.Lengh;

Using the cout extractor to display the values of the object members, our program could be as follows:

#include <iostream>

#include <string>

using namespace std;

class ShoeBox

public:

double Length, Width, Height;

string Color;

private:

float ShoeSize;

};

int main()

ShoeBox Shake; // Display the characteristics of the shoe box

cout << "Characteristics of this shoe box";

cout << "\n\tLength = " << Shake.Length

<< "\n\tWidth = " << Shake.Width

<< "\n\tHeight = " << Shake.Height

<< "\n\tVolume = " << Shake.Length * Shake.Width * Shake.Height

<< "\n\tColor = " << Shake.Color

<< "\n\tSize = " << Shake.ShoeSize

<< "\n\n";

return 0;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (5 of 24)11/20/2006 3:57:12 PM


C++ Tutorial - Introcution to Classes

At this time, because of trying to access a private member, the program would produce the following error

[C++ Error] Unit1.cpp(30): E2247 'ShoeBox::TShoeSize' is not accessible

Even if you change the ShoeSize member access from private to public, the program would render unpredictable results
because the members have not been given appropriate values:

Characteristics of this shoe box Length = 0 Width = 1.79571e-307 Height = 4.17266e-315 Volume = 0 Color = Size =
3.58732e-43Press any key to continue...

Techniques of Initializing a Class


There are various techniques used to initialize a class: 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.

#include <iostream>

#include <string>

using namespace std;

class ShoeBox

public:

double Length, Width, Height;

string Color;

float ShoeSize;

private:

};

int main()

ShoeBox Shake;

double Volume; // Initializing each member of the class

Shake.Length = 12.55;

Shake.Width = 6.32;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (6 of 24)11/20/2006 3:57:12 PM


C++ Tutorial - Introcution to Classes

Shake.Height = 8.74;

Shake.Color = "Yellow Stone";

Shake.ShoeSize = 10.50;

Volume = Shake.Length * Shake.Width * Shake.Height;

// Display the characteristics of the shoe box

cout << "Characteristics of this shoe box";

cout << "\n\tLength = " << Shake.Length

<< "\n\tWidth = " << Shake.Width

<< "\n\tHeight = " << Shake.Height

<< "\n\tVolume = " << Volume

<< "\n\tColor = " << Shake.Color

<< "\n\tSize = " << Shake.ShoeSize << "\n\n";

return 0;

This time, the program would render a reasonable result.

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; each value is
separated with a comma. The first rule you must keep in mind is that the list of variables must follow the order of the
declared members of the class. The second rule you must observe is that none of the members of the class must be another
class. In the following example, one of the members of the class is another class, namely a string. Because of the way a
variable of the class is declared, the program would not compile:

#include <iostream>

#include <string>

using namespace std;

class ShoeBox

public:

double Length, Width, Height;

string Color;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (7 of 24)11/20/2006 3:57:12 PM


C++ Tutorial - Introcution to Classes

float ShoeSize;

private:

};

int main()

// Declaring and initializing the class as a variable

ShoeBox LadyShake = { 12.55, 6.32, 8.74, "Yellow Stone", 10.50 };

Double Volume = LadyShake.Length * LadyShake.Width * LadyShake.Height;

// Display the characteristics of the shoe box

cout << "Characteristics of this shoe box";

cout << "\n\tLength = " << LadyShake.Length

<< "\n\tWidth = " << LadyShake.Width

<< "\n\tHeight = " << LadyShake.Height

<< "\n\tVolume = " << Volume

<< "\n\tColor = " << LadyShake.Color

<< "\n\tSize = " << LadyShake.ShoeSize << "\n\n";

return 0;

Classes and Member Functions


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. In this book, 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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (8 of 24)11/20/2006 3:57:12 PM


C++ Tutorial - Introcution to Classes

A member function is declared like any of the functions we have used so far; it could or could not return a value.

The shoe box we have been using so far needs a volume that would be used to determine what size can fit in the box.
Therefore, we will use a member function that can perform that calculation. Our object, when including methods could be
structured as follows:

class ShoeBox

public:

double Length;

double Width;

double Height;

string Color;

float ObtainShoeSize();

double CalcVolume();

private:

};

When using functions 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 objects. 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 the private section. After
doing this, use the methods in the public section to help the class interact with the other objects or functions of the program.
At this time, our ShoeBox object would look like this:

class ShoeBox

public:

float ObtainShoeSize();

double CalcVolume();

string Color;

private:

double Length;

double Width;

double Height;

};

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (9 of 24)11/20/2006 3:57:12 PM


C++ Tutorial - Introcution to Classes

There are at least two techniques you can use to implement a method member

Implementing Member Functions Locally


To implement a method in the class where it is declared, use the same techniques we used to define regular functions. When
a method is a class' member, it has access to the member variables of the same class; this means you do not need to pass
the variables as arguments (there are cases when you will need to); you can just use any of them as if it were supplied. Here
is how you would define the CalcVolume() method inside of the ShoeBox class:

#include <string>

using namespace std;

class ShoeBox

public:

float ObtainShoeSize();

double CalcVolume()

return (Length * Width * Height);

string Color;

private:

double Length;

double Width;

double Height;

};

If your class has a lot of methods, this technique could be cumbersome. You should use it only for small methods.

Implementing Member Functions Globally

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (10 of 24)11/20/2006 3:57:12 PM


C++ Tutorial - Introcution to Classes

When the methods execute long assignments, you should implement them outside of the object by first accessing the desired
function member of the class. To access a method of a class when implementing it, instead of the member access operator
“.”, you will use the scope resolution operator represented as two colons ::

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.

Another implementation of our CalcVolume() method would be:

class ShoeBox

public:

float ObtainShoeSize();

double CalcVolume();

string Color;

private:

double Length;

double Width;

double Height;

};

double ShoeBox::CalcVolume()

return (Length * Width * Height);

Inline Methods
When studying functions, we learned that an assignment can be carried where it is being called. 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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (11 of 24)11/20/2006 3:57:12 PM


C++ Tutorial - Introcution to Classes

class ShoeBox

public:

inline Double CalcVolume();

float CalcShoeSize();

void Display();

private: . . .

};

You can choose which methods would be inline and which ones 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.

If you decide to implement a method locally (in the class), you have the option of implementing it as inline:

class ShoeBox

public:

inline double CalcVolume()

return Length * Width * Height;

inline float CalcShoeSize()

return Length - 0.35;

void Display();

private:

double Length;

double Width;

double Height;

string Color;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (12 of 24)11/20/2006 3:57:12 PM


C++ Tutorial - Introcution to Classes

};

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.

Class Members Interactions


Regardless of how the member methods of an object are implemented, any method can call another without using an access
operator. This allows an object’s methods to exchange information among themselves easily. Furthermore, unlike regular
functions where a function must be declared prior to another function calling it, the method members of a class do not abide
by that rule: one method can call another method before or after the other has been implemented, as long as it is defined
somewhere.

#include <iostream>

#include <string>

using namespace std;

class ShoeBox

public: . . .

};

void ShoeBox::Display()

// Initializing the dimensions

Length = 12.55;

Width = 6.32;

Height = 8.74;

Color = "Early Breeze";

// Display the characteristics of the shoe box

cout << "Characteristics of this shoe box";

cout << "\n\tLength = " << Length

<< "\n\tWidth = " << Width

<< "\n\tHeight = " << Height

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (13 of 24)11/20/2006 3:57:12 PM


C++ Tutorial - Introcution to Classes

<< "\n\tVolume = " << CalcVolume()

<< "\n\tColor = " << Color

<< "\n\tSize = " << CalcShoeSize();

duble ShoeBox::CalcVolume()

return Length * Width * Height;

Once an object is defined and behaves as complete as possible, the other function or objects of the program can make the
appropriate calls trusting that the called object can handle its assignments efficiently. This ability allows you to
(tremendously) reduce the work overload of the other components of a program.

The main() function can simply call the appropriate member of the ShoeBox object now:

int main()

ShoeBox Sample;

Sample.Display();

return 0;

Tuning Objects
There are other features you can apply to make your objects more professional and less prone to errors. These include
constant arguments, constant, private, and inline methods, etc.

Constant Arguments

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (14 of 24)11/20/2006 3:57:12 PM


C++ Tutorial - Introcution to Classes

When studying functions, we learned that when a function receives an argument that it does not modify, the argument should
be declared as constant. This allows the compiler to make sure the argument would not be modified. The same technique
applies to an argument used by a method of an object.

To declare an argument of an object’s method as constant, type the const keyword on the left of the argument’s data type.
To improve our ShoeBox object, 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 Area();

On a box (rectangular parallelepiped), we have three rectangles 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 Area(Double Side1, Double Side2);

After declaring it in the public section, we would define it as follows:

double ShoeBox::Area(Double Side1, Double Side2)

return Side1 * Side2;

In the Display() method, we could display the area of the length by the height using:

cout << “\n\tArea = “ << Area(Length, Height);

As you can see, the Side1 and Side2 arguments are not modified; therefore, they should be declared as constants. To declare
each as constant, we would change the declaration of the method as follows:

Double Area(const Double Side1, const Double Side2);

And we would define it as follows:

double ShoeBox::Area(const Double Side1, const Double Side2)

return Side1 * Side2;

For an example such as this one, the const keyword can be typed before or after the data type, the result would be the same.
If a method is receiving more than one argument, their constancy is independent: the fact that one of them needs to be
constant does not imply anything about the other(s).

To help the method specify what side it is calculating the area, we could provide a string that names the side. We could
declare the method as follows:

void Area(const Double Side1, const Double Side2, PChar SideName);

We would then define the new method as follows:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (15 of 24)11/20/2006 3:57:12 PM


C++ Tutorial - Introcution to Classes

void ShoeBox::Area(const Double S1, const Double S2, PChar n)

cout << "\nThe area of the " << n << " side is: " << S1 * S2;

In the Display() method, we could specify the name of the side and provide the corresponding measures as follows:

Area(Length, Height, "front");Area(Length, Width, "top");Area(Width, Height, "left");

Here is the complete implementation:

#include <iostream>

#include <string>

using namespace std;

class ShoeBox

public:

double CalcVolume()

return Length * Width * Height;

void Area(const double Side1, const double Side2, char SideName[]);

float CalcShoeSize()

return Length - 0.35;

void Display();

private:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (16 of 24)11/20/2006 3:57:12 PM


C++ Tutorial - Introcution to Classes

double Length;

double Width;

double Height;

char Color[32];

};

void ShoeBox::Area(const double S1, const double S2, char N[])

cout << "\nThe area of the " << N << " side is: " << S1 * S2;

void ShoeBox::Display()

// Initializing the dimensions

Length = 10.42;

Width = 5.28;

Height = 5.88;

Color = "Yellow Stone";

// Display the characteristics of the shoe box

cout << "Characteristics of this shoe box";

cout << "\nDimensions(L*H*W) = "

<< Length << " * " << Height << " * " << Width;

Area(Length, Height, "front");

Area(Length, Width, "top");

Area(Height, Width, "left");

cout << "\n\tVolume = " << CalcVolume()

<< "\n\tColor = " << Color

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (17 of 24)11/20/2006 3:57:12 PM


C++ Tutorial - Introcution to Classes

<< "\n\tSize = " << CalcShoeSize();

int main()

ShoeBox Bambou;

Bambou.Display();

return 0;

Constant Methods
Some of the method members of an object, though using member variables of the same object, do not modify them. To
make sure that such a method does not alter the value of a member variable, 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 it. Here is an
example:

string SpecFullName() const;

The CalcVolume() and the CalcShoeSize() methods do not modify the member variables they receive. You can reinforce this
by declaring them as const:

double CalcVolume() const;float CalcShoeSize() const;

When implementing the method, type the const keyword on the right side of the method’s closing parenthesis:

double ShoeBox::CalcVolume() const

return Length * Width * Height;

float ShoeBox::CalcShoeSize() const

return Length - 0.35;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (18 of 24)11/20/2006 3:57:12 PM


C++ Tutorial - Introcution to Classes

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.

Notice that the Display() method assigns values to the member variables, which means it alters their values. Therefore, it
cannot be declared or defined as constant. Here is the new version of our ShoeBox object:

class ShoeBox

public:

double CalcVolume() const

return Length * Width * Height;

void Area(const double Side1, const double Side2, char SideName[]);

float CalcShoeSize() const

return Length - 0.35;

void Display();

private:

double Length;

double Width;

double Height;

string Color;

};

The program would still produce the same result.

Private Methods
http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (19 of 24)11/20/2006 3:57:12 PM
C++ Tutorial - Introcution to Classes

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 do not call such methods and do
not communicate with them. If you create a class and know that a particular member 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:

class Employee

public:

void IdentifyEmployee();

string FullName() const { return FirstName + " " + LastName; }

void GetHourlySalary();

void CalcTotalHours();

void Display();

void CalcNetPay()

if( IsMarried() == false )

NetPay = GrossPay - (GrossPay * 30 / 100);

else

NetPay = GrossPay;

private:

void CalcGrossPay();

bool inline IsMarried() const;

string FirstName;

string LastName;

double TotalHours;

double HourlySalary;

double WeeklySalary;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (20 of 24)11/20/2006 3:57:12 PM


C++ Tutorial - Introcution to Classes

double GrossPay;

double NetPay;

};

Objects and Their Implementations


An object is made of the material that compose it and the actual structure of the object, which defines how the object is built
and used. This means, a class is be 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 is 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 object’s 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 ShoeBox header file would look like:

#include <iostream>

#include <string>

using namespace std;

class ShoeBox

public:

double CalcVolume() const

return Length * Width * Height;

void Area(const double Side1, const double Side2, char SideName[32]);

float CalcShoeSize() const

return Length - 0.35;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (21 of 24)11/20/2006 3:57:12 PM


C++ Tutorial - Introcution to Classes

void Display();

private:

double Length;

double Width;

double Height;

string Color;

};

Class Source Code


This file used to implement the object is called a source file. It is used to define what the object is supposed to do. It contains
all or some of the methods and their implementations.

To create the source file, from the New property page of the New Items dialog box, click the Cpp File icon and click OK. By
default, the (first) file is called File1.cpp. To change that name, you must save the project and replace the name of the file
with the desired name.

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 is 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 ShoeBox would look like:

#include "File1.h"

void ShoeBox::Area(const Double S1, const Double S2, PChar N)

cout << "\nThe area of the " << N << " side is = " << S1 * S2;

void ShoeBox::Display()

// Initializing the dimensions

Length = 14.32;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (22 of 24)11/20/2006 3:57:12 PM


C++ Tutorial - Introcution to Classes

Width = 8.36;

Height = 6.54;

Color = "Brown Carpet";

// Display the characteristics of the shoe box

cout << "Characteristics of this shoe box";

cout << "\nDimensions(L*H*W) = "

<< Length << " * " << Height << " * "

<< Width; Area(Length, Height, "front");

Area(Length, Width, "top");

Area(Height, Width, "left");

cout << "\n\tVolume = " << CalcVolume()

<< "\n\tColor = " << Color

<< "\n\tSize = " << CalcShoeSize();

The main() function of our shoe box project is reduced to simply calling the appropriate ShoeBox method member:

#include <iostream.h>

#include "ShoeBox.h"

int main()

ShoeBox Sala;

Sala.Display();

return 0;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (23 of 24)11/20/2006 3:57:12 PM


C++ Tutorial - Introcution to Classes

Previous Copyright © 2000-2003 FunctionX, Inc. Next

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson12.htm (24 of 24)11/20/2006 3:57:12 PM


Lesson 11 - Constructing Objects

Constructing Objects
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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (1 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

double TBrick::Volume() const

return Length * Height * Width;

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

void TBrick::Properties() const

cout << "Red Brick Properties";

cout << setiosflags(ios::fixed) << setprecision(2);

cout << "\nLength = " << Length;

cout << "\nHeight = " << Height;

cout << "\nThickness = " << Width;

cout << "\nVolume = " << Volume() << "\n";

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

int main(int argc, char* argv[])

TBrick RedBrick;

RedBrick.Initializer(124.45, 56.25, 32.55);

RedBrick.Properties();

return 0;

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

This would produce:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (2 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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(int argc, char* argv[])

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (3 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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 = 8.95

Height = 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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (4 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

#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 Display();

private:

string FirstName;

string LastName;

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,

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (5 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

int DOB, int MOB, int YOB)

FirstName = fn;

LastName = ln;

DayOfBirth = DOB;

MonthOfBirth = MOB;

YearOfBirth = YOB;

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

void TStudent::Display()

// 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"

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

void Exit()

cout << "\n\nPress any key to continue...";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (6 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

int main(int argc, char* argv[])

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (7 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

TBook(); // Constructor

};

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

TBook::TBook()

cout << "I see a book...\n";

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

int main(int argc, char* argv[])

TBook B;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (8 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

#ifndef BricksH

#define BricksH

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

struct TBrick

public:

TBrick(); // Empty Constructor

void setDimensions(double l, double h, double t);

void Initializer(double l, double h, double w);

double CementVolume();

void ShowProperties();

private:

double Length;

double Height;

double Thickness;

};

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

#endif

Brick Unit - Source File: Bricks.cpp

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

#include <iostream>

#include <iomanip>

using namespace std;

#include "Bricks.h"

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (9 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

TBrick::TBrick()

//TODO: Add your source code here

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

void TBrick::setDimensions(double l, double h, double t)

Length = l;

Height = h;

Thickness = t;

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

double TBrick::CementVolume()

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;

return ValidVolume;

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

void TBrick::ShowProperties()

cout << "Foundation Brick Properties";

cout << setiosflags(ios::fixed) << setprecision(2);

cout << "\nLength = " << Length; cout

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (10 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

<< "\nHeight = " << Height;

cout << "\nThickness = " << Thickness;

cout << "\nCement Volume = " << CementVolume() << "\n";

}//---------------------------------------------------------------------------

Main File: Main.cpp

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

#include <iostream>

using namespace std;

#include "Bricks.h"

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

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

int main(int argc, char* argv[])

TBrick Foundation;

Foundation.setDimensions(4.24, 3.55, 3.45);

Foundation.ShowProperties();

return 0;

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

This program would produce:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (11 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

Foundation Brick Properties

Length = 4.24

Height = 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 Display();

private:

string FirstName;

string LastName;

int DayOfBirth;

int MonthOfBirth;

int YearOfBirth;

};

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (12 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

#endif

2. Change the Students.cpp file accordingly:

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

#include <iostream>

using namespace std;

#include "Students.h"

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

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

TStudent::STudent()

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

void TStudent::InitialValues(string fn, string ln,

int DOB, int MOB, int YOB)

FirstName = fn;

LastName = ln;

DayOfBirth = DOB;

MonthOfBirth = MOB;

YearOfBirth = YOB;

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

void TStudent::Display()

// Display the characteristics of the student

cout << "Characteristics of this student";

cout << "\nFull Name: " << FirstName << " " << LastName;

cout << "\nDate of Birth: " << DayOfBirth

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (13 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

<< "/" << MonthOfBirth << "/" << YearOfBirth << "\n";

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

3. Press F9 to test the program.

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

public:

TBrick(); // Default Constructor

TBrick(double l, double h, double t);

double CementVolume();

void ShowProperties();

private:

double Length;

double Height;

double Thickness;

};

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (14 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

#endif

Listing - Brick Unit - Source File: Bricks.cpp

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

#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 TBrick::CementVolume()

double Enclosure = 0.50; // This includes both walls of the brick itself

double HoleLength = Length - 0.75; // Including both holes

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (15 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

double HoleThickness = Thickness - Enclosure;

double HoleVolume = HoleLength * HoleThickness * Height;

double TotalVolume = Length * Height * Thickness;

double ValidVolume = TotalVolume - HoleVolume;

return ValidVolume;

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

void TBrick::ShowProperties()

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

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

#include <iostream>

using namespace std;

#include "Bricks.h"

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

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

int main(int argc, char* argv[])

TBrick Solid(4.15, 3.35, 3.05);

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (16 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

Solid.ShowProperties();

return 0;

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

This would produce the following result:

Foundation Brick Properties

Length = 4.15

Height = 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

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

#ifndef BricksH

#define BricksH

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

struct TBrick

public:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (17 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

TBrick(); // Default Constructor

TBrick(double l, double h, double t);

void setLength(double l);

void setHeight(double h);

void setThickness(double t);

double CementVolume();

void ShowProperties();

private:

double Length;

double Height;

double Thickness;

};

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

#endif

Brick Unit - Source File: Brick.cpp

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

#include <iostream>

#include <iomanip>

using namespace std;

#include "Bricks.h"

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

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

TBrick::TBrick()

//TODO: Add your source code here

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (18 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

TBrick::TBrick(double l, double h, double t)

setLength(l);

setHeight(h);

setThickness(t);

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

void TBrick::setLength(double l)

Length = l;

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

void TBrick::setHeight(double h)

Height = h;

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

void TBrick::setThickness(double t)

Thickness = t;

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

double TBrick::CementVolume()

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (19 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

return ValidVolume;

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

void TBrick::ShowProperties()

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

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

#include <iostream>

using namespace std;

#include "Bricks.h"

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

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

int main(int argc, char* argv[])

TBrick Solid(4.15, 3.35, 3.05);

Solid.ShowProperties();

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (20 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

return 0;

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

This would produce:

Foundation Brick Properties

Length = 4.15

Height = 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 Display();

private:

string FirstName;

string LastName;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (21 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

int DayOfBirth;

int MonthOfBirth;

int YearOfBirth;

};

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

#endif

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 = fn;

LastName = ln;

DayOfBirth = DOB;

MonthOfBirth = MOB;

YearOfBirth = YOB;

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

void TStudent::Display()

// Display the characteristics of the student

cout << "Characteristics of this student";

cout << "\nFull Name: " << FirstName << " " << LastName;

cout << "\nDate of Birth: " << DayOfBirth

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (22 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

<< "/" << MonthOfBirth << "/" << YearOfBirth << "\n";

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

3. Finally, change the main():

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

#include <iostream>

using namespace std;

#include "Students.h"

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

void Exit()

cout << "\n\nPress any key to continue...";

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

int main(int argc, char* argv[])

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (23 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

void ShowProperties();

private:

double Length;

double Height;

double Thickness;

};

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

And implemented as

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

#include <iostream>

using namespace std;

#include "Bricks.h"

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

TBrick::TBrick()

//TODO: Add your source code here

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (24 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

double TBrick::CementVolume()

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 TBrick::ShowProperties()

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (25 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

#include <iostream>

using namespace std;

#include "Bricks.h"

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

int main(int argc, char* argv[])

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

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (26 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (27 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

double CementVolume();

void ShowProperties();

private:

double Length;

double Height;

double Thickness;

};

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

#endif

Brick Unit - Source File: Brick.cpp

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

#include <iostream>

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (28 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

double TBrick::CementVolume()

...

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

void TBrick::ShowProperties()

...

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

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

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

#include <iostream>

using namespace std;

#include "Bricks.h"

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

int main(int argc, char* argv[])

// Brick with default dimensions

TBrick Mather;

Mather.ShowProperties();

cout << endl;

// Brick with a supplied length

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (29 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (30 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

#ifndef BricksH

#define BricksH

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

class TBrick

public:

TBrick();

TBrick(double L);

TBrick(double L, double h, double t);

double CementVolume();

void ShowProperties();

private:

double Length;

double Height;

double Thickness;

};

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

#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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (31 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

#include <iostream>

using namespace std;

#include "Bricks.h"

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

int main(int argc, char* argv[])

// 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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (32 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (33 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

double CementVolume();

void ShowProperties();

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:

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

#include <iostream>

using namespace std;

#include "Bricks.h"

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

int main(int argc, char* argv[])

// The following (default) constructor is not available

TBrick GrayMatte;

GrayMatte.ShowProperties();

cout << endl;

// A Brick with set dimensions

TBrick Fantasma(3.25, 3.05, 3.25);

Fantasma.ShowProperties();

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (34 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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 getLength() const;

void setLength(const double l);

double getHeight() const;

void setHeight(const double h);

double getThickness() const;

void setThickness(const double t);

double CementVolume();

void ShowProperties();

private:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (35 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

double Length;

double Height;

double Thickness;

};

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

#endif

Brick Unit - Source File: Brick.cpp

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

#include <iostream>

#include <iomanip>

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)

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (36 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

Length = L;

Height = h;

Thickness = t;

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

double TBrick::getLength() const

return Length;

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

void TBrick::setLength(const double l)

Length = l;

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

double TBrick::getHeight() const

return Height;

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

void TBrick::setHeight(const double h)

Height = h;

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

double TBrick::getThickness() const

return Thickness;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (37 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

void TBrick::setThickness(const double t)

Thickness = t;

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

double TBrick::CementVolume()

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 TBrick::ShowProperties()

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (38 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

#include <iostream>

using namespace std;

#include "Bricks.h"

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

int main(int argc, char* argv[])

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (39 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

Foundation Brick Properties

Length = 6.25

Height = 5.85

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (40 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

private:

string FirstName;

string LastName;

int DayOfBirth;

int MonthOfBirth;

int YearOfBirth;

};

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

#endif

2. Implement the new constructor in the Student.cpp file as follows:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (41 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

_fastcall TStudent::TStudent()

FirstName = "Paul";

LastName = "Kamus";

DayOfBirth = 28;

MonthOfBirth = 5;

YearOfBirth = 1986;

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

3. To test both constructors, change the main() function as follows:

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

#include <iostream>

using namespace std;

#include "Students.h"

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

void Exit()

cout << "\n\nPress any key to continue...";

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

int main(int argc, char* argv[])

TStudent SampleStudent;

SampleStudent.Display();

cout << endl;

TStudent Complete("Alexander", "Biyidi", 30, 4, 1988);

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (42 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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>

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

class TStudent

public:

TStudent(); // Default Constructor

TStudent(string F, string L); // Name Initializer

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (43 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

private:

string FirstName;

string LastName;

int DayOfBirth;

int MonthOfBirth;

int YearOfBirth;

};

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

#endif

7. Implement the constructors in the Students.cpp file as follows:

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

using namespace std;

#include "Students.h"

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

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

_fastcall TStudent::TStudent()

FirstName = "John";

LastName = "Doe";

DayOfBirth = 1;

MonthOfBirth = 1;

YearOfBirth = 1990;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (44 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

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 TStudent::Display()

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (45 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

// 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"

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

void Exit()

cout << "\n\nPress any key to continue...";

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

int main(int argc, char* argv[])

TStudent DefaultStudent;

DefaultStudent.Display();

cout << endl;

TStudent WithNameOnly("Genevieve", "Souchon");

WithNameOnly.Display();

cout << endl;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (46 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (47 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

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

class TBrick

public:

TBrick(double L, double h, double t) { Length = L; Height = h; Thickness = t; }

double getLength() const;

void setLength(const double l);

double getHeight() const;

void setHeight(const double h);

double getThickness() const;

void setThickness(const double t);

double CementVolume();

void ShowProperties();

private:

double Length;

double Height;

double Thickness;

};

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (48 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

#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

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

#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 getLength() const;

void setLength(const double l);

double getHeight() const;

void setHeight(const double h);

double getThickness() const;

void setThickness(const double t);

double CementVolume();

void ShowProperties();

private:

double Length;

double Height;

double Thickness;

};

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (49 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

#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 TBrick::getLength() const

return Length;

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

void TBrick::setLength(const double l)

Length = l;

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

double TBrick::getHeight() const

return Height;

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

void TBrick::setHeight(const double h)

Height = h;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (50 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

double TBrick::getThickness() const

return Thickness;

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

void TBrick::setThickness(const double t)

Thickness = t;

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

double TBrick::CementVolume()

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 TBrick::ShowProperties()

cout << "Foundation Brick Properties";

cout << setiosflags(ios::fixed) << setprecision(2);

cout << "\nLength = " << Length;

cout << "\nHeight = " << Height;

cout << "\nThickness = " << Thickness;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (51 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

cout << "\nCement Volume = " << CementVolume() << "\n";

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

To test the program, we would implement the main() function as follows.

Main Unit - Source File: Main.cpp

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

#include <iostream>

using namespace std;

#include "Bricks.h"

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

int main(int argc, char* argv[])

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (52 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

#ifndef BricksH

#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 getLength() const;

void setLength(const double l);

double getHeight() const;

void setHeight(const double h);

double getThickness() const;

void setThickness(const double t);

double CementVolume();

void ShowProperties();

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (53 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

#include <iostream>

using namespace std;

#include "Bricks.h"

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

int main(int argc, char* argv[])

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

return 0;

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

This would produce the following result:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (54 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (55 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

TBrick(double L, double h, double t);

double getLength() const;

void setLength(const double l);

double getHeight() const;

void setHeight(const double h);

double getThickness() const;

void setThickness(const double t);

double CementVolume();

void ShowProperties();

private:

double Length;

double Height;

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)

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (56 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

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;

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 = fn;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (57 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

LastName = ln;

DayOfBirth = DOB;

MonthOfBirth = MOB;

YearOfBirth = YOB;

void Display();

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:

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

using namespace std;

#include "Students.h"

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

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

TStudent::TStudent(string FN, string LN)

FirstName = FN;

LastName = LN;

DayOfBirth = 1;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (58 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

MonthOfBirth = 1;

YearOfBirth = 1985;

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

TStudent::TStudent(int DOB, int MOB, int YOB)

FirstName = "William";

LastName = "Smith";

DayOfBirth = DOB;

MonthOfBirth = MOB;

YearOfBirth = YOB;

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

void TStudent::Display()

// 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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (59 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

#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(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 Display();

private:

string FirstName;

string LastName;

int DayOfBirth;

int MonthOfBirth;

int YearOfBirth;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (60 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

};

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

#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 Display();

private:

string FirstName;

string LastName;

int DayOfBirth;

int MonthOfBirth;

int YearOfBirth;

};

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

#endif

8. Change the Students.cpp file as follows:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (61 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

#include "Students.h"

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

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (62 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

void TStudent::Display()

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

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 Example


A value to a variable int a = 250;
The value of one variable to another NbrOfBoys = NbrOfGirls;
A value to an object’s member 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 take care of in the following main() function:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (63 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

#include <iostream>

using namespace std;

#include "Bricks.h"

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

int main(int argc, char* argv[])

// 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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (64 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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;

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

int main(int argc, char* argv[])

// Assigning a value to a variable using the = sign

int CheeseSteak = 2;

// Assigning a value using the parenthesis

int TunaSalad(4);

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (65 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

// 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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (66 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (67 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

TBrick(double L, double h, double t);

TBrick(const TBrick &Brk);

double getLength() const;

void setLength(const double l);

double getHeight() const;

void setHeight(const double h);

double getThickness() const;

void setThickness(const double t);

double CementVolume();

void ShowProperties();

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:

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

TBrick::TBrick(const TBrick& B)

Length = B.Length;

Height = B.Height;

Thickness = B.Thickness;

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

Here is an example that uses a copy constructor to copy one order into another:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (68 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

#include <iostream>

#include <iomanip>

using namespace std;

#include "Bricks.h"

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

int main(int argc, char* argv[])

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (69 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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() function as follows:

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

#include <iostream>

using namespace std;

#include "Students.h"

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

int main(int argc, char* argv[])

TStudent Student1("Pamela", "Wattson", 2, 18, 1988);

Student1.Display();

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (70 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

private:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (71 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

string FirstName;

string LastName;

int DayOfBirth;

int MonthOfBirth;

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (72 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

#ifndef BricksH

#define BricksH

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

class TBrick

public:

TBrick();

TBrick(double L, double h, double t);

TBrick(const TBrick &Brk);

~TBrick();

double getLength() const;

void setLength(const double l);

double getHeight() const;

void setHeight(const double h);

double getThickness() const;

void setThickness(const double t);

double CementVolume();

void ShowProperties();

private:

double Length;

double Height;

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (73 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

#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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (74 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

#include <iostream>

using namespace std;

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

class TBook

public:

TBook(); // Constructor

~TBook(); // Destructor

void Message() { cout << "\tI read the book\n"; }

};

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

TBook::TBook()

cout << "I see a book... Using the Constructor\n";

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

TBook::~TBook()

cout << "I close the book! Using the Destructor\n";

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

int main(int argc, char* argv[])

cout << "I am at the library\n";

TBook A;

cout << "\nI didn't like that book. I will try another\n\n";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (75 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (76 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

#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 Display();

private:

string FirstName;

string LastName;

int DayOfBirth;

int MonthOfBirth;

int YearOfBirth;

};

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

#endif

7. Implement the destructor in the Students.cpp file as follows:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (77 of 78)11/20/2006 3:57:21 PM


Lesson 11 - Constructing Objects

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

TStudent::~TStudent()

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

8. Test the program and return to your programming environment.

Previous Copyright © 2000-2003 FunctionX, Inc. Next

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson13.htm (78 of 78)11/20/2006 3:57:21 PM


Lesson 14 - Combining Objects

Combining Objects
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. Let’s 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

TCone(double r, double h); // Constructor to initialize

TCone(const TCone& c); // Copy constructor

~TCone(); // Destructor

void setRadius(const double r) { Radius = r; }

void setHeight(const double h) { Height = h; }

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (1 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

double getRadius() const { return Radius; }

double getHeight() const { return Height; }

double Base() const;

double TextureArea() const;

double Volume() const;

private:

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (2 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

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

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (3 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

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

return 0;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (4 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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: " << Tone.getRadius();

cout << "\nHeight: " << Tone.getHeight();

cout << "\nBase Area: " << Tone.Base();

cout << "\nTexture Area: " << Tone.TextureArea() << "\n";

return 0;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (5 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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[])

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: " << Camper.getRadius();

cout << "\nHeight: " << Camper.getHeight();

cout << "\nBase Area: " << Camper.Base();

cout << "\nTexture Area: " << Camper.TextureArea() << "\n";

return 0;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (6 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

Which would produce, for example:

Specify the dimensions of the tent

Radius: 7.24

Radius: 4.88

A tent with user-defined dimensions

Radius: 7.24

Height: 4.88

Base Area: 164.675

Texture Area: 198.59

The Starting Object

1. Start your programming environment if you didn’t 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

#define StudentsH

#include <iostream>

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

class TStudent

public:

TStudent();

TStudent(string fn, string ln, int d, int m, int y);

~TStudent();

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (7 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (8 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (9 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

<< "/" << 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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (10 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (11 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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. That’s why set methods are very valuable. To provide
set methods, change the header file of the TStudents object as follows:

Header File: Students.h

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (12 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

#ifndef StudentsH

#define StudentsH

#include <iostream>

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

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;

};

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (13 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

#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";

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (14 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

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.

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (15 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (16 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

Source File: Main.cpp

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

#include <iostream>

#include <iomanip>

using namespace std;

#include "Cone.h"

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

void ShowTent(TCone c)

cout << "\nCharacteristics of this tent";

cout << setiosflags(ios::fixed) << setprecision(2);

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;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (17 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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: 10.24

Height: 6.84

Base Area: 329.42

Texture Area: 396.15

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (18 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (19 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

Enter the student's information

First Name: Joan

Last Name: Lucent

Day of Birth: 18

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"

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (20 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

void Exit()

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

void ShowTent(TCone c)

cout << "\nCharacteristics of this tent";

cout << setiosflags(ios::fixed) << setprecision(2);

cout << "\nRadius: " << c.getRadius();

cout << "\nHeight: " << c.getHeight();

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (21 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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: 8.44

Height: 5.26

Base Area: 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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (22 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (23 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

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: 18.12

Height: 10.26

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (24 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

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

TStudent Register()

string FN, LN;

int Day, Month, Year;

TStudent s;

cout << "Enter the student's information\n";

cout << "First Name: "; cin >> FN;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (25 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (26 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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
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: " << c.getRadius();

cout << "\nHeight: " << c.getHeight();

cout << "\nBase Area: " << c.Base();

cout << "\nTexture Area: " << c.TextureArea() << "\n";

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (27 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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[])

TCone Tent;

ObtainDimensions(Tent);

ShowTent(Tent);

Exit();

return 0;

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

Here is example of running the program:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (28 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

Specify the dimensions of the tent

Radius: 5.12

Radius: 3.84

Characteristics of this tent

Radius: 5.12

Height: 3.84

Base Area: 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);

Register(Stud);

ShowStudent(Stud);

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (29 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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: "

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (30 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (31 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

private:

int Qty;

double UnitPrice;

};

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

TForSale::TForSale(int Quantity, double Price)

: Qty(Quantity), UnitPrice(Price)

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

double TotalPrice(TForSale i)

return i.Qty * i.UnitPrice;

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

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (32 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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;

};

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

#endif

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (33 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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)

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (34 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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:

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (35 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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"

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

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

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)

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (36 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (37 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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, 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: " << T.getBase() << endl;

cout << "Height: " << T.getHeight() << endl;

cout << "Perimeter: " << Perimeter(T) << endl;

cout << "Area: " << Area(T) << endl;

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

int main(int argc, char* argv[])

TTriangle Trng(12.55, 10.85);

Characteristics(Trng);

return 0;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (38 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

Here is an example of running the program:

Characteristics of the triangle

Base: 12.55

Height: 10.85

Perimeter: 39.99

Area: 68.08

When a friend function does not modify the value(s) of the object’s member variable(s) it 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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (39 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (40 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

#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 object’s 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);

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (41 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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.

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (42 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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:

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

#include <iostream>

#include <iomanip>

using namespace std;

#include "Triangle.h"

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (43 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

void Characteristics(const TTriangle& T)

cout << "\nCharacteristics of the triangle\n";

cout << setiosflags(ios::fixed) << setprecision(2);

cout << "Base: " << T.getBase() << endl;

cout << "Height: " << T.getHeight() << endl;

cout << "Perimeter: " << Perimeter(T) << endl;

cout << "Area: " << Area(T) << endl;

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

int main(int argc, char* argv[])

TTriangle Slice;

double b, h;

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (44 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

#ifndef StudentsH

#define StudentsH

#include <iostream>

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

class TStudent

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (45 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

int YearOfBirth;

};

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

#endif

2. Change the source file as follows:

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

using namespace std;

#include "Students.h"

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

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

TStudent 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: "; 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;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (46 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

DayOfBirth(Stud.DayOfBirth),

MonthOfBirth(Stud.MonthOfBirth),

YearOfBirth(Stud.YearOfBirth)

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (47 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (48 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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:

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (49 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

. . .

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;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (50 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (51 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (52 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (53 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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"

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

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)

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (54 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (55 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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, 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: " << LabelType.getColor();

cout << "\nAdhesive: " << LabelType.getAdhesive();

return 0;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (56 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

The program would produce:

A label with default characteristics

Dimensions: 3.25 * 2.55

Area: 8.2875

Model No.: 0

Model Name: None

Color: White

Adhesive: Not Specified

The program can also provide the values of each object, using their methods:

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(4.55, 2.25);

TLabelType LabelType(25442, "Mandarin", "One Touch", "Non-Removable");

cout << "An example label";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (57 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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: " << LabelType.getColor();

cout << "\nAdhesive: " << 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: Mandarin

Adhesive: Non-Removable

Combining Objects

1. To process a semi-complete registration for a student, consisting of a complete address, change the Students.h file as
follows:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (58 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (59 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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;

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"

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (60 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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: "; 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;

cout << "Address: ";

cin >> ws;

getline(cin, S.Address);

cout << "City: ";

getline(cin, S.City);

cout << "State: ";

getline(cin, S.State);

cout << "ZIPCode: ";

getline(cin, S.ZIPCode);

cout << "Country: ";

getline(cin, S.Country);

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

TStudent::TStudent()

FirstName = "John";

LastName = "Doe";

DayOfBirth = 1;

MonthOfBirth = 1;

YearOfBirth = 1990;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (61 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

Address = "123 Main Street";

City = "Old Town";

State = "This State";

ZIPCode = "01234-0001";

Country = "USA";

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

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

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (62 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (63 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (64 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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"

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

TGrades::TGrades()

: English(0.00),

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (65 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (66 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

//TODO: Add your source code here

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

double TGrades::CalcTotal()

double Total = English + SecondLng + History +

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: "; cin >> Student.History;

cout << "Geography: "; cin >> Student.Geography;

cout << "Chemistry: "; cin >> Student.Chemistry;

cout << "Sociology: "; cin >> Student.Sociology;

cout << "Mathematics: "; cin >> Student.Math;

cout << "Comp Sciences: "; cin >> Student.CompSc;

cout << "Morale: "; cin >> Student.Morale;

cout << "Sports: "; cin >> Student.Sports;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (67 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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

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

cout << "Student Registration\n";

Registration(Stud);

cout << endl;

cout << "Student Grades\n";

GetGrades(Grade);

system("cls");

StudentInfo(Stud);

ShowGrades(Grade);

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (68 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

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: " << s.getAddress()

<< "\n " << s.getCity() << ", " << s.getState()

<< ", " << s.getZIPCode()

<< "\n " << s.getCountry();

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

void ShowGrades(TGrades d)

cout << setiosflags(ios::fixed) << setprecision(2);

cout << "\n------------------------------------";

cout << "\n\tEnglish: " << d.getEnglish();

cout << "\n\tLanguage 2: " << d.getSecondLng();

cout << "\n\tHistory: " << d.getHistory();

cout << "\n\tGeography: " << d.getGeography();

cout << "\n\tChemistry: " << d.getChemistry();

cout << "\n\tSociology: " << d.getSociology();

cout << "\n\tMathematics: " << d.getMath();

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (69 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

cout << "\n\tComp Sciences: " << d.getCompSc();

cout << "\n\tMorale: " << d.getMorale();

cout << "\n\tSports: " << 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: Paul

Last Name: Delamarre

Day of Birth: 28

Month of Birth: 2

Year of Birth: 1986

Address: 8402 Norton Hwy #D12

City: Silver Spring

State: MD

ZIPCode: 20910-4412

Country: USA

Student Grades

English: 12.50

Second Language: 10.25

History: 14.50

Geography: 13.00

Chemistry: 15.00

Sociology: 12.50

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (70 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

Mathematics: 16.50

Comp Sciences: 17.25

Morale: 14.00

Sports: 15.50

Second Screen:

====================================

Student Report

------------------------------------

Student Registration

Full Name: Paul Delamarre

Date of Birth: 28/2/1986

Address: 8402 Norton Hwy #D12

Silver Spring, MD, 20910-4412

USA

------------------------------------

English: 12.50

Language 2: 10.25

History: 14.50

Geography: 13.00

Chemistry: 15.00

Sociology: 12.50

Mathematics: 16.50

Comp Sciences: 17.25

Morale: 14.00

Sports: 15.50

------------------------------------

Total: 141.00 Mean: 14.10

====================================

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (71 of 72)11/20/2006 3:57:44 PM


Lesson 14 - Combining Objects

8. Return to your programming environment

Previous Copyright © 2000-2003 FunctionX, Inc. Next

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson14.htm (72 of 72)11/20/2006 3:57:44 PM


Lesson 15 - Composition and Inheritance

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 if…else 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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (1 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

string getPrintType() const;

private:

unsigned int ModelNumber;

string Name;

string Color;

int PrintType;

};

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

#endif

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)

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (2 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

return Name;

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

string TLabelType::getColor() const

return Color;

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

string TLabelType::getPrintType() const

string PrintingType;

switch( PrintType )

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (3 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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;

cout << "A label with default characteristics";

cout << "\nModel Number: " << Label.getModelNumber();

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (4 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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 semi-complete 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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (5 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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 enumrator are exemplified in the new version of the TLabelType object as follows:

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

#ifndef LabelTypeH

#define LabelTypeH

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (6 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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 shold not neglect warnings.

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)

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (7 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (8 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

#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: " << Label.getName();

cout << "\nMain Color: " << 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: " << Label.getName();

cout << "\nMain Color: " << Label.getColor();

cout << "\nPrinting Type: " << Label.getPrintType();

cout << "\nAdhesive Type: " << Label.getAdhesive();

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (9 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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:

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (10 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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:

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

using namespace std;

#include "Students.h"

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

TStudents::TStudents()

: FirstName("John"),

LastName("Doe"),

DayOfBirth(5),

MonthOfBirth(10),

YearOfBirth(1988),

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (11 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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)

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (12 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (13 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (14 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

~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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (15 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (16 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

#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 of the member object B using the member
access operator (.). As a result, you would be using two period operators. After declaring the main object, the first operator is used to
access the members of the main object, usually the constructor. The second operator, if used, allows accessing a member of the
dependent object. Here is an example:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (17 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

#include <iomanip>

using namespace std;

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

#include "LabelType.h"

#include "LabelDimensions.h"

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

int main(int argc, char* argv[])

TLabelType LblType;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (18 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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;

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

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (19 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (20 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

double getSports() const { return Sports; }

double CalcTotal() const;

double CalcMean() const;

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (21 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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() const

double Total = English + SecondLng + History +

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (22 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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;

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (23 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (24 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

G.setHistory(Hist);

G.setGeography(Geog);

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (25 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (26 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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:

View
the
illustration

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

public:

TLabels();

TLabels(const TLabels& L);

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (27 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

~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()

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (28 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

void TLabels::ProcessALabel()

// Get the dimensions of the label

// Get the label's characteristics

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

void TLabels::ShowReceipt()

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (29 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

#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:

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

#ifndef LabelTypeH

#define LabelTypeH

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

#include <iostream>

using namespace std;

#include "LabelDimensions.h"

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

enum TPrintCategory { pcInkjet = 1, pcLaser, pcMultiPurpose, pcUnspecified };

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (30 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (31 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

~TLabels();

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)

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (32 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

TLabels::~TLabels()

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

void TLabels::GetLabelDimensions(TDimensions& Rect)

cout << "Enter dimensions of the label\n";

cout << "Length: ";

cin >> Rect.Length;

cout << "Height: ";

cin >> Rect.Height;

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (33 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

Label.Adhesive = adNone;

cout << "Printing Type"

<< "\n1 - Inkjet"

<< "\n2 - Laser"

<< "\n3 - Multi-Purpose"

<< "\n4 - Unspecified"

<< "\nYour Choice: ";

cin >> Label.PrintType;

Label.Name = LabelName;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (34 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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=================================";

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (35 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (36 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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:

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (37 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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 follows:

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

#ifndef GradeReportH

#define GradeReportH

#include <iostream>

#include "Students.h"

#include "Grades.h"

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

struct TGradeInfo

int Level;

string MajorCode;

string MajorName;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (38 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

};

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

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

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

TStudents TGradeReport::Registration()

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (39 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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,

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (40 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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;

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: "

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (41 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

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[])

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (42 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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


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, let’s build the base first.The header file of TRectangle creates an object with its
dimensions as follows:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (43 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

#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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (44 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

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)

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

TRectangle::~TRectangle()

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

void TRectangle::setLength(const double L)

Length = L;

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

void TRectangle::setHeight(const double H)

Height = H;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (45 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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;

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

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.

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (46 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

#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";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (47 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

RectProperties(Rect3);

return 0;

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

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;

};

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (48 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

#endif

5. Implement the source file as follows:

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

using namespace std;

#include "Person.h"

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

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

TPerson::TPerson(string fn, string ln)

: FirstName(fn), LastName(ln)

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (49 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

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

int main(int argc, char* argv[])

TPerson P("John", "Landis");

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (50 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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.

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (51 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (52 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (53 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

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

cout << "\nArea: " << B.TotalArea();

cout << "\nVolume: " << B.Volume();

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (54 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (55 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

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

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 parent’s protected members. This allows us the change the source file of the TBox object as follows:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (56 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

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;

else

Width = W;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (57 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (58 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

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

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,

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (59 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (60 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (61 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

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[])

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (62 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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;

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

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)

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (63 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

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

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

string TStudent::getGender() const

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (64 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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[])

TStudent P;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (65 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (66 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

#ifndef AddressH

#define AddressH

#include <iostream>

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

class TAddress

public:

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (67 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

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

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (68 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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"

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

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

TStaff::TStaff()

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (69 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (70 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

switch(EmploymentStatus)

case 'f':

case 'F':

EStatus = "Full-Time";

break;

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (71 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

MStatus = "Single";

break;

case 2:

MStatus = "Married";

break;

case 3:

MStatus = "Widow";

break;

case 4:

MStatus = "Divorcé";

break;

default:

MStatus = "Not Specified";

return MStatus;

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (72 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

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

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (73 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

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

#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é"

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (74 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

<< "\nStatus: "; cin >> MStatus;

Employee.setFirstName(FirstName);

Employee.setLastName(LastName);

Employee.setAddress(Address);

Employee.setCity(City);

Employee.setState(State);

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (75 of 76)11/20/2006 3:57:56 PM


Lesson 15 - Composition and Inheritance

system("cls");

cout << "Personal Information";

ShowInfo(Empl);

return 0;

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

10. Test the program and return to your programming environment.

Previous Copyright © 2000-2003 FunctionX, Inc. Next

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson15.htm (76 of 76)11/20/2006 3:57:56 PM


Lesson 16 - Polymorphism and Abstraction

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (1 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

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

#include <iomanip>

using namespace std;

#include "Circle.h"

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

const double PI = 3.14159;

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

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (2 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

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:

};

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (3 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

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

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (4 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

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

#ifndef CylinderH

#define CylinderH

#include "Circle.h"

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

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (5 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

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

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

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

double TCylinder::Area() const

double Base = TCircle::Area();

double Lateral = LateralArea();

return (2 * Base) + Lateral;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (6 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

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

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[])

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (7 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

TCircle e(12.55);

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[])

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (8 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

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;

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

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 protégé) 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"

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (9 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

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 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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (10 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

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

#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 Bcb.
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);

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (11 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

~TCircle();

void setRadius(const double r) { Radius = r; }

double getRadius() const { return Radius; }

virtual double Area() const;

virtual void ShowCharacteristics() const;

protected:

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (12 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (13 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

};

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

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
4. On the Status Bar, click the Polygon.h tab and create a regular class as follows:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (14 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

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

#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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (15 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

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

#include <iostream>

using namespace std;

#include "Polygon.h"

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

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

namespace Shapes

TPolygon::TPolygon(int s, char *n, double r)

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (16 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

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

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

void TPolygon::setRadius(const double r)

//Avoid a negative radius. It wouldn't make sense

if( r < 0 )

Radius = 0.00;

else

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (17 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (18 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

cout << "Shape Characteristics";

cout << setiosflags(ios::fixed) << setprecision(2);

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


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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (19 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

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;

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)

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (20 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

. . .

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

. . .

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

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (21 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (22 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (23 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

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

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (24 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

Tri->setRadius(15.55);

Tri->ShapeCharacteristics();

return 0;

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

17. Test the program and return to Bcb.


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

virtual double Apothem();

virtual double Perimeter();

virtual void ShapeCharacteristics();

protected:

private:

};

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (25 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

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

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (26 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

double TPolySquare::Side()

return Radius * sqrt(2);

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (27 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

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

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

virtual double Apothem();

virtual double Perimeter();

virtual void ShapeCharacteristics();

protected:

private:

};

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

#endif

23. Implement the THexagon class as follows:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (28 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

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

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (29 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

double THexagon::Apothem()

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (30 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

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

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

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;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (31 of 32)11/20/2006 3:58:11 PM


Lesson 16 - Polymorphism and Abstraction

25. Test the program and return to Bcb

Previous Copyright © 2000-2003 FunctionX, Inc. Next

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson16.htm (32 of 32)11/20/2006 3:58:11 PM


Lesson 17 - Operator Overloading

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (1 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

#include <iostream>

#include <iomanip>

using namespace std;

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

struct TSquare

public:

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: " << Carre.Area();

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

int main(int argc, char* argv[])

TSquare CupHolder;

CupHolder.setSide(35.55);

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (2 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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;

};

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

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (3 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (4 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (5 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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: " << Carre.Area();

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

int main(int argc, char* argv[])

TSquare Holder, Loop;

Holder.setSide(35.55);

Properties(Holder);

cout << "\n\n";

Loop.setSide(18.04);

TSquare Base(Loop);

Properties(Base);

cout << "\n\n";

TSquare Sink = Holder;

Properties(Sink);

return 0;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (6 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (7 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

In reality (that is, on a different compiler, such as MSVC), this would produce:

Values of variables

A: 2.122e-314

B: 2.53936e-314

Press any key to continue…

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (8 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

Values of variables

A: 266.52

B: 2.53936e-314

Press any key to continue…

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;

cout << "\nB: " << B;

A = B;

cout << "\n\nValues of variables";

cout << "\nA: " << A;

cout << "\nB: " << B;

return 0;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (9 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

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

Press any key to continue…

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (10 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

B = A;

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

Press any key to continue…

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (11 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

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

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (12 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (13 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (14 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

#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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (15 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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) {}

. . .

TRectangle& operator=(const TRectangle& Rect);

private:

double Length;

double Height;

};

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (16 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

#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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (17 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

int main(int argc, char* argv[])

TRectangle Rect(42.88, 36.14);

TRectangle Recto(16.52, 22.65);

cout << Recto + Rect;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (18 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

public:

TRectangle(double L = 0.00, double H = 0.00)

: Length(L), Height(H) {}

. . .

TRectangle& operator=(const TRectangle& Rect);

private:

double Length;

double Height;

};

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (19 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (20 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (21 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

double Height;

};

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

#endif

The implementation of these functions also follows the same syntax applied to the addition operator:

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

using namespace std;

#include "Rectangle.h"

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

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

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (22 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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;

if( y.Length == 0 ) // Avoid a zero denominator

R.Length = 0;

else

R.Length = x.Length / y.Length;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (23 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (24 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

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

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (25 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

#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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (26 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

TRectangle& TRectangle::operator+(const double Number)

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (27 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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;

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

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (28 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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;

A += D;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (29 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (30 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (31 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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[])

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (32 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (33 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

};

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

#endif

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (34 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

#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:

. . .

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (35 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

};

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

#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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (36 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (37 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (38 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

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;

Height = Rect.Height;

return *this;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (39 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (40 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

R.Length = x.Length * y.Length;

R.Height = x.Height * y.Height;

return R;

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

TRectangle operator/(const TRectangle& x, const TRectangle& y)

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (41 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

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)

Length -= R.Length;

Height -= R.Height;

return *this;

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

TRectangle& TRectangle::operator*=(const TRectangle& R)

Length *= R.Length;

Height *= R.Height;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (42 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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"

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

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

void Properties(const TRectangle& Rect)

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (43 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

cout << setiosflags(ios::fixed) << setprecision(2);

cout << "\nLength: " << Rect.getLength();

cout << "\nHeight: " << Rect.getHeight();

cout << "\nPerimeter: " << Rect.Perimeter();

cout << "\nArea: " << Rect.Area();

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

int main(int argc, char* argv[])

TRectangle Rect, Recto;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (44 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

return 0;

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

This would produce:

Using the += Operator

Length: 59.40

Height: 58.79

Perimeter: 236.38

Area: 3492.13

Using the -= Operator

Length: 26.36

Height: 13.49

Perimeter: 79.70

Area: 355.60

Using the *= Operator

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (45 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

Length: 708.38

Height: 818.57

Perimeter: 3053.90

Area: 579857.36

Using the /= Operator

Length: 2.60

Height: 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;

double D = 560.25;

if( A >= D )

cout << "A is greater than D";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (46 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (47 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

#include <iostream>

using namespace std;

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

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

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (48 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (49 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

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

return 0;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (50 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (51 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

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)

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (52 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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;

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

. . .

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

This allows you to perform any comparison on variables declared from the class. Here is an example:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (53 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

#include <iostream>

using namespace std;

#include "Rectangle.h"

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

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

void Properties(const TRectangle& Rect)

cout << "\nLength: " << Rect.getLength();

cout << "\nHeight: " << Rect.getHeight();

cout << "\nPerimeter: " << Rect.Perimeter();

cout << "\nArea: " << Rect.Area();

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

int main(int argc, char* argv[])

TRectangle Rect(42.88, 36.14), Recto(16.52, 22.65);

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.

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (54 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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[])

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (55 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

#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

#define RectangleH

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

class TRectangle

. . .

public:

. . .

void operator<<(ostream& Ostr, const TRectangle& Rect);

private:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (56 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

. . .

};

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

#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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (57 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

void operator<<(ostream& Ostr, const TRectangle& R)

Ostr << "(" << R.Length << ", " << R.Height << ")";

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

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (58 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

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

return Ostr;

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

The Input Operator


The input operator “>>” is used to request a value or some values from the user. Here is an example:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (59 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (60 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

friend istream& operator>>(istream& Istr, TRectangle& Rect);

. . .

public:

. . .

private:

. . .

};

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

#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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (61 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

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

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

return 0;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (62 of 63)11/20/2006 3:58:20 PM


Lesson 17 - Operator Overloading

Previous Copyright © 2000-2003 FunctionX, Inc. Next

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson17.htm (63 of 63)11/20/2006 3:58:20 PM


Lesson 18: Exceptions and Classes

Exceptions and Classes


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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (1 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

double TotalOrder;

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

cout << " - Customer Order Processing -\n";

try {

cout << "Number of\n";

cout << "Shirts: ";

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (2 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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;

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

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (3 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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

#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: ";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (4 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (5 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (6 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (7 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (8 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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

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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (9 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (10 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

break;

case '/':

if( y == 0 )

throw 0;

R = x / y;

break;

return R;

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (11 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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;

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

7. Test it and return to your programming environment.

Introduction to Exceptions in Classes

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (12 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and 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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (13 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

double TotalPricePants;

double TotalPriceMisc;

double TotalOrder;

};

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

TCleaningOrder::TCleaningOrder()

: NumberOfShirts(0), NumberOfPants(0), NumberMisc(0)

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

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (14 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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

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

void TCleaningOrder::DisplayReceipt()

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (15 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (16 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

return 0;

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

Practical Learning: Class' Methods and their Exceptions


1. As an example, change the program as follows:

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

#include <iostream>

using namespace std;

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (17 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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;

Operator = c;

Operand2 = Denom;

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

double TCalculator::CalcResult() const

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (18 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (19 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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

cout << "To proceed, enter\n";

Calc.RequestOperands();

Calc.DisplayResult();

cout << "\nPress any key to continue...";

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (20 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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() 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:

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (21 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (22 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

double TotalPricePants;

double TotalPriceMisc;

double TotalOrder;

};

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

TCleaningOrder::TCleaningOrder()

: NumberOfShirts(0), NumberOfPants(0), NumberOfMisc(0)

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

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)

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (23 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (24 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (25 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

<< "\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: 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).

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (26 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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;

double Operand2;

char Operator;

};

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

TCalculator::TCalculator()

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (27 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (28 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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)

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] != '.') )

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (29 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

throw Oper2;

Operand2 = atof(Oper2);

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

double TCalculator::getOperand2() const

return Operand2;

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

void TCalculator::setOperator(const char Symbol)

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (30 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (31 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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;

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (32 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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;

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

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (33 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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;

setOperand1(Number1);

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (34 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (35 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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

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

double TCalculator::getOperand2() const

return Operand2;

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

void TCalculator::setOperator(const char Symbol) throw(const char)

if(Symbol != '+' && Symbol != '-' &&

Symbol != '*' && Symbol != '/')

throw Symbol;

Operator = Symbol;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (36 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (37 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (38 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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

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

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (39 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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

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

double TCalculator::getOperand2() const

return Operand2;

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

void TCalculator::setOperator(const char Symbol) throw(const char)

if(Symbol != '+' && Symbol != '-' &&

Symbol != '*' && Symbol != '/')

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (40 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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 '-':

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (41 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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

Result = CalcResult();

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (42 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

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

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-2003 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (43 of 44)11/20/2006 3:58:26 PM


Lesson 18: Exceptions and Classes

http://192.168.16.242/cts/tutorials/functionx/cpp/Lesson18.htm (44 of 44)11/20/2006 3:58:26 PM


C++ Keywords: bool

FunctionX
- C++ Keywords: else
Practical
Learning
The Boolean data type is used to declare a variable whose value will be set as true (1) or false (0). To declare such a
Logo
value, you use the bool keyword. The variable can then be initialized with the starting value. A Boolean constant is
used to check the state of a variable, an expression, or a function, as true or false.

You can declare a Boolean 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(int argc, char* argv[])

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;

http://192.168.16.242/cts/tutorials/functionx/cpp/keywords\bool.htm (1 of 2)11/20/2006 3:59:35 PM


C++ Keywords: bool

return 0;

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

Copyright © 2002-2003 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/keywords\bool.htm (2 of 2)11/20/2006 3:59:35 PM


C++ Keywords - break

FunctionX
- C++ Keywords: break
Practical
Learning
The break keyword is used to stop a loop for any reason you consider fit. The break statement can be used in a
Logo
while condition to stop an ongoing action. The following program tries to count alphabetical letters from d to n, but
a break makes it stop when it encounters k:

#include <iostream>

using namespace std;

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

int main(int argc, char* argv[])

char Letter = 'd';

while( Letter <= 'n' )

cout << "Letter " << Letter << endl;

if( Letter == 'k' )

break;

Letter++;

return 0;

The break statement can be used in a do…while loop in the same way.

In a for statement, the break can stop the counting when a particular condition becomes true. For example, the
following program is supposed to count from 0 to 12, but the programmer wants it to stop as soon as it detects the

http://192.168.16.242/cts/tutorials/functionx/cpp/keywords\break.htm (1 of 4)11/20/2006 3:59:42 PM


C++ Keywords - break

number 5:

#include <iostream>

using namespace std;

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

int main(int argc, char* argv[])

for(int Count = 0; Count <= 12; ++Count)

cout << "Count " << Count << endl;

if( Count == 5 )

break;

return 0;

The break statement is typically used to handle the cases in a switch statement where you usually may want the
program to ignore invalid cases.

Consider a program used 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 working version of that program:

#include <iostream>

using namespace std;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/keywords\break.htm (2 of 4)11/20/2006 3:59:42 PM


C++ Keywords - break

int main(int argc, char* argv[])

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;

case 3:

cout << "\nYou typed 3.";

break;

default:

cout << endl << Number << " is out of the requested range.";

return 0;

http://192.168.16.242/cts/tutorials/functionx/cpp/keywords\break.htm (3 of 4)11/20/2006 3:59:42 PM


C++ Keywords - break

Copyright © 2001-2003 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/keywords\break.htm (4 of 4)11/20/2006 3:59:42 PM


C++ Keywords - else

FunctionX
- C++ Keywords: else
Practical
Learning
Logo
Overview

The else keyword is used to complete the if condition. It provides an alternative to a primary condition. The else
keyword is never used by itself. It is used in the following context:
if(Condition)

Statement1;

else

Statement2;

The first if statement is used to evaluate a condition. If the condition is true, then it gets executed and the test ends.
If the first condition is false, an else statement is used. When used by itself after an if condition, the else statement
is used to process what ever would be negative but fits in the if condition. In this case, the else statement is used to
embrace all false possibilities of the previous if condition. Here is an example:

#include <iostream>

using namespace std;

void main()

unsigned int Miles;

const double LessThan100 = 0.25;

const double MoreThan100 = 0.15;

double PriceLessThan100, PriceMoreThan100, TotalPrice;

cout << "Enter the number of miles: ";

cin >> Miles;

if(Miles <= 100)

PriceLessThan100 = Miles * LessThan100;

http://192.168.16.242/cts/tutorials/functionx/cpp/keywords\else.htm (1 of 2)11/20/2006 3:59:51 PM


C++ Keywords - else

PriceMoreThan100 = 0;

else

PriceLessThan100 = 100 * LessThan100;

PriceMoreThan100 = (Miles - 100) * MoreThan100;

TotalPrice = PriceLessThan100 + PriceMoreThan100;

cout << "\nTotal Price = $" << TotalPrice << "\n\n";

Here is an example of running the program:

Enter the number of miles: 75

Total Price = $18.75

Press any key to continue


The else keyword can be preceded by an if statement. In this case, the else statement is made to process one or
more particular negations of the previous conditions.

C++ Tutorial Copyright © 2001-2003 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/keywords\else.htm (2 of 2)11/20/2006 3:59:51 PM


C++ Keywords: for

C++ Keywords: for

The for statement is typically used to count a number of items. It is made of three sections. 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 formula of the for statement is:

for(Start; End; Frequency) Statement;

The Start expression is a variable assigned the starting value. An example would be Count = 0;

The End expression is an expression that 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.

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 formula of the for statement:

#include <iostream>

using namespace std;

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

int main(int argc, char* argv[])

for(signed Count = 0; Count <= 12; Count++)

cout << "Number " << Count << endl;

return 0;

The program would produce:

Number 0

Number 1

Number 2

http://192.168.16.242/cts/tutorials/functionx/cpp/keywords\for.htm (1 of 4)11/20/2006 3:59:59 PM


C++ Keywords: for

Number 3

Number 4

Number 5

Number 6

Number 7

Number 8

Number 9

Number 10

Number 11

Number 12

Press any key to continue...

Although we mentioned that a for statement is made of three sections, C++ allows you to create a for loop without
specifying either one, two, or none of the three sections. To do this, you must still use the semi-colon delimiters of
the sections but you don't have to include anything in the section. Based on this, you can create an empty for loop
that appears as

for(;;) Statement;

Here is an example:

#include <iostream>

using namespace std;

int main()

char StudentName[10];

char Answer[10];

http://192.168.16.242/cts/tutorials/functionx/cpp/keywords\for.htm (2 of 4)11/20/2006 3:59:59 PM


C++ Keywords: for

for(;;)

cout << "Enter Student Name: ";

cin >> StudentName;

cout << "New Student: " << StudentName << endl;

cout << "Do you have another students(y/n)? ";

cin >> Answer;

Answer[0] = toupper(Answer[0]);

if( Answer[0] != 'Y' )

break;

cout << endl;

return 0;

Here is an example of running the program:

Enter Student Name: James

New Student: James

Do you have another students(y/n)? y

Enter Student Name: Paul

http://192.168.16.242/cts/tutorials/functionx/cpp/keywords\for.htm (3 of 4)11/20/2006 3:59:59 PM


C++ Keywords: for

New Student: Paul

Do you have another students(y/n)? y

Enter Student Name: Bertrand

New Student: Bertrand

Do you have another students(y/n)? n

Press any key to continue

Copyright © 2002-2003 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/keywords\for.htm (4 of 4)11/20/2006 3:59:59 PM


C++ References - inline

FunctionX
- Inline Functions
Practical
Learning
Logo
Overview
When one function calls another, the calling function must send a request to the called function that would process
it and return the necessary value, if any. C++ allows you to implement a function so that, when it is called, a copy
of the whole function is placed where the function is being called. This means that the calling functions doesn't
send a request to the function that performs the assignment: the function itself is accessed where it is needed.

To create an inline function, type the inline keyword to its left when declaring the function. Here is an example:

#include <iostream>

using namespace std;

inline double Sum(const double * Numbers, const int Count)

double s = 0;

for(int i = 0; i < Count; i++)

s += Numbers[i];

return s;

int main()

double Nbr[] = { 15.66, 18, 25, 128.62, 12.06, 22.18 };

double Total = Sum(Nbr, 6);

http://192.168.16.242/cts/tutorials/functionx/cpp/keywords\inline.htm (1 of 3)11/20/2006 4:00:07 PM


C++ References - inline

cout << "Sum = " << Total << endl;

return 0;

If you first declare a function that would be defined somewhere else, when implementing the function, you can type
or omit the inline keyword:

#include <iostream>

using namespace std;

inline double Sum(const double * Numbers, const int Count);

int main()

double Nbr[] = { 15.66, 18, 25, 128.62, 12.06, 22.18 };

double Total = Sum(Nbr, 6);

cout << "Sum = " << Total << endl;

return 0;

inline double Sum(const double * Numbers, const int Count)

http://192.168.16.242/cts/tutorials/functionx/cpp/keywords\inline.htm (2 of 3)11/20/2006 4:00:07 PM


C++ References - inline

double s = 0;

for(int i = 0; i < Count; i++)

s += Numbers[i];

return s;

Copyright © 2003 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/keywords\inline.htm (3 of 3)11/20/2006 4:00:07 PM


C++ References - static

FunctionX
- Static Variables
Practical
Learning
Logo
Overview
The static keyword allows a variable to maintain its value among different function calls. If the value of a static
variable changes when the variable has been accessed, the variable keeps the new value. If the same variable gets
accessed again, it would be holding its most recent value. This is possible because, when the static variable is
declared, the compiler uses a separate memory area to store it. By doing this, when the value of the static variable
gets changed, it is updated in the memory it is occupying. And because this memory is separate, the compiler can
monitor its values even when its function exits.

To declare a variable as static, type the static keyword to its left. Here is an example:

void Example()

static int Mine;

You can declare as many static variables as you judge necessary, and you can use the same name for different static
variables in different functions:

void Example()

static int Mine;

void Function()

static int Mine;

http://192.168.16.242/cts/tutorials/functionx/cpp/keywords\static.htm (1 of 2)11/20/2006 4:00:21 PM


C++ References - static

Copyright © 2003 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/keywords\static.htm (2 of 2)11/20/2006 4:00:21 PM


C++ Examples

FunctionX
- Anonymous Objects
Practical
Learning
An anonymous class is one that doesn't have a name. In the following example, both structures inside the
Logo
TRectangle union are anonymous classes:
//---------------------------------------------------------------------------

#include <iostream>

#include <conio>

using namespace std;

#pragma hdrstop

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

#pragma argsused

// This rectangle can be identified by EITHER its location OR its dimensions

union TRectangle

struct // Location

int x1;

int y1;

int x2;

int y2;

};

struct // Dimensions

double Length;

double Height;

};

};

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

http://192.168.16.242/cts/tutorials/functionx/cpp/references\anonymousclass.htm (1 of 4)11/20/2006 4:00:55 PM


C++ Examples

int main(int argc, char* argv[])

TRectangle Recto;

char Choice;

cout << "You want to identify your rectangle by "

<< "its location or its dimensions?";

cout << "\n1 - Location";

cout << "\n2 - Dimension";

cout << "\nEnter your choice: ";

cin >> Choice;

if( Choice == '1' )

cout << "\nEnter the location of the rectangle on a "

<< "Cartesian coordinate system\n";

cout << "First point\n";

cout << "X coordinate: "; cin >> Recto.x1;

cout << "Y coordinate: "; cin >> Recto.y1;

cout << "Second point\n";

cout << "X coordinate: "; cin >> Recto.x2;

cout << "Y coordinate: "; cin >> Recto.y2;

cout << "\nThe rectangle spans from A("

<< Recto.x1 << ", " << Recto.y1 << ") to B("

<< Recto.x2 << ", " << Recto.y2 << ").\n";

else if( Choice == '2' )

http://192.168.16.242/cts/tutorials/functionx/cpp/references\anonymousclass.htm (2 of 4)11/20/2006 4:00:55 PM


C++ Examples

cout << "Enter the dimensions of the rectangle\n";

cout << "Length: "; cin >> Recto.Length;

cout << "Height: "; cin >> Recto.Height;

cout << "\nDimensions of the rectangle";

cout << "\nLength: " << Recto.Length;

cout << "\nHeight: " << Recto.Height << endl;

else

cout << "\nInvalid Choice";

return 0;

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

Here is an example of running the program:

You want to identify your rectangle by its location or its dimensions?

1 - Location

2 - Dimension

Enter your choice: 1

Enter the location of the rectangle on a Cartesian coordinate system

First point

X coordinate: -4

Y coordinate: 2

Second point

X coordinate: 5

Y coordinate: 1

http://192.168.16.242/cts/tutorials/functionx/cpp/references\anonymousclass.htm (3 of 4)11/20/2006 4:00:55 PM


C++ Examples

The rectangle spans from A(-4, 2) to B(5, 1).

Press any key to continue...

C++ Tutorial Copyright © 2001 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/references\anonymousclass.htm (4 of 4)11/20/2006 4:00:55 PM


C++ References - Comments

FunctionX
- Comments
Practical
Learning
Logo
A comment is a line or paragraph of text in a file such that that line or paragraph is not considered when the compiler (or the
parser) is decoding the code of the file.

The C/C++ language accepts two types of comments:

● To write a comment on one line, type two forward slashes // and type the comment. Anything on the right side of
both forward slashes would not be read by the compiler (actually the parser)
Here are examples:

// This are various examples of a one-line comment

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

// Include the necessary libraries for a basic program

#include <iostream>

#include <conio>

using namespace std;

#pragma hdrstop

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

#pragma argsused

// Every C++ function must have a main() function

int main(int argc, char* argv[])

// Display a simple sentence to the user

cout << "Welcome to the wonderful world of C++ Programming!!!\n";

// Prompt the user to close the program

cout << "\nPress any key to continue...";

http://192.168.16.242/cts/tutorials/functionx/cpp/references\comments.htm (1 of 3)11/20/2006 4:01:44 PM


C++ References - Comments

// Let the user press a key to stop the program

getch();

// The program went alright, so return 0

return 0;

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

● To write a comment, you can start it with a forward slash / followed by an asterisk *, write the comment. To end the
comment, type an asterisk * followed by a forward slash /. This type of comment can be spread on various lines
Here are examples:

/* This are various examples of a forward slash asterisk comment */

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

/* Include the necessary libraries for a basic program

Because this program is intended for Borland C++ Builder,

you should include the conio.h library that has the getch() function. */

#include <iostream>

#include <conio>

using namespace std;

#pragma hdrstop

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

#pragma argsused

/* Every C++ function must have a main() function

The current C++ Standard recommends that the main() function return

a value. In this case, it will return an integer.

http://192.168.16.242/cts/tutorials/functionx/cpp/references\comments.htm (2 of 3)11/20/2006 4:01:44 PM


C++ References - Comments

The main() function is the entry point of the program.

This version of main() takes two arguments. Sometimes the arguments

are not used at all, as is the case in this program.

*/

int main(int argc, char* argv[])

// Display a simple sentence to the user

cout << "Welcome to the wonderful world of C++ Programming!!!\n";

/* Because we are using Borland C++, we will explicitly prompt the user

to press an key in order to stop the program.

Upon pressing a key, we will call the getch() function to receive it */

cout << "\nPress any key to continue...";

getch();

// The program went alright, so return 0

return 0;

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

Copyright © 2003 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/references\comments.htm (3 of 3)11/20/2006 4:01:44 PM


C++ Examples

FunctionX
- Class Inheritance
Practical
Learning
Inheritance is the ability for one class to receive its primary functionality from another class, also called its base
Logo
class.

This example uses a class called Circle so that, given a radius, the program would calculate and display the
diameter, the circumference, and the area.

Another class called Sphere is derived from the Circle class. This class can supply its own radius, display the same
pieces of information as the Circle. Additionally, the Sphere class should calculate and display the volume.

This exercise uses different header and source files. It uses the following five files: circle.h, circle.cpp, sphere.h,
sphere.cpp and exo.cpp.

Header File: circle.h

#ifndef CIRCLE_H

#define CIRCLE_H

struct Circle

public:

Circle();

void setRadius(double r);

double getRadius();

double Diameter();

double Circumference();

double Area();

void Display();

protected:

double Radius;

private:

};

http://192.168.16.242/cts/tutorials/functionx/cpp/references\inheritance1.htm (1 of 6)11/20/2006 4:02:09 PM


C++ Examples

#endif

Source File: circle.cpp

#include <iostream.h>

#include "circle.h"

const double PI = 3.14159;

Circle::Circle()

Radius = 0;

void Circle::setRadius(double r)

Radius = r <= 0 ? 1 : r;

double Circle::getRadius()

return Radius;

double Circle::Diameter()

return Radius * 2;

http://192.168.16.242/cts/tutorials/functionx/cpp/references\inheritance1.htm (2 of 6)11/20/2006 4:02:09 PM


C++ Examples

double Circle::Circumference()

return Diameter() * PI;

double Circle::Area()

return Radius * Radius * PI;

void Circle::Display()

cout << "\nCircle Properties";

cout << "\nRadius = " << getRadius();

cout << "\nDiameter = " << Diameter();

cout << "\nCircumference = " << Circumference();

cout << "\nArea = " << Area() << "\n";

Header File: sphere.h

#ifndef SPHERE_H

#define SPHERE_H

struct Sphere : public Circle

public:

double Volume();

void Show();

http://192.168.16.242/cts/tutorials/functionx/cpp/references\inheritance1.htm (3 of 6)11/20/2006 4:02:09 PM


C++ Examples

private:

};

#endif

Source File: sphere.cpp

#include <iostream.h>

#include "circle.h"

#include "sphere.h"

const double PI = 3.14159;

double Sphere::Volume()

return Radius * Radius * Radius * PI * 4 / 3;

void Sphere::Show()

cout << "\nCircle Properties";

cout << "\nRadius = " << getRadius();

cout << "\nDiameter = " << Diameter();

cout << "\nCircumference = " << Circumference();

cout << "\nArea = " << Area();

cout << "\nVolume = " << Volume() << "\n\n";

Main File: exo.cpp

#include "circle.h"

http://192.168.16.242/cts/tutorials/functionx/cpp/references\inheritance1.htm (4 of 6)11/20/2006 4:02:09 PM


C++ Examples

#include "sphere.h"

void main()

Circle circle; // Displaying a circle using the default value of the


radius

circle.Display();

Circle circ; // A circle with a value supplied for the radius

circ.setRadius(12.50);

circ.Display();

Sphere sphere; // A sphere that has its own radius, using the functions

sphere.setRadius(8.95); // of the base class

sphere.Show();

Here is an example of running the program:

Circle Properties

Radius = 0

Diameter = 0

Circumference = 0

Area = 0

Circle Properties

Radius = 12.5

Diameter = 25

Circumference = 78.5397

http://192.168.16.242/cts/tutorials/functionx/cpp/references\inheritance1.htm (5 of 6)11/20/2006 4:02:09 PM


C++ Examples

Area = 490.873

Circle Properties

Radius = 8.95

Diameter = 17.9

Circumference = 56.2345

Area = 251.649

Volume = 3003.01

Press any key to continue

C++ Tutorial Copyright © 2001 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/references\inheritance1.htm (6 of 6)11/20/2006 4:02:09 PM


C++ Examples - A Simple C++ Program

FunctionX
- A Simple C++ Program
Practical
Learning
This is the simples C++ program. It displays a sentence on the console or the terminal
Logo
Version 1

#include <iostream>

int main()

std::cout << "Welcome to the wonderful world of C++!!!\n";

return 0;

Version 2

#include <iostream>

using namespace std;

int main()

cout << "Welcome to the wonderful world of C++!!!\n";

return 0;

Here is an example of running the program:

Welcome to the wonderful world of C++!!!

Press any key to continue

C++ Tutorial Copyright © 2001 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\simple.htm11/20/2006 4:02:49 PM
C++ Examples

FunctionX
- C++ Examples: If-Else
Practical
Learning
Logo
Exercise The LeVan Car Rental company charges $0.25/mile if the total mileage does not exceed 100. If the total mileage is
over 100, the company charges $0.25/mile for the first 100 miles, then it charges $0.15/mile for any additional
mileage over 100.

Write a program so that if the clerk enters the number of miles, the program would display the total price owed.

Source File

#include <iostream.h>

void main()

unsigned int Miles;

const double LessThan100 = 0.25;

const double MoreThan100 = 0.15;

double PriceLessThan100, PriceMoreThan100, TotalPrice;

cout << "Enter the number of miles: ";

cin >> Miles;

if(Miles <= 100)

PriceLessThan100 = Miles * LessThan100;

PriceMoreThan100 = 0;

else

PriceLessThan100 = 100 * LessThan100;

PriceMoreThan100 = (Miles - 100) * MoreThan100;

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\ifelse1.htm (1 of 2)11/20/2006 4:03:04 PM


C++ Examples

TotalPrice = PriceLessThan100 + PriceMoreThan100;

cout << "\nTotal Price = $" << TotalPrice << "\n\n";

Here is an example of running the program:

Enter the number of miles: 75

Total Price = $18.75

Press any key to continue

C++ Tutorial Copyright © 2001 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\ifelse1.htm (2 of 2)11/20/2006 4:03:04 PM


C++ Examples - Passing an Argument By Value

FunctionX
- Passing Arguments by Value
Practical
Learning
This illustrates the technique used to pass arguments by value to a function.
Logo
#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);

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\argbyvalue.htm (1 of 3)11/20/2006 4:03:14 PM


C++ Examples - Passing an Argument By Value

FullName = GetName();

Hours = GetHours(FullName);

cout << "\nEmployee's Name: " << FullName;

cout << "\nWeekly Hours: " << Hours << " hours\n\n";

return 0;

double GetHours(string FullName)

double Mon, Tue, Wed, Thu, Fri, TotalHours;

cout << endl << FullName << "'s Weekly Hours\n";

cout << "Monday: ";

cin >> Mon;

cout << "Tuesday: ";

cin >> Tue;

cout << "Wednesday: ";

cin >> Wed;

cout << "Thursday: ";

cin >> Thu;

cout << "Friday: ";

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\argbyvalue.htm (2 of 3)11/20/2006 4:03:14 PM


C++ Examples - Passing an Argument By Value

cin >> Fri;

TotalHours = Mon + Tue + Wed + Thu + Fri;

return TotalHours;

Copyright © 2003 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\argbyvalue.htm (3 of 3)11/20/2006 4:03:14 PM


C++ Examples

FunctionX
- Passing Arguments
Practical
Learning
This example demonstrates different techniques of passing arguments: by value, by reference, and as pointers
Logo
Source File

#include <iostream.h>

void main()

int Boys = 3, Girls = 5;

void PassByValue(int males, int females);

void Reference(int &m, int &f);

void Pointers(int *u, int *v);

cout << "At startup, within main()";

cout << "\n\tBoys = " << Boys;

cout << "\n\tGirls = " << Girls;

cout << "\nPassing arguments by value = Copy";

PassByValue(Boys, Girls);

cout << "\nAfter calling PassByValue(), within main()";

cout << "\n\tBoys = " << Boys;

cout << "\n\tGirls = " << Girls;

cout << "\nPassing arguments by reference";

Reference(Boys, Girls);

cout << "\nAfter calling Reference(), within main()";

cout << "\n\tBoys = " << Boys;

cout << "\n\tGirls = " << Girls;

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\passargs.htm (1 of 4)11/20/2006 4:06:42 PM


C++ Examples

cout << "\nPassing arguments pointers";

Pointers(&Boys, &Girls);

cout << "\nAfter calling Pointers(), within main()";

cout << "\n\tBoys = " << Boys;

cout << "\n\tGirls = " << Girls;

cout << "\n";

void PassByValue(int b, int g)

b += 3, g += 4;

cout << "\nWithin PassByValue(), now";

cout << "\n\tBoys = " << b;

cout << "\n\tGirls = " << g;

void Reference(int &b, int &g)

b = b + 8, g = g + 5;

cout << "\nWithin Reference(), now";

cout << "\n\tBoys = " << b;

cout << "\n\tGirls = " << g;

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\passargs.htm (2 of 4)11/20/2006 4:06:42 PM


C++ Examples

void Pointers(int *b, int *g)

*b = 44, *g = 52;

cout << "\nWithin Pointers(), now";

cout << "\n\tBoys = " << *b;

cout << "\n\tGirls = " << *g;

This would produce:

At startup, within main()

Boys = 3

Girls = 5

Passing arguments by value = Copy

Within PassByValue(), now

Boys = 6

Girls = 9

After calling PassByValue(), within main()

Boys = 3

Girls = 5

Passing arguments by reference

Within Reference(), now

Boys = 11

Girls = 10

After calling Reference(), within main()

Boys = 11

Girls = 10

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\passargs.htm (3 of 4)11/20/2006 4:06:42 PM


C++ Examples

Passing arguments pointers

Within Pointers(), now

Boys = 44

Girls = 52

After calling Pointers(), within main()

Boys = 44

Girls = 52

Press any key to continue

C++ Tutorial Copyright © 2001 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\passargs.htm (4 of 4)11/20/2006 4:06:42 PM


C++ Examples - A Simple Class

FunctionX
- A Simple Class
Practical
Learning
Logo
Exercise Write a simple class called Cube. The object should calculate the total area and the volume based on the side
measurement. If the program supplies a side equal or lower than 0, reset the side to 1. Create an empty constructor
and an empty destructor.

Implement the object in different files.

Header File: cube.h

#ifndef CUBE_H

#define CUBE_H

class Cube

public:

Cube();

~Cube();

void setSide(double s);

double getSide();

double Area();

double Volume();

void Properties();

private:

double Side;

};

#endif

Source File cube.cpp

#include <iostream.h>

#include "cube.h"

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\simpleclass.htm (1 of 4)11/20/2006 4:07:00 PM


C++ Examples - A Simple Class

Cube::Cube()

Cube::~Cube()

void Cube::setSide(double s)

Side = s <= 0 ? 1 : s;

double Cube::getSide()

return Side;

double Cube::Area()

return 6 * Side * Side;

double Cube::Volume()

return Side * Side * Side;

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\simpleclass.htm (2 of 4)11/20/2006 4:07:00 PM


C++ Examples - A Simple Class

void Cube::Properties()

cout << "Characteristics of this cube";

cout << "\nSide = " << getSide();

cout << "\nArea = " << Area();

cout << "\nVolume = " << Volume() << "\n\n";

Main File: Exo.cpp

#include "cube.h"

void main()

Cube cube;

cube.setSide(-12.55);

cube.Properties();

Cube de;

de.setSide(28.15);

de.Properties();

Here is an example of the result:

Characteristics of this cube

Side = 1

Area = 6

Volume = 1

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\simpleclass.htm (3 of 4)11/20/2006 4:07:00 PM


C++ Examples - A Simple Class

Characteristics of this cube

Side = 28.15

Area = 4754.53

Volume = 22306.7

Press any key to continue

C++ Tutorial Copyright © 2001 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\simpleclass.htm (4 of 4)11/20/2006 4:07:00 PM


C++ Examples - An Object as an Argument

FunctionX
- Passing an Object as Argument
Practical
Learning
This example demonstrates how an object can be made an argument of a function.
Logo
#include <iostream.h>

struct Paper

double Width;

double Height;

};

void MagazineCover(Paper ppr)

cout << "Characteristics of this piece of paper";

cout << "\nWidth = " << ppr.Width;

cout << "\nHeight = " << ppr.Height;

cout << "\nPerimeter = " << 2 + (ppr.Width + ppr.Height);

cout << "\nArea = " << ppr.Width * ppr.Height;

int main(int argc, char* argv[])

double w, h;

cout << "Provide the dimensions of the magazine cover\n";

cout << "Width: ";

cin >> w;

cout << "Height: ";

cin >> h;

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\objasarg.htm (1 of 2)11/20/2006 4:07:56 PM


C++ Examples - An Object as an Argument

Paper Cover = {w, h};

MagazineCover(Cover);

getchar();

return 0;

C++ Tutorial Copyright © 2001 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\objasarg.htm (2 of 2)11/20/2006 4:07:56 PM


C++ Examples

FunctionX
- A Class as a Member Variable of Another Class
Practical
Learning
This is an example of one object (the shape class implements a rectangle) being a member variable of another
Logo
object (a brick).

Header File: shape.h

#ifndef _SHAPE_H

#define _SHAPE_H

class FRectangle

public:

FRectangle(double l = 0, double w = 0)

: Length(l), Width(w) {}

void setLength(double lgt);

void setWidth(double wdt);

double getLength() const;

double getWidth() const;

double Perimeter() const;

double Area() const;

void Properties();

private:

double Length;

double Width;

};

#endif // _SHAPE_H

Source File: shape.cpp

#include <iostream.h>

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\classmbr.htm (1 of 7)11/20/2006 4:08:22 PM


C++ Examples

#include "shape.h"

void FRectangle::setLength(double lgt)

Length = lgt;

void FRectangle::setWidth(double wdt)

Width = wdt;

double FRectangle::getLength() const

return Length;

double FRectangle::getWidth() const

return Width;

double FRectangle::Perimeter() const

return 2 * (Length + Width);

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\classmbr.htm (2 of 7)11/20/2006 4:08:22 PM


C++ Examples

double FRectangle::Area() const

return Length * Width;

void FRectangle::Properties()

cout << "\nRectangle characteristics";

cout << "\n\tLength = " << Length;

cout << "\n\tWidth = " << Width;

cout << "\n\tPerimeter = " << Perimeter();

cout << "\n\tArea = " << Area() << endl;

Header File: brick.h

#ifndef BRICK_H_

#define BRICK_H_

#include "shape.h"

class Brick

public:

Brick() {}

void setThickness(double Tck);

void setDimensions(double l, double w, double t);

void setColor(char* clr);

void setTexture(char* txr);

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\classmbr.htm (3 of 7)11/20/2006 4:08:22 PM


C++ Examples

char* getColor() const;

char* getTexture() const;

double Volume() const;

void Display();

private:

FRectangle shape;

char* Color;

char* Texture;

double Thickness;

};

#endif // BRICK_H_

Source File: brick.cpp

#include <iostream.h>

#include "brick.h"

void Brick::setThickness(double Tck)

Thickness = Tck;

void Brick::setColor(char* clr)

Color = clr;

void Brick::setTexture(char* txr)

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\classmbr.htm (4 of 7)11/20/2006 4:08:22 PM


C++ Examples

Texture = txr;

void Brick::setDimensions(double l, double w, double t)

shape.setLength(l);

shape.setWidth(w);

setThickness(t);

char* Brick::getColor() const

return Color;

char* Brick::getTexture() const

return Texture;

double Brick::Volume() const

return shape.getLength() * shape.getWidth() * Thickness;

void Brick::Display()

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\classmbr.htm (5 of 7)11/20/2006 4:08:22 PM


C++ Examples

cout << "\nBrick characteristics";

cout << "\n\tLength = " << shape.getLength();

cout << "\n\tWidth = " << shape.getWidth();

cout << "\n\tArea = " << shape.Area();

cout << "\n\tVolume = " << Volume();

cout << "\n\tColor = " << getColor();

cout << "\n\tTextture = " << getTexture();

cout << endl;

Main File: Exo.cpp

#include "shape.h"

#include "brick.h"

void main()

Brick brick;

brick.setDimensions(12.50, 8.75, 5.55);

brick.setColor("Bone White");

brick.setTexture("Early Breeze");

brick.Display();

Here is an example of running the program:

Brick characteristics

Length = 12.5

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\classmbr.htm (6 of 7)11/20/2006 4:08:22 PM


C++ Examples

Width = 8.75

Area = 109.375

Volume = 607.031

Color = Bone White

Textture = Early Breeze

Press any key to continue

C++ Tutorial Copyright © 2001 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\classmbr.htm (7 of 7)11/20/2006 4:08:22 PM


C++ Examples - Constructor Initializer

FunctionX
- Initializing the Members of a Class Using a Constructor
Practical
Learning
This example uses a class that contains a constructor used to initialize the object. The class is called ShoeBox.
Logo
When supplied with a length, a height, and a width, the object should calculate and display the total area of all sides
and the volume.
Header File: shoebox.h

#ifndef SHOEBOX_H

#define SHOEBOX_H

class ShoeBox

public:

ShoeBox(double l, double h, double w);

double getLength() const;

double getHeight() const;

double getWidth() const;

void Properties();

double Area() const;

double Volume() const;

private:

double Length;

double Height;

double Width;

};

#endif

Source File: shoebox.h

#include <iostream.h>

#include "box.h"

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\constrinit.htm (1 of 4)11/20/2006 4:08:40 PM


C++ Examples - Constructor Initializer

ShoeBox::ShoeBox(double l, double h, double w)

Length = l;

Height = h;

Width = w;

double ShoeBox::getLength() const

return Length;

double ShoeBox::getHeight() const

return Height;

double ShoeBox::getWidth() const

return Width;

double ShoeBox::Area() const

return 2 * ((Length * Height) + (Height + Width) + (Length * Width));

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\constrinit.htm (2 of 4)11/20/2006 4:08:40 PM


C++ Examples - Constructor Initializer

double ShoeBox::Volume() const

return Length * Height * Width;

void ShoeBox::Properties()

cout << "Properties of the shoe box";

cout << "\nLength = " << getLength();

cout << "\nHeight = " << getHeight();

cout << "\nWidth = " << getWidth();

cout << "\nArea = " << Area();

cout << "\nVolume = " << Volume() << "\n\n";

Header File: cube.h

#include "box.h"

void main()

ShoeBox Size6(8.65, 4.25, 4.15);

Size6.Properties();

Here is a result of running the program

Properties of the shoe box

Length = 8.65

Height = 4.25

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\constrinit.htm (3 of 4)11/20/2006 4:08:40 PM


C++ Examples - Constructor Initializer

Width = 4.15

Area = 162.12

Volume = 152.564

Press any key to continue

C++ Tutorial Copyright © 2001 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\constrinit.htm (4 of 4)11/20/2006 4:08:40 PM


C++ Examples

FunctionX
- Class Nesting
Practical
Learning
The C++ language allows you to create a class inside of another. This technique is referred to as nesting. At the
Logo
time of this writing, nesting a class B inside of a class A doesn't give any access privilege of class A' member
variables and methods to class B. Therefore, there is no major advantage to do it, only a matter of convenience and
probably personal preference and opinion. It is said that the next C++ standard will allow a nested class B to have
access to the private member variables and methods of the nesting class A.

(As you can see, this program was created in Borland C++ Builder. If you are using another compiler, remove the
#pragma and probably the conio lines)
//---------------------------------------------------------------------------

#include <iostream>

#include <conio>

using namespace std;

#pragma hdrstop

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

#pragma argsused

const int Maximum = 100;

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

class TListOfStudents

public:

class TStudent

private:

string FullName;

int Age;

char Gender;

public:

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\nestingclass.htm (1 of 6)11/20/2006 4:09:13 PM


C++ Examples

void setFullName(const string Name) { FullName = Name; }

string getFullName() const { return FullName; }

void setAge(const int a) { Age = a; }

int getAge() const { return Age; }

void setGender(const char g) { Gender = g; }

char getGender() const { return Gender; }

TStudent();

TStudent(string FName, int a, char g);

inline virtual ~TStudent() {}

};

private:

TStudent Item[Maximum];

public:

TListOfStudents() : Count(0){}

inline ~TListOfStudents() {}

void Add(const TStudent& d);

TStudent Retrieve(const int n);

int Count;

};

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

TListOfStudents::TStudent::TStudent()

FullName = "";

Age = 0.00;

Gender = 'M';

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

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\nestingclass.htm (2 of 6)11/20/2006 4:09:13 PM


C++ Examples

TListOfStudents::TStudent::TStudent(string FName, int a, char g)

FullName = FName;

Age = a;

Gender = g;

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

void __fastcall TListOfStudents::Add(const TStudent& d)

if( Count < Maximum )

Item[Count] = d;

Count++;

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

TListOfStudents::TStudent TListOfStudents::Retrieve(const int n)

return Item[n];

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

void __fastcall DisplayList(TListOfStudents &List);

void __fastcall CreateList(TListOfStudents &List);

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

int main(int argc, char* argv[])

TListOfStudents ListOfItems;

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\nestingclass.htm (3 of 6)11/20/2006 4:09:13 PM


C++ Examples

CreateList(ListOfItems);

DisplayList(ListOfItems);

return 0;

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

void CreateList(TListOfStudents &ListOfItems)

TListOfStudents::TStudent Pupil;

Pupil.setFullName("Harry Seamen");

Pupil.setAge(12);

Pupil.setGender('M');

ListOfItems.Add(Pupil);

Pupil.setFullName("Hermine Grand");

Pupil.setAge(14);

Pupil.setGender('F');

ListOfItems.Add(Pupil);

Pupil.setFullName("Ronald Hannah");

Pupil.setAge(18);

Pupil.setGender('M');

ListOfItems.Add(Pupil);

Pupil.setFullName("Johnny Hancock");

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\nestingclass.htm (4 of 6)11/20/2006 4:09:13 PM


C++ Examples

Pupil.setAge(16);

Pupil.setGender('M');

ListOfItems.Add(Pupil);

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

void DisplayList(TListOfStudents &ListOfItems)

cout << "Full Name\tAge\tGender";

string Gender[] = { "Male", "Female", "Unknown" };

for(int i = 0; i < ListOfItems.Count; i++)

cout << "\n" << ListOfItems.Retrieve(i).getFullName()

<< "\t" << ListOfItems.Retrieve(i).getAge()

<< "\t";

switch(ListOfItems.Retrieve(i).getGender())

case 'm':

case 'M':

cout << Gender[0];

break;

case 'f':

case 'F':

cout << Gender[1];

break;

default:

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\nestingclass.htm (5 of 6)11/20/2006 4:09:13 PM


C++ Examples

cout << Gender[2];

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

Here is an example of running the program:

Full Name Age Gender

Harry Seamen 12 Male

Hermine Grand 14 Female

Ronald Hannah 18 Male

Johnny Hancock 16 Male

Press any key to continue...

C++ Tutorial Copyright © 2001 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\nestingclass.htm (6 of 6)11/20/2006 4:09:13 PM


C++ Examples

FunctionX
- An Array of Objects
Practical
Learning
Logoexample show how to declare and use an array of an object
This

#include <iostream.h>

struct Paper

public:

void GetDimensions();

void Properties();

private:

double Perimeter() const;

double Area() const;

double Height;

double Width;

};

void Paper::GetDimensions()

cout << "Enter the dimensions of the label\n";

cout << "Height: ";

cin >> Height;

cout << "Width: ";

cin >> Width;

void Paper::Properties()

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\arrayofobjects.htm (1 of 4)11/20/2006 4:09:54 PM


C++ Examples

cout << "\n\tHeight = " << Height;

cout << "\n\tWidth = " << Width;

cout << "\n\tPerimeter = " << Perimeter();

cout << "\n\tArea = " << Area();

cout << "\n\n";

double Paper::Perimeter() const

return 2 + (Height * Width);

double Paper::Area() const

return Height * Width;

void main()

int Samples;

Paper Label[100];

cout << "How many sample labels do you want? ";

cin >> Samples;

for(int i = 0; i < Samples; ++i)

Label[i].GetDimensions();

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\arrayofobjects.htm (2 of 4)11/20/2006 4:09:54 PM


C++ Examples

cout << "\n\nHere are the characteristics of your labels\n";

for(int j = 0; j < Samples; ++j)

cout << "Label No. " << j;

Label[j].Properties();

Here is an example of running the program:

How many sample labels do you want? 2

Enter the dimensions of the label

Height: 3.25

Width: 3.25

Enter the dimensions of the label

Height: 2.15

Width: 4.55

Here are the characteristics of your labels

Label No. 0

Height = 3.25

Width = 3.25

Perimeter = 12.5625

Area = 10.5625

Label No. 1

Height = 2.15

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\arrayofobjects.htm (3 of 4)11/20/2006 4:09:54 PM


C++ Examples

Width = 4.55

Perimeter = 11.7825

Area = 9.7825

Press any key to continue

C++ Tutorial Copyright © 2001 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\arrayofobjects.htm (4 of 4)11/20/2006 4:09:54 PM


C++ Examples

FunctionX
- String Entering Example
Practical
Learning
This example shows how to perform data entry on strings. The strings are simple array of characters and they are
Logo
declared as member variables of a class. The class provides accessory methods for each member variable.

Header File: Person.h

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

#ifndef PersonH

#define PersonH

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

class TPerson

private:

char* FirstName;

char* LastName;

char* Address;

char* City;

char* State;

long ZIPCode;

public:

void setFirstName(const char *FN);

char* getFirstName() const { return FirstName; }

void setLastName(const char *LN);

char* getLastName() const { return LastName; }

char* FullName() const;

void setAddress(const char *Adr);

char* getAddress() const { return Address; }

void setCity(const char *CT);

char* getCity() const { return City; }

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\person.htm (1 of 9)11/20/2006 4:10:35 PM


C++ Examples

void setState(const char *St);

char* getState() const { return State; }

void setZIPCode(const long ZIP);

long getZIPCode() const { return ZIPCode; }

TPerson();

TPerson(char *FName, char *LName, char *Adr,

char *Ct, char *St, long ZIP);

TPerson(const TPerson &Pers);

TPerson(char * FName, char * LName);

virtual ~TPerson();

};

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

#endif

Source File: Person.cpp

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

#include <iostream>

using namespace std;

#pragma hdrstop

#include "Person.h"

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

#pragma package(smart_init)

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

char *__fastcall TPerson::FullName() const

char *FName = new char[40];

strcpy(FName, FirstName);

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\person.htm (2 of 9)11/20/2006 4:10:35 PM


C++ Examples

strcat(FName, " ");

strcat(FName, LastName);

return FName;

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

__fastcall TPerson::TPerson()

: ZIPCode(0)

//TODO: Add your source code here

FirstName = new char[20];

strcpy(FirstName, "John");

LastName = new char[20];

strcpy(LastName, "Doe");

Address = new char[40];

strcpy(Address, "123 Main Street Apt A");

City = new char[32];

strcpy(City, "Great City");

State = new char[30];

strcpy(State, "Our State");

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

__fastcall TPerson::TPerson(char * FName, char * LName)

: ZIPCode(0)

//TODO: Add your source code here

FirstName = new char[strlen(FName) + 1];

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\person.htm (3 of 9)11/20/2006 4:10:35 PM


C++ Examples

strcpy(FirstName, FName);

LastName = new char[strlen(LName) + 1];

strcpy(LastName, LName);

Address = new char[40];

strcpy(Address, "123 Main Street Apt A");

City = new char[32];

strcpy(City, "Great City");

State = new char[30];

strcpy(State, "Our State");

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

__fastcall TPerson::TPerson(char *FName, char *LName, char *Adr,

char *Ct, char *St, long ZIP)

: ZIPCode(ZIP)

//TODO: Add your source code here

FirstName = new char[strlen(FName) + 1];

strcpy(FirstName, FName);

LastName = new char[strlen(LName) + 1];

strcpy(LastName, LName);

Address = new char[40];

strcpy(Address, Adr);

City = new char[32];

strcpy(City, Ct);

State = new char[30];

strcpy(State, St);

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

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\person.htm (4 of 9)11/20/2006 4:10:35 PM


C++ Examples

__fastcall TPerson::TPerson(const TPerson &Pers)

: ZIPCode(Pers.ZIPCode)

//TODO: Add your source code here

FirstName = new char[strlen(Pers.FirstName) + 1];

strcpy(FirstName, Pers.FirstName);

LastName = new char[strlen(Pers.LastName) + 1];

strcpy(LastName, Pers.LastName);

Address = new char[strlen(Pers.Address) + 1];

strcpy(Address, Pers.Address);

City = new char[strlen(Pers.City) + 1];

strcpy(City, Pers.City);

State = new char[strlen(Pers.State) + 1];

strcpy(State, Pers.State);

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

void __fastcall TPerson::setFirstName(const char *FN)

strcpy(FirstName, FN);

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

void __fastcall TPerson::setLastName(const char *LN)

strcpy(LastName, LN);

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

void __fastcall TPerson::setAddress(const char *Adr)

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\person.htm (5 of 9)11/20/2006 4:10:35 PM


C++ Examples

strcpy(Address, Adr);

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

void __fastcall TPerson::setCity(const char *CT)

strcpy(City, CT);

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

void __fastcall TPerson::setState(const char *St)

strcpy(State, St);

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

void __fastcall TPerson::setZIPCode(const long ZIP)

ZIPCode = ZIP;

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

__fastcall TPerson::~TPerson()

//TODO: Add your source code here

delete [] FirstName;

delete [] LastName;

delete [] Address;

delete [] City;

delete [] State;

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\person.htm (6 of 9)11/20/2006 4:10:35 PM


C++ Examples

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

Main File: Main.cpp

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

#include <iostream>

using namespace std;

#pragma hdrstop

#include "Person.h"

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

#pragma argsused

TPerson ProcessRegistration();

void DisplayInformation(const TPerson&);

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

int main(int argc, char* argv[])

TPerson Employee = ProcessRegistration();

DisplayInformation(Employee);

return 0;

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

TPerson ProcessRegistration()

char FName[12], LName[12];

char Addr[40], CT[32], St[30];

long ZC;

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\person.htm (7 of 9)11/20/2006 4:10:35 PM


C++ Examples

cout << "Enter personal information\n";

cout << "First Name: "; cin >> FName;

cout << "Last Name: "; cin >> LName;

cout << "Address: "; cin >> ws;

cin.getline(Addr, 40);

cout << "City: ";

cin.getline(CT, 32);

cout << "State: ";

cin.getline(St, 30);

cout << "Zip Code: "; cin >> ZC;

TPerson Pers(FName, LName, Addr, CT, St, ZC);

return Pers;

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

void DisplayInformation(const TPerson& Pers)

cout << "\nEmployee Identification";

cout << "\nFull Name: " << Pers.FullName();

cout << "\nAddress: " << Pers.getAddress();

cout << "\nCity: " << Pers.getCity() << ", "

<< Pers.getState() << " " << Pers.getZIPCode();

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

Here is an example of running the program:

Enter personal information

First Name: Jeremy

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\person.htm (8 of 9)11/20/2006 4:10:35 PM


C++ Examples

Last Name: Nguyen

Address: 1466 16th Street #B

City: Washington

State: DC

Zip Code: 20004

Employee Identification

Full Name: Jeremy Nguyen

Address: 1466 16th Street #B

City: Washington, DC 20004

Press any key to continue...

C++ Tutorial Copyright © 2001 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\person.htm (9 of 9)11/20/2006 4:10:35 PM


C++ Examples

FunctionX
- C++ Lists: A Simple List Of Items
Practical
Learning
This example illustrates a simple list of items such as a list of integers, characters, etc.
Logo
Header File: List.h

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

#ifndef ListH

#define ListH

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

const int MaxItems = 100;

typedef double ItemType;

class FList

public:

FList();

virtual ~FList();

int Count() const;

bool Add(const ItemType NewItem);

ItemType Retrieve(const int Pos);

bool Delete(const int Pos);

private:

int Counter;

ItemType Item[MaxItems];

const Index(const int Pos) const;

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\list1.htm (1 of 6)11/20/2006 4:11:14 PM


C++ Examples

};

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

#endif

Source File: List.cpp


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

#pragma hdrstop

#include "List.h"

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

#pragma package(smart_init)

FList::FList()

: Counter(0)

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

FList::~FList()

}//---------------------------------------------------------------------------

int FList::Count() const

return Counter;

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

const FList::Index(const int Pos) const

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\list1.htm (2 of 6)11/20/2006 4:11:14 PM


C++ Examples

return Pos-1;

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

bool FList::Add(const ItemType NewItem)

if( (Counter < 0) || (Counter > MaxItems) )

return false;

else

Item[Counter] = NewItem;

Counter++;

return true;

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

ItemType FList::Retrieve(const int Pos)

if( (Pos < 0) || (Pos > Counter) )

return 0;

else

return Item[Pos];

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

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\list1.htm (3 of 6)11/20/2006 4:11:14 PM


C++ Examples

bool FList::Delete(const int Pos)

if( (Pos < 0) || (Pos > Counter) )

return false;

else

for(int i = Pos+1; i <= Counter; i++)

Item[Index(i-1)] = Item[Index(i)];

Counter--;

return true;

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

Source File: Main.cpp


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

#include <iostream>

#include <conio>

using namespace std;

#pragma hdrstop

#include "List.h"

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

#pragma argsused

int main(int argc, char* argv[])

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\list1.htm (4 of 6)11/20/2006 4:11:14 PM


C++ Examples

FList List;

List.Add(1240.42);

List.Add(283.15);

List.Add(42.48);

List.Add(582.12);

List.Add(60.14);

List.Add(8022.28);

cout << "List of items";

for(int i = 0; i < List.Count(); i++)

cout << "\nItem No." << i + 1 << ": " << List.Retrieve(i);

cout << "\nNumber of items: " << List.Count() << " items\n\n";

List.Delete(5);

List.Delete(2);

cout << "List of items";

for(int i = 0; i < List.Count(); i++)

cout << "\nItem No." << i + 1 << ": " << List.Retrieve(i);

cout << "\nNumber of items: " << List.Count() << " items\n\n";

cout << "Press any key to continue...";

getch();

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\list1.htm (5 of 6)11/20/2006 4:11:14 PM


C++ Examples

return 0;

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

Home Copyright 2003 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\list1.htm (6 of 6)11/20/2006 4:11:14 PM


C++ Examples

FunctionX
- Car Rental Order Processing Exercise
Practical
Learning
Logo File: car.h
Header

#if !defined CAR_H

#define CAR_H

enum TCarType { ctEconomy = 1, ctCompact, ctStandard, ctFullSize, ctMiniVan, ctSUV };

class Car

public:

Car();

Car(char *MM, int Y, int Cat);

virtual ~Car();

void setMakeModel(const char *mm);

char* getMakeModel() const;

void setCarYear(const int y);

int getCarYear() const;

void setCategory(const int c);

int getCategory() const;

private:

char* MakeModel;

int CarYear;

int Category;

};

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (1 of 29)11/20/2006 4:11:36 PM


C++ Examples

#endif // CAR_H

Source File: car.cpp

// Car.cpp: implementation of the Car class.

#include <iostream>

#include <string>

using namespace std;

#include "Car.h"

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

Car::Car()

setMakeModel("No Car Selected");

setCarYear(2000);

setCategory(1);

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

Car::Car(char *MM, int Y, int Cat)

setMakeModel(MM);

setCarYear(Y);

setCategory(Cat);

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

Car::~Car()

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (2 of 29)11/20/2006 4:11:36 PM


C++ Examples

// delete [] MakeModel;

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

void Car::setMakeModel(const char *m)

MakeModel = new char[strlen(m) + 1];

strcpy(MakeModel, m);

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

char* Car::getMakeModel() const

return MakeModel;

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

void Car::setCarYear(const int y)

CarYear = y;

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

int Car::getCarYear() const

return CarYear;

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

void Car::setCategory(const int c)

Category = c;

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (3 of 29)11/20/2006 4:11:36 PM


C++ Examples

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

int Car::getCategory() const

return Category;

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

Header File: customer.h

#if !defined CUSTOMER_H

#define CUSTOMER_H

class Customer

private:

char* FirstName;

char* LastName;

char* Address;

char* City;

char* State;

long ZIPCode;

public:

void setFirstName(const char *FN);

char* getFirstName() const { return FirstName; }

void setLastName(const char *LN);

char* getLastName() const { return LastName; }

char* FullName() const;

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (4 of 29)11/20/2006 4:11:36 PM


C++ Examples

void setAddress(const char *Adr);

char* getAddress() const { return Address; }

void setCity(const char *CT);

char* getCity() const { return City; }

void setState(const char *St);

char* getState() const { return State; }

void setZIPCode(const long ZIP);

long getZIPCode() const { return ZIPCode; }

Customer();

Customer(char *FName, char *LName, char *Adr,

char *Ct, char *St, long ZIP);

Customer(const Customer &Pers);

Customer(char * FName, char * LName);

~Customer();

};

#endif // CUSTOMER_H

Source File: customer.cpp

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

#include <iostream>

using namespace std;

#pragma hdrstop

#include "Customer.h"

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

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (5 of 29)11/20/2006 4:11:36 PM


C++ Examples

char *Customer::FullName() const

char *FName = new char[40];

strcpy(FName, FirstName);

strcat(FName, " ");

strcat(FName, LastName);

return FName;

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

Customer::Customer()

: ZIPCode(0)

FirstName = new char[20];

strcpy(FirstName, "John");

LastName = new char[20];

strcpy(LastName, "Doe");

Address = new char[40];

strcpy(Address, "123 Main Street Apt A");

City = new char[32];

strcpy(City, "Great City");

State = new char[30];

strcpy(State, "Our State");

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

Customer::Customer(char * FName, char * LName)

: ZIPCode(0)

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (6 of 29)11/20/2006 4:11:36 PM


C++ Examples

FirstName = new char[strlen(FName) + 1];

strcpy(FirstName, FName);

LastName = new char[strlen(LName) + 1];

strcpy(LastName, LName);

Address = new char[40];

strcpy(Address, "123 Main Street Apt A");

City = new char[32];

strcpy(City, "Great City");

State = new char[30];

strcpy(State, "Our State");

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

Customer::Customer(char *FName, char *LName, char *Adr,

char *Ct, char *St, long ZIP)

: ZIPCode(ZIP)

FirstName = new char[strlen(FName) + 1];

strcpy(FirstName, FName);

LastName = new char[strlen(LName) + 1];

strcpy(LastName, LName);

Address = new char[40];

strcpy(Address, Adr);

City = new char[32];

strcpy(City, Ct);

State = new char[30];

strcpy(State, St);

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (7 of 29)11/20/2006 4:11:36 PM


C++ Examples

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

Customer::Customer(const Customer &Pers)

: ZIPCode(Pers.ZIPCode)

FirstName = new char[strlen(Pers.FirstName) + 1];

strcpy(FirstName, Pers.FirstName);

LastName = new char[strlen(Pers.LastName) + 1];

strcpy(LastName, Pers.LastName);

Address = new char[strlen(Pers.Address) + 1];

strcpy(Address, Pers.Address);

City = new char[strlen(Pers.City) + 1];

strcpy(City, Pers.City);

State = new char[strlen(Pers.State) + 1];

strcpy(State, Pers.State);

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

void Customer::setFirstName(const char *FN)

strcpy(FirstName, FN);

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

void Customer::setLastName(const char *LN)

strcpy(LastName, LN);

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

void Customer::setAddress(const char *Adr)

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (8 of 29)11/20/2006 4:11:36 PM


C++ Examples

strcpy(Address, Adr);

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

void Customer::setCity(const char *CT)

strcpy(City, CT);

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

void Customer::setState(const char *St)

strcpy(State, St);

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

void Customer::setZIPCode(const long ZIP)

ZIPCode = ZIP;

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

Customer::~Customer()

delete [] FirstName;

delete [] LastName;

delete [] Address;

delete [] City;

delete [] State;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (9 of 29)11/20/2006 4:11:36 PM


C++ Examples

Header File: Invoice.h

#if !defined INVOICE_H

#define INVOICE_H

#include "Customer.h"

#include "Car.h"

#include "RentDate.h"

class Invoice

public:

Invoice();

virtual ~Invoice();

Customer CustomerRegistration();

void CustomerInformation(const Customer& Pers);

Car CarSelection();

void CarSelected(const Car& Vehicle);

double CalculatePrice(const Car& Vehicle, double& Rate, int &Days);

void setMileage(const long g);

long getMileage() const;

void setTankLevel(const char *v);

char* getTankLevel() const;

void setCarCondition(const char *c);

char* getCarCondition() const;

void ProcessOrder();

void CarExamination();

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (10 of 29)11/20/2006 4:11:36 PM


C++ Examples

void ShowOrder();

private:

long Mileage;

char *TankLevel;

char *CarCondition;

};

#endif // INVOICE_H

Source File: Invoice.cpp

// Invoice.cpp: implementation of the Invoice class.

//

//////////////////////////////////////////////////////////////////////

#include <iostream>

#include <iomanip>

#include <string>

using namespace std;

#include "Invoice.h"

//////////////////////////////////////////////////////////////////////

// Construction/Destruction

//////////////////////////////////////////////////////////////////////

Invoice::Invoice()

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (11 of 29)11/20/2006 4:11:36 PM


C++ Examples

setTankLevel("Empty");

setCarCondition("Good");

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

Invoice::~Invoice()

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

Customer Invoice::CustomerRegistration()

char FName[20], LName[20], Addr[40], CT[32], St[30];

long ZC = 0;

cout << "Enter Customer Information\n";

cout << "First Name: "; cin >> FName;

cout << "Last Name: "; cin >> LName;

cout << "Address: "; cin >> ws;

cin.getline(Addr, 40);

cout << "City: ";

cin.getline(CT, 32);

cout << "State: ";

cin.getline(St, 30);

cout << "Zip Code: "; cin >> ZC;

Customer Cust(FName, LName, Addr, CT, St, ZC);

return Cust;

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

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (12 of 29)11/20/2006 4:11:36 PM


C++ Examples

Car Invoice::CarSelection()

int CarType, ModelChosen;

char strCarSelected[20];

int CarSelectedYear = 2000;

cout << "What type of car would you like to rent?";

do {

cout << "\n1 - Economy | 2 - Compact | 3 - Standard"

<< "\n4 - Full Size | 5 - Mini Van | 6 - Sports Utility";

cout << "\nYour Choice: ";

cin >> CarType;

if( CarType < 1 || CarType > 6 )

cout << "\nPlease type a number between 1 and 6";

} while(CarType < 1 || CarType > 6);

switch(CarType)

case ctEconomy:

cout << "\nFor the Economy type, we have:"

<< "\n1 - Daewoo Lanos | 2 - Cheverolet Metro";

cout << "\nWhich one would you prefer? ";

cin >> ModelChosen;

if(ModelChosen == 1)

strcpy(strCarSelected, "Daewoo Lanos");

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (13 of 29)11/20/2006 4:11:36 PM


C++ Examples

CarSelectedYear = 1999;

else

strcpy(strCarSelected, "Chevrolet Metro");

CarSelectedYear = 1998;

break;

case ctCompact:

cout << "\nFor the Compact type, we have:"

<< "\n1 - Chevrolet Cavalier | 2 - Dogde Neon"

<< "\n3 - Nissan Sentra | 4 - Toyota Corolla";

cout << "\nWhich one would you prefer? ";

cin >> ModelChosen;

if(ModelChosen == 1)

strcpy(strCarSelected, "Chevrolet Cavalier");

CarSelectedYear = 1999;

else if(ModelChosen == 2)

strcpy(strCarSelected, "Dodge Neon");

CarSelectedYear = 2001;

else if(ModelChosen == 3)

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (14 of 29)11/20/2006 4:11:36 PM


C++ Examples

strcpy(strCarSelected, "Nissan Sentra");

CarSelectedYear = 1998;

else

strcpy(strCarSelected, "Toyota Corrolla");

CarSelectedYear = 2002;

break;

case ctStandard:

cout << "\nFor the Standard type, we have:"

<< "\n1 - Chevrolet Monte Carlo | 2 - Toyota Camri";

cout << "\nWhich one would you prefer? ";

cin >> ModelChosen;

if(ModelChosen == 1)

strcpy(strCarSelected, "Chevrolet Monte Carlo");

CarSelectedYear = 2000;

else

strcpy(strCarSelected, "Toyota Camri");

CarSelectedYear = 1998;

break;

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (15 of 29)11/20/2006 4:11:36 PM


C++ Examples

case ctFullSize:

cout << "\nFor the Full Size type, we have:"

<< "\n1 - Chrysler 300M | 2 - Buick Century | 3 - Infinity


I30";

cout << "\nWhich one would you prefer? ";

cin >> ModelChosen;

if(ModelChosen == 1)

strcpy(strCarSelected, "Chrysler 300M");

CarSelectedYear = 2000;

else if(ModelChosen == 2)

strcpy(strCarSelected, "Buick Century");

CarSelectedYear = 1999;

else

strcpy(strCarSelected, "Infinity I30");

CarSelectedYear = 2003;

break;

case ctMiniVan:

cout << "\nFor the Mini-Van type, we have:"

<< "\n1 - Dodge Caravan | 2 - Dodge Caravan"

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (16 of 29)11/20/2006 4:11:36 PM


C++ Examples

<< "\n3 - Pontiac Montana | 4 - Pontiac Montana | 5 -


Chevrolet Astro Van";

cout << "\nWhich one would you prefer? ";

cin >> ModelChosen;

if(ModelChosen == 1)

strcpy(strCarSelected, "Dodge Caravan");

CarSelectedYear = 2001;

else if(ModelChosen == 2)

strcpy(strCarSelected, "Dodge Caravan");

CarSelectedYear = 2003;

else if(ModelChosen == 3)

strcpy(strCarSelected, "Pontiac Montana");

CarSelectedYear = 2003;

else

strcpy(strCarSelected, "Chevrolet Astro Van");

CarSelectedYear = 2000;

break;

case ctSUV:

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (17 of 29)11/20/2006 4:11:36 PM


C++ Examples

cout << "\nFor the Sport Utility type, we have:"

<< "\n1 - GMC Jimmy | 2 - Jeep Cherokee"

<< "\n3 - Chevrolet Blazer | 4 - Toyota Pathfinder";

cout << "\nWhich one would you prefer? ";

cin >> ModelChosen;

if(ModelChosen == 1)

strcpy(strCarSelected, "GMC Jimmy");

CarSelectedYear = 1998;

else if(ModelChosen == 2)

strcpy(strCarSelected, "Jeep Cherokee");

CarSelectedYear = 2003;

else if(ModelChosen == 3)

strcpy(strCarSelected, "Chevrolet Blazer");

CarSelectedYear = 2001;

else

strcpy(strCarSelected, "Toyota Pathfinder");

CarSelectedYear = 2000;

break;

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (18 of 29)11/20/2006 4:11:36 PM


C++ Examples

Car Selected(strCarSelected, CarSelectedYear, CarType);

return Selected;

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

void Invoice::setMileage(const long g)

Mileage = g;

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

long Invoice::getMileage() const

return Mileage;

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

void Invoice::setTankLevel(const char *v)

TankLevel = new char[strlen(v) + 1];

strcpy(TankLevel, v);

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

char* Invoice::getTankLevel() const

return TankLevel;

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

void Invoice::setCarCondition(const char *c)

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (19 of 29)11/20/2006 4:11:36 PM


C++ Examples

CarCondition = new char[strlen(c) + 1];

strcpy(CarCondition, c);

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

char* Invoice::getCarCondition() const

return CarCondition;

//--------------------------------------------------------------------

void Invoice::ProcessOrder()

int NbrOfDays;;

double Rate, TotalPrice;

// Enter Customer Information

Customer Person = CustomerRegistration();

cout << "\nProcess Car Information\n";

Car Driving = CarSelection();

TotalPrice = CalculatePrice(Driving, Rate, NbrOfDays);

CarExamination();

// This function works for both Borland C++ Builder and MSVC

system("cls");

cout << " - Bethesda Car Rental -";

cout << "\n=============================";

CustomerInformation(Person);

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (20 of 29)11/20/2006 4:11:36 PM


C++ Examples

cout << "\n------------------------------";

CarSelected(Driving);

cout << setiosflags(ios::fixed) << setprecision(2);

cout << "\n------------------------------";

cout << "\nCar Mileage: " << getMileage();

cout << "\nCondition: " << getCarCondition();

cout << "\nTank Level: " << getTankLevel();

cout << "\n# of Days: " << NbrOfDays;

cout << "\n------------------------------";

cout << "\nRate: $" << Rate;

cout << "\nTotal Price: $" << TotalPrice;

cout << "\n==============================\n";

//--------------------------------------------------------------------

void Invoice::CustomerInformation(const Customer& Pers)

cout << "\nEmployee Identification";

cout << "\nFull Name: " << Pers.FullName();

cout << "\nAddress: " << Pers.getAddress();

cout << "\nCity: " << Pers.getCity() << ", "

<< Pers.getState() << " " << Pers.getZIPCode();

//--------------------------------------------------------------------

void Invoice::CarSelected(const Car& Vehicle)

cout << "\nModel: " << Vehicle.getMakeModel();

cout << "\nYear: " << Vehicle.getCarYear();

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (21 of 29)11/20/2006 4:11:36 PM


C++ Examples

//--------------------------------------------------------------------

double Invoice::CalculatePrice(const Car& Vehicle, double& DayRate,

int &NumberOfDays)

// char WeekEndResponse;// Does the customer rent the car for the week-end?

double OneDayRate, // If renting for less than 5 days including week-end

WeekDay, // If renting for at least 5 days, regardless


of the days

WeekEnd = 0;// If renting for more than two days from Friday to
monday

//double DayRate; // Rate applied based on the number of days

double TotalRate;

switch(Vehicle.getCategory())

case ctEconomy:

DayRate = 24.95;

OneDayRate = 29.95;

WeekDay = 24.95;

WeekEnd = 19.95;

break;

case ctCompact:

DayRate = 34.95;

OneDayRate = 39.95;

WeekDay = 34.95;

WeekEnd = 25.95;

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (22 of 29)11/20/2006 4:11:36 PM


C++ Examples

break;

case ctStandard:

DayRate = 38.95;

OneDayRate = 49.95;

WeekDay = 38.95;

WeekEnd = 32.95;

break;

case ctFullSize:

DayRate = 44.95;

OneDayRate = 69.95;

WeekDay = 44.95;

WeekEnd = 35.95;

break;

case ctMiniVan:

DayRate = 54.95;

OneDayRate = 89.95;

WeekDay = 54.95;

WeekEnd = 42.95;

break;

case ctSUV:

DayRate = 64.95;

OneDayRate = 89.95;

WeekDay = 64.95;

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (23 of 29)11/20/2006 4:11:36 PM


C++ Examples

WeekEnd = 50.95;

break;

cout << "\nHow many days? "; cin >> NumberOfDays;

TotalRate = DayRate * NumberOfDays;

return TotalRate;

//--------------------------------------------------------------------

void Invoice::CarExamination()

char Cond;

int GasLevel;

cout << "Rate the car's condition (e=Excellent/g=Good/d=Driveable): ";

cin >> Cond;

if( Cond == 'e' || Cond == 'E' )

strcpy(CarCondition, "Excellent");

else if( Cond == 'g' || Cond == 'G' )

strcpy(CarCondition, "Good");

else if( Cond == 'd' || Cond == 'D' )

strcpy(CarCondition, "Driveable");

else

strcpy(CarCondition, "Can't Decide");

cout << "Enter the car mileage: ";

cin >> Mileage;

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (24 of 29)11/20/2006 4:11:36 PM


C++ Examples

do {

cout << "Gas level in the tank"

<< "\n1 - Considered Empty"

<< "\n2 - 1/4 Full"

<< "\n3 - Half Full"

<< "\n4 - 3/4 Full"

<< "\n5 - Full Tank";

cout << "\nEnter the gas level: ";

cin >> GasLevel;

}while(GasLevel < 1 || GasLevel > 5);

switch(GasLevel)

case 1:

setTankLevel("Empty");

break;

case 2:

setTankLevel("1/4 Full");

break;

case 3:

setTankLevel("Half Full");

break;

case 4:

setTankLevel("3/4 Full");

break;

case 5:

setTankLevel("Full Tank");

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (25 of 29)11/20/2006 4:11:36 PM


C++ Examples

break;

//--------------------------------------------------------------------

Main File: Main.cpp

#include "Invoice.h"

void main()

CInvoice Order;

Order.ProcessOrder();

Order.ShowOrder();

The following class was not tested and was not (yet) integrated in the program. I don't find time to do it, I hope you will. The idea is
that the clerk should be able to ask the customer for the starting date to rent the car and the project date of the end of lease. Of
course, you (the programmer) must calculate the number of days, find out if the date range falls on a week-end or on a week days. If
the date range is more than 5 days, the rate should be lower than that of 5 days, which should be lower than the rate for 3 days; in
fact the rate should even be lower if the customer wants the car for 20 days or more, which would apply a (low) monthly rate.

Header File: RentDate.h

class CRentDate

public:

CRentDate();

CRentDate(int m, int d, int y);

CRentDate(const CRentDate& d);

void setDate(int m, int d, int y);

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (26 of 29)11/20/2006 4:11:36 PM


C++ Examples

int getMonth();

int getDay();

int getYear();

virtual ~CRentDate();

private:

int Month;

int Day;

int Year;

};

Source File RentDate.cpp


// RentDate.cpp: implementation of the CRentDate class.

//

//////////////////////////////////////////////////////////////////////

#include <iostream.h>

#include "RentDate.h"

//////////////////////////////////////////////////////////////////////

// Construction/Destruction

//////////////////////////////////////////////////////////////////////

CRentDate::CRentDate()

: Month(1), Day(1), Year(1990)

//---------------------------------------------------------------------

CRentDate::CRentDate(int m, int d, int y)

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (27 of 29)11/20/2006 4:11:36 PM


C++ Examples

: Month(m), Day(d), Year(y)

//---------------------------------------------------------------------

CRentDate::CRentDate(const CRentDate& d)

Month = d.Month;

Day = d.Day;

Year = d.Year;

//---------------------------------------------------------------------

CRentDate::~CRentDate()

//---------------------------------------------------------------------

void CRentDate::setDate(int m, int d, int y)

Month = m;

Day = d;

Year = y;

//---------------------------------------------------------------------

int CRentDate::getMonth()

return Month;

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (28 of 29)11/20/2006 4:11:36 PM


C++ Examples

//---------------------------------------------------------------------

int CRentDate::getDay()

return Day;

//---------------------------------------------------------------------

int CRentDate::getYear()

return Year;

//---------------------------------------------------------------------

C++ Tutorial Copyright © 2001 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/examples\carrental.htm (29 of 29)11/20/2006 4:11:36 PM


C++ Tutorial - Article Template

FunctionX C File Processing


Tutorials

Overview
File processing consists of creating, storing, and/or retrieving the contents of a file from a recognizable medium.
For example, it is used to save word processed files to a hard drive, to store a presentation on floppy disk, or to
open a file from a CD-ROM.

To perform file processing on an application, you have various choices, including using features of from C and C++
languages. If you are using the either Win32, Borland C++ Builder, Visual C++, their libraries provide additional
support for file processing.

File processing is traditionally performed using the FILE class. In the strict C sense, FILE is a structure and it is
defined in the stdio.h header file. This object is equipped with variables used to indicate what operation would be
performed. To use this structure, you can first declare an instance of the FILE structure. Here is an example:

FILE *Starter;

After instantiating this structure, you can define what to do with it, using one of the provided functions. Because
FILE was created as a C structure, it does not have member functions. The functions used to perform its related
operations on files are also declared in the stdio.h header file:
Opening and/or Saving Files
To create a new file, open an existing file, or save a file, you use the fopen() function. Its syntax is:

FILE *fopen(const char *FileName, const char *Mode);

The first argument, FileName, must be a valid name of a file. If the user is creating or saving a new file, you can let
him specify the name of the file, following the rules of the operating system. If the user is opening an existing file,
you can make sure the file really exists, retrieve its name and pass it to the fopen() function.

Because the fopen() function is used to save a new file, to open an existing one, or to save a file that was only
modified, the second argument, Mode, actually allows you to decide what operation the function will be used to
perform. This argument is a short string of one or two characters and can be one of the following:

http://192.168.16.242/cts/tutorials/functionx/cpp/articles\cfileprocessing.htm (1 of 7)11/20/2006 4:12:03 PM


C++ Tutorial - Article Template

Mode Role If the file already exists If the file does not exist
it would be opened and can
Opens an existing file for be read. After the file is
r the operation would fail
reading only opened, the user cannot add
data to it
the file's contents would be
a new file is created and can be written
w Saves a new file deleted and replaced by the
to
new content
the file is opened and can be
Opens an existing file, saves modified or updated. New
a new file is created and can be written
a new file, or saves a existing information written to the
to
file that has been modified file would be added to the
end of the file
the file is opened and its
r+ Opens an existing file existing data can be the operation would fail
modified or updated
the file is opened, its
Creates new file or saves an contents would be deleted a new file is created and can be written
w+
existing one and replaced with the new to
contents
it is opened and its contents
can be updated. New
Creates a new file or a new file is created and can be written
a+ information written to the
modifies an existing one to
file would be added to the
end of the file
If the operation performed using the fopen() function is successful, the function returns a pointer to the FILE
instance that was declared.

The FILE structure is usually used in C and C++ console programs that must conform to console applications.
However, when used in a GUI application, such as an application created using C++ Builder, Visual C++, Win32,
or another C++ programming environment, because applications are created in a visual development, you can let
the users use the Save and Open common dialog boxes that they are used to.

After using a file, you should/must close its stream. This is done using the fclose() function. Its syntax is:

int fclose(FILE *stream);

To use this function, you must let it know what instance of the FILE object you are closing.
Writing Data to a File

http://192.168.16.242/cts/tutorials/functionx/cpp/articles\cfileprocessing.htm (2 of 7)11/20/2006 4:12:03 PM


C++ Tutorial - Article Template

To save a file, you must write data to its contents. This operation is performed using the fprintf() or the fwprintf()
functions. Their syntaxes are:

int fprintf(FILE *stream, const char *format, ...);

int fwprintf(FILE *stream, const wchar_t *format, ...);

The fprintf() function takes a few arguments depending on how it is used. The first parameter, stream, must be an
instance of a FILE structure.

The second parameter, format, is a string that specifies how data will be formatted and possibly positioned in the
stream instance. The string typically starts with the % symbol followed by one or more characters that represents a
format. Different formats are used depending on the type of data of the variable that is being written. You can use
one the following characters:

Character Used for


c A single character
d An integer
e A floating-point number
f A floating-point number
g A floating-point number
h A short integer
i A decimal, a hexadecimal, or an octal integer
o An octal integer
s A string followed by a white space character
u An unsigned decimal integer
x A hexadecimal integer
After specifying the format, you can type the name of the variable that is being saved. You can repeatedly use the
fprintf() function for each variable you want to save.

Here is an example of creating a file and letting the user supply data that would be saved to the file:

// Program to perform file processing using the FILE structure

// Author: Jacques E. Zoo

#include <iostream>

using namespace std;

int main()

http://192.168.16.242/cts/tutorials/functionx/cpp/articles\cfileprocessing.htm (3 of 7)11/20/2006 4:12:03 PM


C++ Tutorial - Article Template

char Make[20], Model[20];

unsigned int CarYear;

long Mileage;

FILE *CarInventory = fopen("cars.inv", "w");

cout << "Enter the following pieces of information\n";

cout << "Make: "; gets(Make);

cout << "Model: "; gets(Model);

cout << "Year: "; cin >> CarYear;

cout << "Mileage: "; cin >> Mileage;

fprintf(CarInventory, "%s\n", Make);

fprintf(CarInventory, "%s\n", Model);

fprintf(CarInventory, "%d\n", CarYear);

fprintf(CarInventory, "%d\n", Mileage);

fclose(CarInventory);

cout << endl;

return 0;

Here is an example of running the program:

http://192.168.16.242/cts/tutorials/functionx/cpp/articles\cfileprocessing.htm (4 of 7)11/20/2006 4:12:03 PM


C++ Tutorial - Article Template

Reading Data From a File


If you have a file and want to retrieve data stored from it, you can use the fscanf() or the fwscanf() function. Their
syntaxes are:

int fscanf(FILE *stream, const char *format[, address, ...]);

int fwscanf(FILE *stream, const wchar_t *format[, address, ...]);

The first parameter, stream, must be a valid instance of a FILE structure.

The second parameter, format, follows the same rules as for the fprintf() and the fwprintf() functions. After typing
the format, type the name of the variable that is being retrieved.

Here is an example that reads data saved previously:

// Program to perform file processing using the FILE structure

// Author: Jacques E. Zoo

#include <iostream>

using namespace std;

int main()

char Make[20], Model[20];

unsigned int CarYear;

long Mileage;

http://192.168.16.242/cts/tutorials/functionx/cpp/articles\cfileprocessing.htm (5 of 7)11/20/2006 4:12:03 PM


C++ Tutorial - Article Template

/*

FILE *CarInventory = fopen("cars.inv", "w");

cout << "Enter the following pieces of information\n";

cout << "Make: "; gets(Make);

cout << "Model: "; gets(Model);

cout << "Year: "; cin >> CarYear;

cout << "Mileage: "; cin >> Mileage;

fprintf(CarInventory, "%s\n", Make);

fprintf(CarInventory, "%s\n", Model);

fprintf(CarInventory, "%d\n", CarYear);

fprintf(CarInventory, "%d\n", Mileage);

*/

FILE *CarInventory = fopen("cars.inv", "r+");

fscanf(CarInventory, "%s\n", Make);

fscanf(CarInventory, "%s\n", Model);

fscanf(CarInventory, "%d\n", &CarYear);

fscanf(CarInventory, "%d\n", &Mileage);

cout << "Information about the car";

cout << "\nMake: " << Make;

http://192.168.16.242/cts/tutorials/functionx/cpp/articles\cfileprocessing.htm (6 of 7)11/20/2006 4:12:03 PM


C++ Tutorial - Article Template

cout << "\nModel: " << Model;

cout << "\nYear: " << CarYear;

cout << "\nMileage: " << Mileage;

fclose(CarInventory);

cout << endl;

return 0;

This would produce:

Copyright © 1998-2003 FunctionX, Inc.

http://192.168.16.242/cts/tutorials/functionx/cpp/articles\cfileprocessing.htm (7 of 7)11/20/2006 4:12:03 PM


http://192.168.16.242/cts/tutorials/functionx/cpp/clearscreen.htm

Clearing the Screen


Clearing the screen on a console application appears to be related to the operating system you are using or to your
compiler.

Borland C++ Builder


There are two basic ways you can clear the screen in Borland C++ Builder. The simplest technique consists of
calling the system() function with the string argument "cls". Here is an example:

//---------------------------------------------------------------------------

#include <iostream.h>

#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...";

http://192.168.16.242/cts/tutorials/functionx/cpp/clearscreen.htm (1 of 4)11/20/2006 4:12:20 PM


http://192.168.16.242/cts/tutorials/functionx/cpp/clearscreen.htm

getchar();

return 0;

//---------------------------------------------------------------------------

Another technique, highly known to Borland C++ Builder console programmers consists of calling the clrscr()
function. The clrscr() function is part of the conio library. The clrscr() function is neither part of the C++
Standard nor part of the MS Windows operating system. Here is an example of using it:

//---------------------------------------------------------------------------

#include <iostream.h>

#include <conio.h>

#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;

http://192.168.16.242/cts/tutorials/functionx/cpp/clearscreen.htm (2 of 4)11/20/2006 4:12:20 PM


http://192.168.16.242/cts/tutorials/functionx/cpp/clearscreen.htm

cout << "\n\nPress any key to continue...";

getchar();

return EXIT_SUCCESS;

//---------------------------------------------------------------------------

MS Visual C++
To clear the screen in MSVC, first, instead of #include <iostream.h>, you must use

#include <iostream>
using namespace std;

Then, call the system() function with the string argument of "cls" where you want to clear the screen:

#include <iostream>

using namespace std;

int main()

char FirstName[12], LastName[12];

cout << "Enter First Name: "; cin >> FirstName;

cout << "Enter Last Name: "; cin >> LastName;

system("cls");

cout << "Full Name: " << FirstName << " " << LastName << "\n\n";

http://192.168.16.242/cts/tutorials/functionx/cpp/clearscreen.htm (3 of 4)11/20/2006 4:12:20 PM


http://192.168.16.242/cts/tutorials/functionx/cpp/clearscreen.htm

return EXIT_SUCCESS;

http://192.168.16.242/cts/tutorials/functionx/cpp/clearscreen.htm (4 of 4)11/20/2006 4:12:20 PM


C++ Tutorials - Identifiers And Variables - FunctionX

A Console-Based
Multiple Choice Question

Programming a Multiple-Choice Question


Practical Learning: Introduction to Exceptions
1. Create a new Console Application in a new folder named BibleQuiz
2. Create a new C++ source file named Exercise
3. Change the content of the file with the following:

#include <algorithm>

#include <vector>

#include <functional>

#include <iostream>

using namespace std;

#include <time.h>

const int NbrOfQuestions = 22;

int AskQuestion(int q, double &m);

void Verify(int);

int main(int argc, char* argv[])

int i, n;

double Average, Sum = 0;

typedef vector<int> IntVector;

typedef IntVector::iterator IntVectorIt;

IntVector QuestNbr(NbrOfQuestions);

IntVectorIt Start, End;

http://192.168.16.242/cts/tutorials/functionx/cpp/mcq.htm (1 of 22)11/20/2006 4:12:40 PM


C++ Tutorials - Identifiers And Variables - FunctionX

for(i = 0; i < NbrOfQuestions; i++)

QuestNbr[i] = i;

Start = QuestNbr.begin();

End = QuestNbr.end();

srand(time(0));

random_shuffle(Start, End);

cout << " - Multiple Choice Question -\n\n";

do {

cout << "How many questions (1-20)? ";

cin >> n;

} while(n < 1 || n > 20);

system("cls");

for(i = 0; i < n; i++)

system("cls");

cout << "Question " << i + 1 << ": ";

AskQuestion(QuestNbr[i], Sum);

getchar();

system("cls");

Average = (Sum / n) * 100;

cout << "Answers Overview\n";

cout << "Your answers were";

http://192.168.16.242/cts/tutorials/functionx/cpp/mcq.htm (2 of 22)11/20/2006 4:12:40 PM


C++ Tutorials - Identifiers And Variables - FunctionX

cout << "\nGood Answers: " << Sum;

cout << "\nAverage: " << Average<< "%";

cout << "\n\n";

return 0;

int AskQuestion(int q, double &m)

char Answer[10];

switch(q)

case 0:

cout << "\nWho was Jesus Christ\'s mother ? ";

cout << "\n1. Leah"

<< "\n2. Marthe"

<< "\n3. Mary"

<< "\n4. salome"

<< "\nAnswer: ";

cin >> Answer;

if(Answer[0] == '3')

cout << "\nGood Answer";

cout << "\nRef: Lk 1:26-31";

m += 1;

else

cout << "\nWrong Answer!";

http://192.168.16.242/cts/tutorials/functionx/cpp/mcq.htm (3 of 22)11/20/2006 4:12:40 PM


C++ Tutorials - Identifiers And Variables - FunctionX

Verify(0);

break;

case 1:

cout << "\nHow many books are in the canonical Bible?";

cout << "\n1. 33"

<< "\n2. 44"

<< "\n3. 55"

<< "\n4. 66"

<< "\nAnswer: ";

cin >> Answer;

if(Answer[0] == '4')

cout << "Good Answer\n";

m += 1;

else

cout << "Wrong Answer!";

Verify(1);

break;

case 2:

cout << "\nWhat is the first book of the Bible ?";

cout << "\n1. Malachi"

<< "\n2. Isaiah"

<< "\n3. Revelation"

<< "\n4. Genesis"

http://192.168.16.242/cts/tutorials/functionx/cpp/mcq.htm (4 of 22)11/20/2006 4:12:40 PM


C++ Tutorials - Identifiers And Variables - FunctionX

<< "\nAnswer: ";

cin >> Answer;

if(Answer[0] == '4')

cout << "Good Answer\n";

m += 1;

else

cout << "Wrong Answer!";

Verify(2);

break;

case 3:

cout << "\nWhich one of Jacob\'s sons was Joseph\'s "

<< "brother, his own mother\'s son ?";

cout << "\n1. Levi"

<< "\n2. Judah"

<< "\n3. Asher"

<< "\n4. Benjamin"

<< "\nAnswer: ";

cin >> Answer;

if(Answer[0] == '4')

cout << "\nGood Answer";

cout << "\nRef: Ge 43:29";

m += 1;

else

http://192.168.16.242/cts/tutorials/functionx/cpp/mcq.htm (5 of 22)11/20/2006 4:12:40 PM


C++ Tutorials - Identifiers And Variables - FunctionX

cout << "Wrong Answer!";

Verify(3);

break;

case 4:

cout << "\nWhat happened to Ananias and Sapphira after they lied "

<< "about the money\nthey collected from selling the land ?";

cout << "\n1. They died"

<< "\n2. They got sick"

<< "\n3. They were abandoned by the other discples in the bush"

<< "\n4. They were drowned in the sea of Galilee"

<< "\nAnswer: ";

cin >> Answer;

if(Answer[0] == '1')

cout << "\nGood Answer";

cout << "\nRef: Ac 5:1-11";

m += 1;

else

cout << "Wrong Answer!";

Verify(4);

break;

case 5:

cout << "\nHow many apostles did Jesus Christ have?";

http://192.168.16.242/cts/tutorials/functionx/cpp/mcq.htm (6 of 22)11/20/2006 4:12:40 PM


C++ Tutorials - Identifiers And Variables - FunctionX

cout << "\n1. 3"

<< "\n2. 6"

<< "\n3. 9"

<< "\n4. 12"

<< "\nAnswer: ";

cin >> Answer;

if(Answer[0] == '4')

cout << "Good Answer\n";

m += 1;

else

cout << "Wrong Answer!";

Verify(5);

break;

case 6:

cout << "\nWhat was the craftiest of the wild animals "

<< "the Lord had made?";

cout << "\n1. The dragon"

<< "\n2. The serpent"

<< "\n3. The lion"

<< "\n4. The Dove"

<< "\nAnswer: ";

cin >> Answer;

if(Answer[0] == '2')

cout << "Good Answer\n";

http://192.168.16.242/cts/tutorials/functionx/cpp/mcq.htm (7 of 22)11/20/2006 4:12:40 PM


C++ Tutorials - Identifiers And Variables - FunctionX

m += 1;

else

cout << "Wrong Answer!";

Verify(6);

break;

case 7:

cout << "\nTo which disciple did Jesus promise the key\n"

<< "of the kingdom of heaven ?";

cout << "\n1. John"

<< "\n2. Peter"

<< "\n3. Philip"

<< "\n4. Paul"

<< "\nAnswer: ";

cin >> Answer;

if(Answer[0] == '2')

cout << "Good Answer\n";

m += 1;

else

cout << "Wrong Answer!";

Verify(7);

break;

http://192.168.16.242/cts/tutorials/functionx/cpp/mcq.htm (8 of 22)11/20/2006 4:12:40 PM


C++ Tutorials - Identifiers And Variables - FunctionX

case 8:

cout << "\nHow does Paul address Timothy in 1 Timothy?";

cout << "\n1. My disciple"

<< "\n2. My brother"

<< "\n3. My son"

<< "\n4. My father"

<< "\nAnswer: ";

cin >> Answer;

if(Answer[0] == '3')

cout << "\nGood Answer";

m += 1;

else

Verify(8);

cout << "\nWrong Answer!";

cout << endl;

break;

case 9:

cout << "\nWho was the father of the 12 patriarchs?";

cout << "\n1. Noah"

<< "\n2. Abraham"

<< "\n3. Isaac"

<< "\n4. Jacob"

<< "\nAnswer: ";

cin >> Answer;

if(Answer[0] == '4')

http://192.168.16.242/cts/tutorials/functionx/cpp/mcq.htm (9 of 22)11/20/2006 4:12:40 PM


C++ Tutorials - Identifiers And Variables - FunctionX

cout << "\nGood Answer";

m += 1;

else

cout << "\nWrong Answer!";

Verify(9);

cout << endl;

break;

case 10:

cout << "\nWho was the firstborn son of Adam and Eve?";

cout << "\n1. Abel"

<< "\n2. Cain"

<< "\n3. Shem"

<< "\n4. Japhet"

<< "\nAnswer: ";

cin >> Answer;

if(Answer[0] == '2')

cout << "Good Answer\n";

m += 1;

else

cout << "Wrong Answer!";

Verify(10);

http://192.168.16.242/cts/tutorials/functionx/cpp/mcq.htm (10 of 22)11/20/2006 4:12:40 PM


C++ Tutorials - Identifiers And Variables - FunctionX

cout << endl;

break;

case 11:

cout << "\nTo whom did James address his book?";

cout << "\n1. The 12 tribes"

<< "\n2. To those who have received faith"

<< "\n3. To the believers"

<< "\n4. To Epaphroditus"

<< "\nAnswer: ";

cin >> Answer;

if(Answer[0] == '1')

cout << "Good Answer\n";

m += 1;

else

cout << "Wrong Answer!";

Verify(11);

cout << endl;

break;

case 12:

cout << "\nWhat did Micah from the hill country of Ephraim "

<< "do of the\nyoung Levite who came to stay with him?";

cout << "\n1. He taught him to raise the sheep"

<< "\n2. He made him a priest"

http://192.168.16.242/cts/tutorials/functionx/cpp/mcq.htm (11 of 22)11/20/2006 4:12:40 PM


C++ Tutorials - Identifiers And Variables - FunctionX

<< "\n3. He killed him"

<< "\n4. He sent him away"

<< "\nAnswer: ";

cin >> Answer;

if(Answer[0] == '2')

cout << "\nGood Answer\n";

m += 1;

else

cout << "\nWrong Answer!";

Verify(12);

cout << endl;

break;

case 13:

cout << "\nThe account of Noah starts on";

cout << "\n1. Ge 5:6"

<< "\n2. Ge 6:9"

<< "\n3. Ge 8:15"

<< "\n4. Ge 9:18"

<< "\nAnswer: ";

cin >> Answer;

if(Answer[0] == '2')

cout << "Good Answer\n";

m += 1;

http://192.168.16.242/cts/tutorials/functionx/cpp/mcq.htm (12 of 22)11/20/2006 4:12:40 PM


C++ Tutorials - Identifiers And Variables - FunctionX

else

cout << "Wrong Answer!";

Verify(13);

break;

case 14:

cout << "\nIn the parable of the weed, what does the field represent?";

cout << "\n1. The Ocean"

<< "\n2. The world"

<< "\n3. The kingdom"

<< "\n4. The Earth"

<< "\nAnswer: ";

cin >> Answer;

if(Answer[0] == '2')

cout << "Good Answer\n";

m += 1;

else

cout << "Wrong Answer!";

Verify(14);

break;

case 15:

cout << "\nHow many people (including Noah) got in the ark he built?";

cout << "\n1. 6"

http://192.168.16.242/cts/tutorials/functionx/cpp/mcq.htm (13 of 22)11/20/2006 4:12:40 PM


C++ Tutorials - Identifiers And Variables - FunctionX

<< "\n2. 7"

<< "\n3. 8"

<< "\n4. 9"

<< "\nAnswer: ";

cin >> Answer;

if(Answer[0] == '2')

cout << "Good Answer\n";

m += 1;

else

cout << "Wrong Answer!";

Verify(15);

break;

case 16:

cout << "\nWho was John the Baptist\'s mother?";

cout << "\n1. Salome"

<< "\n2. mary"

<< "\n3. Elizabeth"

<< "\n4. Rebecah"

<< "\nAnswer: ";

cin >> Answer;

if(Answer[0] == '3')

cout << "Good Answer\n";

m += 1;

http://192.168.16.242/cts/tutorials/functionx/cpp/mcq.htm (14 of 22)11/20/2006 4:12:40 PM


C++ Tutorials - Identifiers And Variables - FunctionX

else

cout << "Wrong Answer!";

Verify(16);

break;

case 17:

cout << "\nIn how many pieces did the young Levite whose"

<< "concubine was raped by the men of Gibeah cut her?";

cout << "\n1. 3"

<< "\n2. 7"

<< "\n3. 12"

<< "\n4. 36"

<< "\nAnswer: ";

cin >> Answer;

if(Answer[0] == '3')

cout << "\nGood Answer";

m += 1;

else

cout << "\nWrong Answer!";

Verify(17);

break;

case 18:

cout << "\n\"If anyone would come after me, he must deny\n"

http://192.168.16.242/cts/tutorials/functionx/cpp/mcq.htm (15 of 22)11/20/2006 4:12:40 PM


C++ Tutorials - Identifiers And Variables - FunctionX

<< "himself and take up his cross and follow me.\"";

cout << "\nWho said or wrote it ?";

cout << "\n1. Moses"

<< "\n2. John the Baptist"

<< "\n3. Jesus Christ"

<< "\n4. Paul"

<< "\nAnswer: ";

cin >> Answer;

if(Answer[0] == '3')

cout << "\nGood Answer";

m += 1;

else

cout << "\nWrong Answer!";

Verify(18);

break;

case 19:

cout << "\nHow old was Abraham when he died?";

cout << "\n1. 175"

<< "\n2. 230"

<< "\n3. 310"

<< "\n4. 425"

<< "\nAnswer: ";

cin >> Answer;

if(Answer[0] == '1')

http://192.168.16.242/cts/tutorials/functionx/cpp/mcq.htm (16 of 22)11/20/2006 4:12:40 PM


C++ Tutorials - Identifiers And Variables - FunctionX

cout << "\nGood Answer";

m += 1;

else

cout << "\nWrong Answer!";

Verify(19);

break;

case 20:

cout << "\nWho said or wrote, \" You are the light of the world \"?";

cout << "\n1. Moses"

<< "\n2. Paul"

<< "\n3. Jesus"

<< "\n4. John"

<< "\nAnswer: ";

cin >> Answer;

if(Answer[0] == '3')

cout << "\nGood Answer";

m += 1;

else

cout << "\nWrong Answer!";

Verify(20);

break;

http://192.168.16.242/cts/tutorials/functionx/cpp/mcq.htm (17 of 22)11/20/2006 4:12:40 PM


C++ Tutorials - Identifiers And Variables - FunctionX

case 21:

cout << "\nFor how long did the rain fall on the earth\n"

<< "while Noah and his family were in the ark he built?";

cout << "\n1. 30 days"

<< "\n2. 40 days"

<< "\n3. 50 days"

<< "\n4. 60 days"

<< "\nAnswer: ";

cin >> Answer;

if(Answer[0] == '2')

cout << "\nGood Answer";

cout << "\nRef: Ge 7:12";

m += 1;

else

cout << "\nWrong Answer!";

Verify(20);

break;

cout << "\nPress Enter for next question...";

getchar();

return Answer[q];

void Verify(int t)

http://192.168.16.242/cts/tutorials/functionx/cpp/mcq.htm (18 of 22)11/20/2006 4:12:40 PM


C++ Tutorials - Identifiers And Variables - FunctionX

switch(t)

case 0:

cout << "\nLk 1:26-31";

cout << "\nLuke gives the name of Jesus\' mother as Mary";

break;

case 1:

cout << "\nYou can get the right answer by counting the books";

break;

case 2:

cout << "\nYou can check the answer by opening the Bible";

break;

case 3:

cout << "\nRachel was Jacob\'s wife and gave birth to two sons";

cout << "\nJoseph was born in Ge 30:22-24";

cout << "\nBenjamin, was Rachel\'s second son";

break;

case 4:

cout << "\nYou can find the reference at Acts 5:1-11\n";

break;

case 5:

cout << "\nWhen on Earth, Jesus Christ had 12 apostles";

cout << "\nYou can find a reference at Lk 6:13";

break;

case 6:

cout << "\nThe serpent was the craftiest animal";

cout << "\nThe reference can be found at Ge 3:1";

break;

case 7:

http://192.168.16.242/cts/tutorials/functionx/cpp/mcq.htm (19 of 22)11/20/2006 4:12:40 PM


C++ Tutorials - Identifiers And Variables - FunctionX

cout << "\nPeter was promised the key to the kingdom of heaven";

cout << "\nThis can be checked from Mt 16:19";

break;

case 8:

cout << "\nIn 1Tm 1:2, Paul addresses Timothy as \"My true son\"";

break;

case 9:

cout << "\nThe father of the 12 patriarchs was Jacob ";

cout << "as indicated in Acts 7:8";

break;

case 10:

cout << "\nAccording to Ge 4:1, Cain was Adam\'s first son";

cout << "\nAdam\'s second son was Abel, as found in Ge 4:2";

break;

case 11:

cout << "\nJames addressed his book to the 12 tribes";

cout << "\nReference: James 1:1";

break;

case 12:

cout << "\nMicah made the young man his priest";

cout << "\nReference: Judges 17:12";

break;

case 13:

cout << "\nThe story of Noah is in Genesis";

cout << "\nThe reference can be found at Ge 6:9";

break;

case 14:

cout << "\nIn the parable of the weed, the field"

<< "represents the world";

cout << "\nRef: Mt 13:38";

http://192.168.16.242/cts/tutorials/functionx/cpp/mcq.htm (20 of 22)11/20/2006 4:12:40 PM


C++ Tutorials - Identifiers And Variables - FunctionX

break;

case 15:

cout << "\nNoah was married: 2 people";

cout << "\nNoah had 3 sons and each was married: 6 people";

cout << "\n2 + 6 means there were 8 people in the arch.";

cout << "\nRef: Ge 7:7";

break;

case 16:

cout << "\nElizabeth was John The Baptiste mother";

cout << "\nRef: Lk 1:36-37";

break;

case 17:

cout << "\nThis story is accounted in Judges 19";

cout << "\nRef: Jg 19:29";

break;

case 18:

cout << "\nJesus said that in Mt 16:24";

break;

case 19:

cout << "\nAbraham lived 175 years and died";

cout << "\nThis is indicated in Ge 25:7";

break;

case 20:

cout << "\nThis is quote from The Sermon on the Mount";

cout << "\nRef: Mt 5:14";

case 21:

cout << "\nwhile Noah and his family were in the ark he built\n"

<< "the \"rain fell on the earth 40 days and 40 nights.";

cout << "\nRef: Ge 7:12";

break;

http://192.168.16.242/cts/tutorials/functionx/cpp/mcq.htm (21 of 22)11/20/2006 4:12:40 PM


C++ Tutorials - Identifiers And Variables - FunctionX

4. Test the program.

Copyright © 2003 FunctionX

http://192.168.16.242/cts/tutorials/functionx/cpp/mcq.htm (22 of 22)11/20/2006 4:12:40 PM

You might also like