Functionx CPP Tutorials
Functionx CPP Tutorials
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
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
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.
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.
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
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.
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.
#include <iostream.h>
#include <stdio.h>
getchar();
return 0;
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
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
//---------------------------------------------------------------------------
#include <iostream.h>
#include <conio.h>
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
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.
#include <iostream.h>
int main()
return 0;
7. Save your file. If you are using gedit like me, on the main menu, click File -> Save As...
8. Under the Directory header in the left list, double-click the Up One Level button ../
If you see your user name in the left list, fine. Otherwise, double-click ../ again.
9. On the left list, double-click your user name (for me that would be root/) to open you personal directory
10. On the left list, double-click the Exercise1/ directory we created.
11. In the Selection: text box, type the name of the file as Exo.cpp and click OK
12. To execute the program, open the Terminal: Start -> System -> Terminal.
In the Terminal window, you should see [UserName@localhost Username]$
For example, mine is [root@localhost root]$
13. This ensures that you are in your personal directory. To change to the directory that hosts your exercise, type cd
Exercise1
Now the new folder should be inside the square brackets. Mine is [Username@localhost Exercise1]$
14. To compile the program, we will use the free g++ compiler. Therefore, type:
g++ Exo.cpp
15. For example, on mine, I type [jezoo@localhost Exercise1]$ g++ Exo.cpp
16. You may receive one warning. For now, don't worry.
17. To execute the program, type ./a.out and press Enter
18. This is because the executable file, named a with the extension .out has been created one folder up from the actual
location of the C++ file.
For example, on mine, I type [root@localhost Exercise1]$ ./a.out
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
1. To create program in KDevelop, start KDevelop by clicking Start -> Development ->KDevelop
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
#include <iostream.h>
int main()
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
7. Click OK.
8. In the Win32 Console Application Step 1 of 1, click the An Empty Project radio button
9. Click Finish.
10. You will be presented with another dialog box. Click OK.
11. To create a C++ file, on the main menu, click File -> New...
12. In the New dialog box, make sure the Files property sheet is selected.
13. Click C++ Source File
14. In the File Name, type a name such as Exercise and click OK
15. From what we have learned so far, change the contents of the file as follows:
#include <iostream.h>
int main()
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.
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
#include <iostream.h>
int main()
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.
From now on, you will sometimes be asked to create a project. Follow the instructions of your compiler as we have
seen above.
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()
return 0;
Comments
The most basic documentation you will (have to) perform is to put comments as much as you can. Comments help you and
other people who read your code to figure out what you were doing.
Comments are not read by the compiler while executing your program. That means you write them in everyday conversation.
There are two usual ways of including comments in your program. To comment the contents of one line, you start it with
double forward slashes like this //
Here is an example:
#include <iostream.h>
int main()
return 0;
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 */
#include <iostream.h>
int main()
return 0;
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.
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.
#include <iostream.h>
main()
// Another list
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:
#include <iostream.h>
main()
<< "Company\t\tSoftware\n"
// Another list
<< "Continent\tCountry\tCapital\n"
<< "Europe\t\tItaly\tRome\n"
<< "Africa\t\tLybia\tTripoli\n"
Introduction to Variables
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.
● 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)
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:
Some of these words are used by KDevelop or could come in conflict with various libraries. Therefore, avoid using these
additional words:
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.
● 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
After declaring a variable, the compiler reserves a space in memory for that variable:
A variable, any variable, occupies more that one small “cell” of space in memory. It will always be your responsibility to
decide how much space a variable needs, based on your goal.
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:
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.
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.
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.
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
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.
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.
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.
In real life, there are numbers counted in decrement values. Such numbers start at –1 and move down to -2, -3, -4 etc.
These numbers are qualified as negative.
When you write a number “normally”, such as 42, 502, or 1250, the number is positive. If you want to express the number
as negative, you use the – on the left side of the number. The – symbol is called a sign. Therefore, if the number does not
have the – symbol, C++ (or the compiler) considers such a number as unsigned. In C++, if you declare a variable that would
represent a numeric value and you do not initialize (assign a value to) such a variable, the compiler will consider that the
variable can hold either a signed or an unsigned value. If you want to let the compiler know that the variable should hold only
a positive value, you will declare such a variable as unsigned.
Representing Numbers
A Bit
The computer (or an Intel computer, or a computer that runs on an Intel microprocessor) uses the binary system to
represent its information. A piece of information in the computer is called a datum; and the plural is data. Sometimes, the
word data is used for both singular and plural.
The computer represents data using only a 0 or 1 values. To make an illustration, let's consider that a computer uses a small
box to represent such a value. This small box can have only one of two states. When the box is empty, we will give it a value
of 0. When the box is full, we give it a value of 1. The box can have only one of these two values.
Since this box can have only one of two states, consider that you can use it to represent anything that could assume one out
of two states. Examples include: True-False; Parent-Child; On-Off; Discount-NoDiscount; Male-Female; Yes-No, etc.
This technique of representing values is called The Binary system. In the computer, it uses values 0 and/or 1, which
themselves are called digits. The entity used to represent such a value is called a binary digit; in its abbreviated form, it is
called a bit (for binary digit). The bit (binary digit) is the most fundamental representation of the computer's counting
system. Although this is valid for the computer, the Intel microprocessors cannot validate a variable at this level; but
eventually, you will be able to manipulate data at the bit level.
Although the C++ compiler recognizes a bit, you cannot store a variable in a bit. However, eventually, you will be able to
manipulate the information stored in a bit.
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:
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:
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:
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.
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:
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()
Character Variables
A byte is used to hold a single character. A character is an individual symbol that displays on your screen. It could be:
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:
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()
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()
You can also declare a positive character as unsigned char. Here is an example:
#include <iostream.h>
main()
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()
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()
Besides the \n escape sequence, you can also use the endl keyword to move the cursor to the next line.
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:
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()
MachineIsWorking = false;
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
= 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:
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>
By default, a short integer is signed. You can also explicitly declare such a variable as a signed short. Here is an example:
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>
main()
<< "\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.
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 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:
27 26 25 24 23 22 21 20
128 64 32 16 8 4 2 1
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
= 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:
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()
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:
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:
An unsigned integer can also be declared simply with the unsigned keyword. Here is an example:
#include <iostream.h>
main()
<< 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;
Enumerations
An enumeration provides a technique of setting a list of integers where each item of the list is ranked and has a specific
name. For example, instead of numbers that represent players of a football (soccer) game such as 1, 2, 3, 4, 5, you can use
names instead. This would produce GoalKeeper, RightDefender, LeftDefender, Stopper, Libero. The syntax of creating an
enumeration is
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:
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:
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:
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:
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()
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:
#include <iostream.h>
main()
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 values at random, you could change the list of pizzas as follows:
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
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()
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()
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.
#include <iostream.h>
main()
Using Variables
A reference is a variable name that is a duplicate of an existing variable. It provides a technique of creating more than one
name to designate the same variable. The syntax of creating or declaring a reference is:
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()
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()
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()
Number = 4250;
Nbr = 38570;
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;
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:
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()
return 0;
Constants
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()
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:
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:
#define MAXSTUDENTS 35
Another technique of creating a constant is by using the const keyword. The syntax of using the const keyword is:
Or
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.
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";
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.
In the same way, C++ provides constant double-precision numbers in the cfloat library. These constants are:
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
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.
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;
return 0;
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::Time = 2;
return 0;
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()
return 0;
Principal: $12500
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;
Interest = InterestAndDiscount::Principal *
(InterestAndDiscount::Rate/100) *
InterestAndDiscount::Time;
return 0;
To call a namespace, on the section of the program where you need to access the members, type:
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
double Principal;
double Rate;
int Time;
int main()
double Interest;
double MaturityValue;
return 0;
Principal: $2500
Number of Years: 4
Loan Processing
Principal: $2500
Rate: 12.15%
Time: 4 years
Interest: $1215
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;
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;
double TaxRate;
double TaxAmount;
double Discount;
double DiscountAmount;
double NetPrice;
int main()
InterestAndDiscount::Principal = 12500; // $
InterestAndDiscount::Rate = 8.25; // %
InterestAndDiscount::Time = 5; // Years
InterestAndDiscount::Interest = InterestAndDiscount::Principal *
InterestAndDiscount::Discount *
InterestAndDiscount::Time;
InterestAndDiscount::MaturityValue = InterestAndDiscount::Principal +
InterestAndDiscount::Interest;
BuyAndSell::OriginalPrice = 250; // $
BuyAndSell::TaxRate = 16.00; // %
BuyAndSell::Discount = 20.00; // %
BuyAndSell::TaxAmount = BuyAndSell::OriginalPrice *
BuyAndSell::TaxRate / 100;
BuyAndSell::DiscountAmount = BuyAndSell::OriginalPrice *
BuyAndSell::Discount / 100;
BuyAndSell::NetPrice = BuyAndSell::OriginalPrice +
BuyAndSell::TaxAmount -
BuyAndSell::DiscountAmount;
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;
double Interest;
double Discount;
double MaturityValue;
namespace BuyAndSell
double OriginalPrice;
double TaxRate;
double TaxAmount;
double Discount;
double DiscountAmount;
double NetPrice;
int main()
Principal = 12500; // $
Rate = 8.25; // %
Time = 5; // Years
OriginalPrice = 250; // $
TaxRate = 16.00; // %
Discount = 20.00; // %
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
. . .
namespace BuyAndSell
. . .
int main()
. . .
. . .
return 0;
Before creating a “physical” scope, we saw that the compiler is able to point out what problem occurred at compilation time.
Fortunately, the compiler is able to explicitly designate what problem it encountered. In this case there is a conflict in name
resolution: two namespaces have a member of the same name.
The solution, which is commonly used, is to qualify the variable that is causing the conflict. You 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()
Principal = 12500; // $
Rate = 8.25; // %
Time = 5; // Years
OriginalPrice = 250; // $
TaxRate = 16.00; // %
BuyAndSell::Discount = 20.00; // %
return 0;
Nesting Namespaces
Nesting a namespace is the ability to include a namespace inside (as part of the body) of another namespace. To do this,
create the intended namespace as a member of the parent namespace. The nested namespace should have its own name and
its own body. Here is an example:
namespace BuyAndSell
double OriginalPrice;
double TaxRate;
double TaxAmount;
double Discount;
double DiscountAmount;
double NetPrice;
long ItemNumber;
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;
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;
return 0;
Following the same logic, you can have as many namespaces and as many nested namespaces in your application as you
desire. If you nest a namespace, you can use as many :: operators to qualify each member of the nested namespace 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()
. . .
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;
int main()
OriginalPrice = 780.50;
TaxRate = 7.55;
Discount = 25; // %
ItemNumber = 641238;
QualifyForDiscount = true;
Month = 10;
Day = 18;
Year = 2002;
cout << "\nReceipt Date: " << Month << "/" << Day << "/" << Year;
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 following additional libraries can be used to include C header files into a C++ program:
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;
#include <iostream.h>
#include <iostream>
Because this second technique is conform with the C++ Standard, we will use it whenever we need one of its libraries.
Introduction to Strings
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>
main()
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>
main()
char FirstName[12];
char LastName[12];
cout << "\nFull Name: " << FirstName << " " << LastName;
To request a group of words using an array, use one of the following functions:
To use the array variables, change the content of the file as follows:
#include <iostream>
main()
cin.getline(FirstName, 20);
cin.getline(LastName, 20);
cin.getline(Address, 40);
cout << "Describe the job performed on the customer's car in 100 words or less:\n";
cin.getline(JobPerformed, 80);
cout << "\nCustomer Name: " << FirstName << " " << LastName;
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>
main()
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>
main()
string MusicAlbum;
string TrackTitle;
cout << "Welcome to Radio Request where the listeners select their songs:\n";
getline(cin, MusicAlbum);
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
The following example uses the = symbol as the end character of the sentence:
string Address;
Here is an example:
#include <iostream>
#include <string>
main()
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>
main()
string Address;
string JobPerformed;
getline(cin, Address);
getline(cin, JobPerformed);
cout << "\nCustomer Name: " << FirstName << " " << LastName;
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.
-∞ -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>
main()
cout << "The value of the number is: " << Number << "\n";
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>
main()
cout << "The value of the first number is: " << Number1 << "\n";
cout << "The value of the second number is: " << Number2 << "\n";
return 0;
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.
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>
main()
&Number = 0012FED4
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:
#include <iostream>
main()
The ampersand operator between the data type and the variable name can assume one of three positions as follows:
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>
main()
return 0;
If you change the value of the variable, the compiler updates the value of the reference so that both variables would hold the
same value. In the same way, you can modify the value of the reference, which would update the value of the referred to
variable. To access the reference, do not use the ampersand operator; just the name of the reference is sufficient to the
compiler. This is illustrated in the following:
#include <iostream>
main()
Number = 4250;
Nbr = 38570;
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:
#include <iostream>
main()
double Price;
return 0;
There are four methods you can use with the sizeof operator: using the variable or the data type. The general syntaxes of
the sizeof operator are:
sizeof VariableName;
sizeof DataType;
sizeof(VariableName);
sizeof(DataType);
Any of these four formulas is admissible. But it is good to refrain from using the data type except in rare cases that you can
justify. The reason you should apply the sizeof operator on the variable is because, if you change the variable (the word
“variable” means it can change throughout the program), that is, if you perform any operation on it, the sizeof operator will
acknowledge that and render the right result. Some and most of the time, if you apply the sizeof operator on the data type,
you might end up with a bug; if you are lucky, the program would simply not compile.
Here is an example:
#include <iostream>
main()
cout << "The size of Period is " << SizeOf << " bytes\n\n";
#include <iostream>
main()
char iChar;
int iInt;
float iFloat;
double iDouble;
in Bytes
----------------------------------
char 1
unsigned char 1
signed char 1
int 4
short int 2
unsigned int 4
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
#include <iostream>
main()
char iChar;
int iInt;
float iFloat;
double iDouble;
Algebraic Operators
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:
#include <iostream>
main()
You can also add some values already declared and initialized in your program. Here is an example:
#include <iostream>
main()
int a = 244;
int b = 835;
cout << a << " + " << b << " = " << a + b;
You can also get the values from the user as illustrated in the following program:
#include <iostream>
main()
int a, b, c;
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:
#include <iostream>
main()
cout << Value1 << " - " << Value2 << " = " << Value3 << "\n\n";
#include <iostream>
main()
// Addition associativity
// Subtraction non-associativity
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
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.
When it comes to programming syntax, the rules we learned with the addition operation also apply to the multiplication.
Here is an example:
#include <instream>
main()
float a, b;
// Multiple of a and b.
cout << a << " * " << b << " = " << a * b;
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.
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:
#include <iostream>
main()
float a;
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:
#include <iostream>
main()
int YourPlayers;
cout << "\nOut of " << Players << " players, "
<< 26 % 11 << " players will have to wait when the "
cout << "\nOut of " << YourPlayers << " players, "
<< YourPlayers % 11 << " players will not have a team "
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:
// Using parentheses
#include <iostream>
main()
cout << "(154 - 12) + 8 = " << (154 - 12) + 8 << "\n";
cout << "154 - (12 + 8) = " << 154 - (12 + 8) << "\n";
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:
#include <iostream>
main()
Value = Value + 1;
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>
main()
Value++;
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>
main()
Value++;
Value++;
Value++;
Value = 12
Value = 13
Value = 14
Value = 15
#include <iostream>
using namespace std;
main()
{
int Value = 12;
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;
Value = 12
Value = 12
Value = 13
#include <iostream>
using namespace std;
main()
{
int Value = 8;
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;
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;
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;
Value = 8
Value = 8
Value = 7
#include <iostream>
using namespace std;
main()
{
double Value = 12.75;
double NewValue;
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;
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;
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.
The bitwise NOT is a unary operator that must be placed on the left side of its operand as in
~Value
To perform this operation, the compiler considers each bit that is part of the operand and inverts the value of each bit from 1
to 0 or from 0 to 1 depending on the value the bit is holding. This operation can be resumed in the following table:
Bit ~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
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:
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;
}
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:
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;
}
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:
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>
main()
cout << N1 << " ^ " << N2 << " = " << (N1 ^ N2) << "\n\n";
187 ^ 242 = 73
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:
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
#include <iostream>
main()
cout << Value << " << 2 = " << (Value << 2) << "\n\n";
42 << 2 = 168
Therefore, if you shift 42 to the right, the binary result would be 0000 1010, whose decimal value is 10.
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
#include <iostream>
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;
cout << "The integer " << i << " converted to a character "
cout << "The character " << a << " converted to an integer "
cout << "The long integer " << g << " converted to a character "
cout << "The float value " << f << " converted to an integer "
cout << "The double value " << d << " converted to a character "
iInt = g + i;
aChar = i + a;
dDouble = d + g;
cout << "The long integer " << g << " + " << " the integer "
cout << "The long integer " << g << " + " << " the integer "
cout << "The integer " << i << " + " << " the character "
cout << "The integer " << i << " + " << " the character "
cout << "The integer " << i << " * " << " the character "
cout << "The double " << d << " / " << " the character "
cout << "The double " << d << " + " << " the long integer "
The double 122.448 + the long integer 241 converted to an integer is 363
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.
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.
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:
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
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
string FirstName();
Here are examples of declaring functions; some take arguments, some don’t:
Defining Functions
In order to use a function in your program, you have to let the compiler know what the function does. Sometimes (depending
on where the function is located in your program), you will not have to declare the function before using it; but you must
always tell the compiler what behavior you are expecting.
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:
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:
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:
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:
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;
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()
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>
void Message()
main()
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.";
void Message()
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>
main()
getchar();
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 "
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;
When a function is of type void, it cannot be displayed on the same line with the cout extractor and it cannot be assigned to a
variable (since it does not return a value). Therefore, a void function can only be called.
Returning a Value
If you declare a function that is returning anything (a function that is not void), the compiler will need to know what value the
function returns. The return value must be the same type declared. The value is set with the return keyword.
If a function is declared as a char, make sure it returns a character (only one character). Here is an example:
char Answer()
char a;
cout << "Do you consider yourself a reliable employee (y=Yes/n=No)? ";
cin >> a;
return a;
A good function can also handle a complete assignment and only hand a valid value to other calling functions. Imagine you
want to process member’s applications at a sports club. You can define a function that would request the first and last names;
other functions that need a member’s full name would request it from such a function without worrying whether the name is
complete. The following function is in charge of requesting both names. It returns a full name that any desired function can
use:
string GetMemberName()
return FullName;
A return value could also be a variable that represents the result. Here is example:
double Area;
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>
int GetMajor()
int Choice;
return Choice;
main()
int 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>
main()
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>
int main()
return 0;
GetHours(FullName);
Here is an example:
#include <iostream>
#include <string>
string GetName()
return FN;
int main()
string FullName;
double Hours;
FullName = GetName();
Hours = GetHours(FullName);
cout << "\nWeekly Hours: " << Hours << " hours\n\n";
return 0;
return TotalHours;
Monday: 8.00
Tuesday: 8.50
Wednesday: 9.00
Thursday: 8.00
Friday: 8.00
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
Here is an example:
#include <iostream>
int main()
cout << "\nThe final price is: " << PurchasePrice(ItemPrice, TaxRate);
return 0;
double Price;
return Price;
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.
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>
int main()
Earnings(Hours, Rate);
return 0;
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.
ThisWeek = 42;
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:
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:
ThisWeek = 42;
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 OrigPrice;
Since this function expects an argument, if you do not supply it, the following program would not compile:
#include <iostream>
double OrigPrice;
int main()
double FinalPrice;
FinalPrice = CalculateNetPrice(Discount);
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>
double OrigPrice;
int main()
double FinalPrice;
FinalPrice = CalculateNetPrice();
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>
cout << "Discount Rate: " << Discount << "%" << endl;
return NetPrice;
int main()
double FinalPrice;
FinalPrice = CalculateNetPrice();
return 0;
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:
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>
double OrigPrice;
return NetPrice;
int main()
double FinalPrice;
FinalPrice = CalculateNetPrice(TaxRate);
return 0;
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.
Here is an example that calculates the moment of inertia with regard to the X axis:
#include <iostream>
// Rectangle
return b * h * h * h / 3;
int main()
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>
// Rectangle
return b * h * h * h / 3;
// Semi-Circle
double MomentOfInertia(double R)
return R * R * R * R * PI/ 8;
int main()
cout << "Moment of inertia of a semi-circle with regard to the X axis: ";
return 0;
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>
// Rectangle
return b * h * h * h / 3;
// Semi-Circle
double MomentOfInertia(double R)
return R * R * R * R * PI/ 8;
// Triangle
return b * h * h * h / 12;
int main()
cout << "\nTriangle\n" << "Moment of inertia with regard to the X axis: ";
return 0;
Constant Arguments
When a function receives an argument, it performs one of two actions with regards to the value of the argument; it may
modify the value itself or only use the argument to modify another argument or another of its own variables. If you know that
the function is not supposed to alter the value of an argument, you should let the compiler know. This is a safeguard that
serves at least two purposes. First, the compiler will make sure that the argument supplied stays intact; if the function tries
to modify the argument, the compiler would throw an error, letting you know that an undesired operation took place. Second,
this speeds up execution time.
To let the compiler know that the value of an argument must stay constant, use the const keyword before the data type of
the argument. For example, if you declare a function like void Area(const string Side), the Area() is not supposed to modify
the value of the Side argument. Consider a function that is supposed to calculate and return the perimeter of a rectangle if it
receives the length and the width from another function, namely main(). Here is a program that would satisfy the operation
(notice the Perimeter() function that takes two arguments):
int main()
cout << "\nThe perimeter of the rectangle is: " << Perimeter(Length, Width);
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:
You can make 0, just one, or more arguments constants, and there is no order on which arguments can be made constant.
Here is an example
#include <iostream>
// Rectangle
return b * h * h * h / 3;
// Semi-Circle
return R * R * R * R * PI/ 8;
// Triangle
return b * h * h * h / 12;
int main()
return 0;
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 Original;
Original = GetOriginalPrice();
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>
return NetPrice;
int main()
double Price;
double Original;
GetOriginalPrice(Original);
return 0;
Inline Functions
When you call a function B() from a function A(), function A() sends a request and must get to Function B(). Whenever your
program includes a small function, C++ allows you to include such a function where it is being called. When function B() calls
function A(), instead of sending a request fo funtion A(), the compiler would include a copy of function A() into funtion B()
where it is being called. Such a function (function A()) is qualified inline.
To create a function as inline, use the inline keyword when declaring the function as well as when defining it. Here is an
example that makes use of an inline function:
#include <iostream>
cout << "The area of the square is " << Side * Side;
int main()
float s;
cin >> s;
Area(s);
return 0;
Static Variables
#include <iostream>
void Starter(int y)
double a = 112.50;
double b = 175.25;
a = a / y;
b = b + 2;
int main()
Starter(2);
Starter(2);
Starter(2);
Starter(2);
return 0;
y = 2
a = 56.25
b = 177.25
b / a = 3.15111
y = 2
a = 56.25
b = 177.25
b / a = 3.15111
y = 2
a = 56.25
b = 177.25
b / a = 3.15111
y = 2
a = 56.25
b = 177.25
b / a = 3.15111
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:
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)
a = a / y;
b = b + 2;
y = 2
a = 56.25
b = 177.25
b / a = 3.15111
y = 2
a = 28.125
b = 179.25
b / a = 6.37333
y = 2
a = 14.0625
b = 181.25
b / a = 12.8889
y = 2
a = 7.03125
b = 183.25
b / a = 26.0622
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>
void Starter(int y)
a = a / y;
b = b + 2;
int main()
Starter(2);
Starter(5);
Starter(14);
Starter(25);
return 0;
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
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).
Value1 == Value2
The equality operation is used to find out whether two variables (or one variable and a constant) hold the same value. From
our syntax, the compiler would compare the value of Value1 with that of Value2. If Value1 and Value2 hold the same value,
the comparison produces a true result. If they are different, the comparison renders false or 0.
Most of the comparisons performed in C++ will be applied to conditional statements; but because a comparison operation
produces an integral result, the result of the comparison can be displayed on the monitor screen using a cout extractor. Here
is an example:
#include <iostream.h>
int main()
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()
cout << "Comparison of Value1 == 15 produces " << (Value1 == 15) << "\n\n";
return 0;
Value 1 = 15
Value 2 = 0
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.
!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()
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()
return 0;
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()
return 0;
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()
return 0;
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()
return 0;
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.
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.
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;
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:
This time, although the user can still type anything, at least you have specified the expected answers.
The Drivers
There are two main categories of people who deal with the traffic light: the drivers and the walkers. To
make our discussion a little simpler, we will consider only the driver. When the light is green, a driver
can drive through. When the light is red, the driver is required to stop and wait.
The Law
Rules and regulations dictate that when a driver does not obey the law by stopping to a red light, he is
considered to have broken the law and there is a consequence.
The most independent of the three entities is the traffic light. It does not think, therefore it does not make mistakes. It is
programmed with a timer or counter that directs it when to act, that is, when to change lights. The second entity, the driver,
is a human being who can think and make decisions based on circumstances that are beyond human understanding. A driver
can decide to stop at a green light or drive through a red light…
A driver who proceeds through a red light can get a ticket depending on one of two circumstances: either a police officer
caught him “hand-in-the-basket” or a special camera took a picture. Worse, if an accident happens, this becomes another
story.
The traffic light is sometimes equipped with a timer or counter. We will call it Timer T. It is equipped with three lights: Green,
Yellow, and Red. 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:
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:
One of the comparisons the computer performs is to find out if a statement is true (in reality, programmers (like you) write
these statements and the computer only follows your logic). If a statement is true, the computer acts on a subsequent
instruction.
The comparison using the if statement is used to check whether a condition is true or false. The syntax to use it is:
if(Condition) Statement;
If the Condition is true, then the compiler would execute the Statement. The compiler ignores anything else:
If the statement to execute is (very) short, you can write it on the same line with the condition that is being checked.
Consider a program that is asking a user to answer Yes or No to a question such as "Are you ready to provide your credit card
number?". A source file of such a program could look like this:
#include <iostream.h>
int main()
char Answer;
cout << "Are you ready to provide your credit card number(1=Yes/0=No)? ";
// 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";
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>
int main()
char Answer;
cout << "Are you ready to provide your credit card number(1=Yes/0=No)? ";
// Since the user is ready, let's process the credit card transaction
if(Answer == '1')
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];
cout << "Are you ready to provide your credit card number(1=Yes/0=No)? ";
// Since the user is ready, let's process the credit card transaction
if(Answer == '1')
cout << "\nPlease enter your credit card number without spaces: ";
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;
if(Number)
return 0;
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:
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
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
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;
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;
#include <iostream.h>
int main()
char Answer;
return 0;
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()
<< " and " << Num2 << " is " << Max;
return 0;
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;
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;
else
return 0;
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;
switch (Number)
case 1:
case 2:
case 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;
}
#include <iostream.h>
int main()
int Number;
switch (Number)
case 1:
case 2:
case 3:
default:
cout << endl << Number << " is out of the requested range.";
return 0;
while(Condition) Statement;
To execute this expression, the compiler first examines the Condition. If the Condition is true, then it executes the Statement.
After executing the Statement, the Condition is checked again. AS LONG AS the Condition is true, it will keep executing the
Statement. When or once the Condition becomes false, it exits the loop.
Here is an example:
int Number;
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:
#include <iostream.h>
int main()
int Number;// = 0;
Number++;
return 0;
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.
#include <iostream.h>
int main()
int Number = 0;
do
return 0;
If the Statement is long and should span more than one line, start it with an opening curly braket and end it with a closing
curly bracket.
The 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 {
return 0;
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.
#include <iostream.h>
int main()
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()
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:
#include <iostream.h>
int main()
int Count;
return 0;
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.
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 << "Could you please sit down for the next exercise?";
return 0;
Wonderful!!!
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 << "Could you please sit down for the next exercise?";
char 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 << "Could you please sit down for the next exercise?";
char WantToContinue;
if(WantToContinue == '1')
char LayOnBack;
cout << "Good. For the next exercise, you should lay on your back";
if(LayOnBack == '1')
else
else
return 0;
In the same way, you can nest statements as you see fit. The goal is to provide an efficient and friendly application. You can
insert and nest statements that provide valuable feedback to the user while minimizing boredom. The above version of the
program can be improved as followed:
#include <iostream.h>
int main()
char SittingDown;
do {
cout << "Could you please sit down for the next exercise?";
char WantToContinue;
if(WantToContinue == '1')
char LayOnBack;
cout << "Good. For the next exercise, you should lay on your back";
if(LayOnBack == '0')
char Ready;
do {
}while(Ready == '0');
else
else
return 0;
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()
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:
#include <iostream.h>
int main()
int Number;
switch (Number)
case 1:
break;
case 2:
break;
case 3:
break;
default:
cout << endl << Number << " is out of the requested range.";
return 0;
Even when using the break statement, the switch allows many case to execute as one. To do this, as we saw when not using
the break, type two cases together. This technique is useful when validating letters because the letters could be in uppercase
or lowercase. This illustrated in the following program:
#include <iostream.h>
int main()
char 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;
break;
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>
int main()
int EmplStatus;
switch( EmplStatus )
case esFullTime:
break;
case esPartTime:
break;
case esContractor:
break;
case esNS:
break;
default:
return 0;
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()
continue;
Sum += posNumber;
cout << "\nSum of the numbers you entered = " << Sum << "\n\n";
return 0;
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()
if( Count == 5 )
goto MamaMia;
MamaMia:
return 0;
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:
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
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
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;
if( Position == 1 )
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;
if( SittingDown == 1 )
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;
if( !(SittingDown == 1) )
cout << "\nCould you please sit down for the next exercise?\n";
return 0;
Let’s segment these expressions and give each a name. The first statement will be called L. Therefore,
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?
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 << "Good Choice. Now we will proceed with the toppings\n";
else
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 << "Could you please sit down for the next exercise?";
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:
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:
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;
else
return 0;
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 ||
char GetPosition()
char Position;
do {
return Position;
int main()
char Position;
Position = GetPosition();
cout << "\nCould you please sit down for the next exercise?\n";
else
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 ||
char GetPosition()
char Position;
do {
Position != 'N' )
Position != 'N' );
return Position;
void NextExercise()
char LayOnBack;
cout << "Good. For the next exercise, you should lay on your back";
if(LayOnBack == '0')
char Ready;
do {
}while(Ready == '0');
else
int main()
Position = GetPosition();
cout << "\nCould you please sit down for the next exercise?";
else
NextExercise();
else
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()
return true;
else
return false;
int main()
bool Answer;
Answer = GetAnswer();
else
return 0;
#include <iostream.h>
#define Or ||
string GetPosition()
char Position;
return "Yes";
return "No";
int main()
string Answer;
Answer = GetPosition();
return 0;
On paper, the function looks fine. If the user answers with y or Y, the function returns the string Yes. If the user answer with
n or N, the function returns the string No. Unfortunately, this function has a problem: what if there is an answer that does not
fit those we are expecting? In reality the values that we have returned in the function conform only to the conditional
statements and not to the function. Remember that in if(Condidion)Statement, the Statement executes only if the Condition
is true. Here is what will happen. If the user answers y or Y, the function returns Yes and stops; fine, it has returned
something, we are happy. If the user answers n or N, the function returns No, which also is a valid value: wonderful. If the
user enters another value (other than y, Y, n, or N), the execution of the function will not execute any of the return
statements and will not exit. This means the execution will reach the closing curly bracket without encountering a return
value. Therefore, the compiler will issue a warning. Although the warning looks like not a big deal, you should take care of it:
never neglect warnings. The solution is to provide a return value so that, if the execution reaches the end of the function, it
would still return something. Here is a solution to the problem:
#include <iostream.h>
#define Or ||
string GetPosition()
char Position;
return "Yes";
return "No";
int main()
string Answer;
Answer = GetPosition();
return 0;
This is illustrated in the following program that has two functions with conditional returns:
#include <iostream.h>
#define Or ||
char GetPosition()
char Position;
do {
Position != 'N' )
Position != 'N' );
return 'y';
return 'n';
return Position;
void NextExercise()
char LayOnBack;
cout << "Good. For the next exercise, you should lay on your back";
if(LayOnBack == '0')
char Ready;
do {
} while(Ready == '0');
else
return true;
return false;
return false;
int main()
bool SittingDown;
Position = GetPosition();
SittingDown = ValidatePosition(Position);
cout << "\nCould you please sit down for the next exercise?";
else
NextExercise();
else
return 0;
Introduction to Arrays
Introduction to Arrays
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.
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.
int Age[12];
float Grade[100];
double Angle[360];
int Age[12]; declares a group or array of 12 values, each one being an integer.
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:
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.
int Number[12] = {18, 42, 25, 12, 34, 15, 63, 72, 92, 26, 26, 12};
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};
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:
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>
int main()
return 0;
Using this approach, each member of the array can have its value accessed. Here is an example:
#include <iostream>
int main()
return 0;
Distance 1: 44.14
Distance 2: 720.52
Distance 3: 96.08
Distance 4: 468.78
Distance 5: 6.28
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>
int main()
return 0;
You can use such a constant in a for loop to scan the array and access each of its members. Here is an example:
#include <iostream>
int main()
cout << "Distance " << i + 1 << ": " << Distance[i] << endl;
return 0;
Distance 1: 44.14
Distance 2: 720.52
Distance 3: 96.08
Distance 4: 468.78
Distance 5: 6.28
We knew the dimensions of the arrays we have used so far, because we could count the number of members of the array.
Imagine you declare a large array, possibly made of 100 or 300 members, you wouldn't start counting the number of
members. C/C++ provides the sizeof operator that can be used to get the dimension of an array. The syntax you would use
is:
sizeof(ArrayName) / sizeof(DataType)
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:
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>
int main()
return 0;
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>
int main()
double Distance[NumberOfItems];
return 0;
Distance 1: -9.25596e+061
Distance 2: -9.25596e+061
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>
int main()
return 0;
Distance 1: 44.14
Distance 2: 720.52
Distance 3: 96.08
Distance 4: 0
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>
int main()
return 0;
Distance 1: 44.14
Distance 2: 720.52
Distance 3: 96.08
Distance 4: 468.78
Distance 5: 6.28
Distance 6: 2.64214e-308
Distance 7: 2.12414e-314
Distance 8: 1.00532e-307
Depending on the compiler you are using, you would also receive a (strong) warning.
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>
int main()
int Page[Counter];
return 0;
Book 1: 842
Book 4: 1204
Summary of books
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>
int main()
int Number[MAX];
int Sum = 0;
Sum += Number[i];
cout << "\n\nThe sum of these numbers is " << Sum << "\n\n";
return 0;
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>
int main()
int Numbers[] = {8, 25, 36, 44, 52, 60, 75, 89};
int Find;
int i, m = 8;
continue;
if (i == m)
cout << Find << " is not in the list" << endl;
else
return 0;
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:
#include <iostream>
int main()
int Numbers[] = {8, 25, 36, 44, 52, 60, 75, 89};
int a = 8;
Minimum = Numbers[i];
return 0;
You can use this same approach to get the maximum value of the members of an array. Here is an example:
#include <iostream>
int main()
int Numbers[] = {8, 25, 36, 44, 52, 60, 75, 89};
int a = 8;
Maximum = Numbers[i];
return 0;
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>
int main()
return 0;
cout << "\nDistance " << i + 1 << ": " << Member[i];
You don't have to specify the dimension of the array. This means that you can leave the square brackets empty:
#include <iostream>
int main()
return 0;
cout << "\nDistance " << i + 1 << ": " << Member[i];
We have already seen that when you declare an array, the compiler reserves an amount of memory space for the members
of the array. To locate these members, the compiler aligns them in a consecutive manner. For example (hypothetically), if a
member is located at 1804 Lockwood drive, the next member would be located at 1805 Lockwood Drive. This allows the
compiler not only to know where the members of a particular array are stored, but also in what block (like the block houses
of a city) the array starts. This means that, when you ask the compiler to locate a member of an array, the compiler starts
where the array starts and moves on subsequently until it finds the member you specified. If the compiler reaches the end of
the block but doesn't find the member you specified, it stops, instead of looking for it all over the computer memory.
Based on this, when you call a function that has an array as argument, the compiler only needs the name of the array to
process it. Therefore, the above function can be called as follows:
#include <iostream>
cout << "\nDistance " << i + 1 << ": " << Member[i];
int main()
DisplayTheArray(Distance);
return 0;
Distance 1: 44.14
Distance 2: 720.52
Distance 3: 96.08
Distance 4: 468.78
Distance 5: 6.28
The good scenario we have used so far is that we know the number of members of our array and we can directly use it in the
function that is passed the argument. Imagine that we want the function to know how many members the array has and we
want to let the function know while we are calling it, after all, in some circumstances, we will not always know how many
members we want the function to process. This should easily be done as follows:
#include <iostream>
cout << "\nDistance " << i + 1 << ": " << Member[i];
int main()
DisplayTheArray(Distance[3]);
return 0;
Unfortunately, this program will not compile. Remember, we saw that the compiler wants only the name of the array,
because the name by itself represents the whole array. Distance[3] is a specific value of a member of the array, it is not a
group of values. In other words, Distance[3] is the same as 468.78. It is as if we want to pass 468.78 as the value to be
treated and not as a subsequent group of values, because that is what an array is. Therefore, the compiler complains that
you are passing a value after you have specifically stated that the argument was a group of values and not a single value.
When you declare and define a function that takes an array as argument, if you plan to process the array, for example, if you
want the calling function to control the number of elements to be processed, you should/must pass another argument that
will allow the function to know how many members of the array would be considered. Such a function can be declared as
follows:
#include <iostream>
int main()
double Distance[] = {44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12};
DisplayTheArray(Distance, 5);
DisplayTheArray(Distance, SizeOfArray);
return 0;
cout << "\nDistance " << i + 1 << ": " << Member[i];
Distance 1: 44.14
Distance 2: 720.52
Distance 3: 96.08
Distance 4: 468.78
Distance 5: 6.28
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>
// This function process an array but starts and ends at specific positions
int main()
double Distance[] = {44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12};
DisplayTheArray(Distance, 2, 6);
return 0;
cout << "\nDistance " << i + 1 << ": " << Member[i];
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>
// This function process an array but starts and ends at specific positions
int main()
double Distance[] = {44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12};
DisplayTheArray(Distance, 2, 6);
return 0;
cout << "\nDistance " << i + 1 << ": " << Member[i];
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
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:
#include <iostream>
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};
return 0;
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:
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:
};
#include <iostream>
int main()
// A 2-Dimensional array
double Distance[][4] = {
};
cout << "\nDistance [" << i << "][" << j << "]: " << Distance[i][j];
return 0;
Multidimensional Arrays
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:
This program would give you the address of the declared variable:
#include <iostream.h>
int main()
int Value;
<< &Value;
return 0;
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:
Only the first variable is a pointer, the second is a regular variable. If you want to declare different variables, you use:
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;
return 0;
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
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()
cout << "Value lives at: " << Value << "\n";
return 0;
#include <iostream.h>
int main()
int *Pointer;
cout << "Value lives at: " << Value << "\n";
Pointer = &Value;
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;
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;
Value = 35;
return 0;
As you know now, both *Pointer and Value have the same value. This allows you to change the value of the pointer directly and affect
the main variable meanwhile. Therefore, you can safely change the value of the pointer and it will be assigned accordingly.
To see an example, make the following change to the file:
#include <iostream.h>
int main()
int Value;
int *Pointer;
Pointer = &Value;
Value = 26;
Value = 35;
*Pointer = 144;
return 0;
Value = 26
*Pointer = 26
Value = 35
*Pointer = 35
Value = 144
*Pointer = 144
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;
return 0;
#include <iostream.h>
int main()
int Students;
int *ptrStudents;
ptrStudents = &Students;
return 0;
Number of students: 24
Number of students: 24
That is: 24 students
In the same way, you can request a value from the user and store it in the pointer. To see an example, make the following change to
the file:<
#include <iostream.h>
int main()
int Students;
int *ptrStudents;
ptrStudents = &Students;
return 0;
Of course, you can use various pointers on the same program. Apply an example by making the following changes:
#include <iostream.h>
int main()
int Boys;
int Girls;
int *ptrBoys;
int *ptrGirls;
ptrBoys = &Boys;
ptrGirls = &Girls;
return 0;
We have learned how to perform algebraic calculations and expressions in C++. When performing these operations on pointers,
remember to use the * for each pointer involved. The calculations should be as smooth:
#include <iostream.h>
int main()
int Boys;
int Girls;
int Total;
int *ptrBoys;
int *ptrGirls;
int *ptrTotal;
ptrBoys = &Boys;
ptrGirls = &Girls;
ptrTotal = &Total;
cout << "\nThere are " << *ptrTotal << " students";
return 0;
Boys: 26
That is: 26 students
Girls: 24
That is: 24 students
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.
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.
#include <iostream.h>
int main()
int Pants = 5;
return 0;
Shirts = 12
Pants = 5
#include <iostream.h>
int main()
int Shirts = 3;
int Pants = 5;
Deposit(Shirts, Pants);
return 0;
s = 8;
p = 12;
Shirts = 3
Pants = 5
Within Deposit()
Shirts = 8
Pants = 12
Shirts = 3
Pants = 5
To pass pointer arguments, use the asterisks when declaring the function, and use the ampersand & when calling the function. Here is
an example:
#include <iostream.h>
int main()
int Pants = 5;
Deposit(Shirts, Pants);
Pickup(&Shirts, &Pants);
return 0;
s = 8; p = 5;
*sht = 26;
*pt = 17;
Shirts = 12
Pants = 5
Within Deposit()
Shirts = 8
Pants = 5
Shirts = 12
Pants = 5
Within Pickup()
Shirts = 26
Pants = 17
Shirts = 26
Pants = 17
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:
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:
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;
#include <iostream.h>
int main()
return 0;
Now, let's add a pointer and try to access it without initializing it:
#include <iostream.h>
int main()
int* Age;
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.
#include <iostream.h>
int main()
int* Age;
Age = &StudentAge;
return 0;
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;
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;
*Age = 15;
return 0;
*Age = -858993460
Student age = 15
*Age = 15
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;
*Age = 15;
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 = 17;
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;
*Age = 15;
*Age = 17;
delete Age;
return 0;
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:
cout << "The name is " << L1 << L2 << L3 << L4 << L5;
#include <iostream>
int main()
cout << "The name is " << L1 << L2 << L3 << L4 << L5;
return 0;
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:
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:
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:
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>
int main()
return 0;
Color = Black
Country = Swaziland
#include <iostream>
int main()
char FirstName[20];
char MI;
char LastName[20];
cout << "\nFull Name: " << FirstName << " " << MI << ". " << LastName;
return 0;
Middle Initial: J
Member Information
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:
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>
int main()
char Author[40];
char Title[40];
char Publisher[50];
cin.getline(Author, 40);
cin.getline(Title, 40);
cin.getline(Publisher, 50);
return 0;
Book Collection
Book Information
#include <iostream>
int main()
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>
int main()
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>
int main()
double *Value;
Value = 12.55;
return 0;
On the other hand, the following declaring of an array of characters and its later initialization is perfectly legal:
#include <iostream>
int main()
char *Country;
return 0;
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:
After declaring such a variable, you can assign it any value you want. Here is an example:
#include <iostream>
int main()
return 0;
#include <iostream>
int main()
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>
int main()
ShowCountry(Country);
return 0;
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>
char *GetFirstName()
gets(FName);
return FName;
int main()
char *FirstName;
FirstName = GetFirstName();
return 0;
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>
int main()
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>
int main()
return 0;
In the same way, make sure that each item of the array has a number of characters (or letters) that is equal to or less than
the second dimension. The following program will not compile because two items of the array (the 1st and the last) have
more than 10 letters after you had declared that the maximum number of letters of each item of the arrays would be 10
characters:
#include <iostream>
int main()
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>
int main()
return 0;
Countries Names
Country 2: Australia
Country 3: Zimbabwe
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>
int main()
cout << "\nCountry " << i + 1 << ": " << Country[i];
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>
int main()
cout << "\nCountry " << i + 1 << ": " << Country[i];
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:
We also saw earlier that the name of an represents the address of the variable. In the same way, you do not have to find the
item that has the highest number of characters and specify it as the second dimension of the array. You can let the compiler
figure out this by letting the square brackets empty. By your initializing the array, the compiler would figure out how much
space each item needs. Therefore, the above array can be declared as follows:
#include <iostream>
int main()
cout << "\nCountry " << i + 1 << ": " << Country[i];
return 0;
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>
cout << "\nCountry " << i + 1 << ": " << S[i];
int main()
ShowCountries(Country);
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>
cout << "\nCountry " << i + 1 << ": " << S[i];
int main()
ShowCountries(Country, 6);
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>
cout << "\nCountry " << i + 1 << ": " << S[i];
int main()
ShowCountries(Country, 6);
return 0;
Alternatively, when declaring and when defining the function, you can specify that the argument is a pointer to char:
#include <iostream>
cout << "\nCountry " << i + 1 << ": " << S[i];
int main()
ShowCountries(Country, 6);
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.
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:
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>
int main()
return 0;
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>
int main()
strcat(Make, Model);
cout << "\n\nAfter concatenating, Make = " << Make << endl;
return 0;
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>
int main()
return 0;
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.
char CarName[20];
If you have two strings and copy one into another, both strings would hold the same value:
#include <iostream>
int main()
strcpy(CarName2, CarName1);
return 0;
The Number argument specifies the number of characters that will be copied from the Source string. Here is an example:
#include <iostream>
int main()
return 0;
This function takes as an argument the string you want to duplication and returns the duplicated string.
#include <iostream>
int main()
char *LastName2;
LastName2 = strdup(LastName1);
cout << "Father: " << FirstName1 << ' ' << LastName1 << endl;
cout << "Son: " << FirstName2 << ' ' << LastName2;
return 0;
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.
This function takes two strings, S1 and S2 and compares them. It returns
#include <iostream>
int main()
<< " and " << FirstName2 << " is\t" << Value1 << endl;
<< " and " << FirstName1 << " is\t" << Value2 << endl;
<< " and " << LastName2 << " is\t" << Value3;
return 0;
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:
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
This function takes two strings, S1 and S2 and compares them. It returns
This function takes two strings, S1 and S2 and compares them. It returns
The strchr() function looks for the first occurrence of a certain character in a string. Its syntax is:
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 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.
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.
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>
int main()
return 0;
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>
int main()
char *SayItLoud;
cout << "What is that drink? " << Drink << endl;
SayItLoud = strupr(Drink);
return 0;
Formatting Strings
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:
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>
int main()
double a, b, c;
cin >> a;
cin >> b;
c = a * b;
cout << "\n" << a << " * " << b << " = " << c << "\n\n";
return 0;
This is a classic easy program. When it comes up, the user is asked to simply type two numbers; the program would use
them to perform a multiplication and display the result.
Imagine that a user, thanks to his infinite creativity or because of just a mistake, decides to type the name of a country or
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:
try {
catch(Argument)
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>
int main()
int StudentAge;
try {
if(StudentAge < 0)
throw;
catch(...)
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>
int main()
try {
if( Number2 == 0 )
throw;
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:
#include <iostream.h>
int main()
int StudentAge;
try {
if(StudentAge < 0)
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:
#include <iostream>
int main()
cout << "This program allows you to perform a division of two numbers\n";
try {
if( Operand2 == 0 )
cout << "\n" << Operand1 << " / " << Operand2 << " = " << Result << "\n\n";
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()
cout << "This program allows you to perform a division of two numbers\n";
try {
if( Operand2 == 0 )
throw 0;
cout << "\n" << Operand1 << " / " << Operand2 << " = " << Result << "\n\n";
cout << "\nBad Operator: Division by " << n << " not allowed\n\n";
return 0;
try {
Code to Try
catch(Arg1)
One Exception
catch(Arg2)
Another Exception
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()
char Operator;
cout << "This program allows you to perform an operation on two numbers\n";
switch(Operator)
case '+':
break;
case '-':
break;
case '*':
break;
case '/':
break;
default:
cout << "\n" << Operand1 << " " << Operator << " "
return 0;
This program works fine as long as the user types a valid sequence of values made of a number followed by a valid arithmetic
operator, followed by a number. Anything else, such as an invalid number, an unexpected operator, or a wrong sequence
(such as Number Number Operator), would produce an unpredictable outcome. Obviously various bad things could happen
when this program is running.
To handle the exceptions that this program could produce, you can start with the most likely problem that would occur.
Trusting that a user is able to provide the two numbers that are requested, it is possible that she would type an invalid
operator. For example, for this program we will perform only the addition (+), the subtraction(-), the multiplication(*), and
the division(/). Therefore, we will first validate the operator. This can be done as follows:
#include <iostream>
#include <string>
int main()
char Operator;
cout << "This program allows you to perform an operation on two numbers\n";
try {
throw Operator;
switch(Operator)
case '+':
break;
case '-':
break;
case '*':
break;
case '/':
break;
cout << "\n" << Operand1 << " " << Operator << " "
catch(const char n)
cout << "\nOperation Error: " << n << " is not a valid operator";
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:
#include <iostream.h>
int main()
char Operator;
cout << "This program allows you to perform a division of two numbers\n";
try {
throw Operator;
if(Operator == '/')
if(Operand2 == 0)
throw 0;
switch(Operator)
case '+':
break;
case '-':
break;
case '*':
break;
case '/':
break;
cout << "\n" << Operand1 << " " << Operator << " "
catch(const char n)
cout << "\nOperation Error: " << n << " is not a valid operator\n\n";
catch(const int p)
cout << "\nBad Operation: Division by " << p << " not allowed\n\n";
return 0;
When running this program, if the user types a wrong operator, the compiler considers the integer error, gets out f the try
block, and looks for a catch that can use a character. The first catch can validate it and gets executed.
If the user enters the right values (Number Operator Number), then the compiler finds out if the operator entered was a
forward slash “/” used to perform a division. If the user wants to 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>
int main()
char Operator;
cout << "This program allows you to perform a division of two numbers\n";
try {
Operand1 = atof(Number1);
Operand2 = atof(Number2);
throw Operator;
if(Operator == '/')
if(Operand2 == 0)
throw 0;
switch(Operator)
case '+':
break;
case '-':
break;
case '*':
break;
case '/':
break;
cout << "\n" << Operand1 << " " << Operator << " "
catch(const int n)
cout << "\nBad Operation: Division by " << n << " not allowed\n\n";
catch(const char n)
cout << "\nOperation Error: " << n << " is not a valid operator\n\n";
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>
int main()
char Operator;
cout << "This program allows you to perform an operation on two numbers\n";
try {
Operand1 = atof(Number1);
Operand2 = atof(Number2);
throw Operator;
switch(Operator)
case '+':
break;
case '-':
break;
case '*':
break;
case '/':
try {
if(Operand2 == 0)
break;
catch(const char n)
cout << "\nOperation Error: " << n << " is not a valid operator";
cout << "\nError: " << BadOperand << " is not a valid number";
return 0;
#include <iostream.h>
int main()
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 << "\n" << Operand1 << " " << Operator << " "
return 0;
double Calculator(const double Oper1, const double Oper2, const char Symbol)
double Value;
switch(Symbol)
case '+':
break;
case '-':
break;
case '*':
break;
case '/':
break;
return Value;
You can still use regular functions along with functions that handle exceptions. Here is an example:
#include <iostream>
#include <string>
double Calculator(const double N1, const double N2, const char p);
int main()
char Operator;
cout << "This program allows you to perform an operation on two numbers\n";
try {
Operand1 = atof(Number1);
Operand2 = atof(Number2);
throw Operator;
if(Operator == '/')
if(Operand2 == 0)
throw 0;
cout << "\n" << Operand1 << " " << Operator << " "
catch(const int n)
cout << "\nBad Operation: Division by " << n << " not allowed";
catch(const char n)
cout << "\nOperation Error: " << n << " is not a valid operator";
cout << "\nError: " << BadOperand << " is not a valid number";
return 0;
double Calculator(const double Oper1, const double Oper2, const char Symbol)
double Value;
switch(Symbol)
case '+':
break;
case '-':
break;
case '*':
break;
case '/':
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>
int main()
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 {
Operand1 = atof(Number1);
Operand2 = atof(Number2);
throw Operator;
catch(const char n)
cout << "\nOperation Error: " << n << " is not a valid operator";
cout << "\nError: " << BadOperand << " is not a valid number";
return 0;
void Calculator(const double Oper1, const double Oper2, const char Symbol)
double Value;
switch(Symbol)
case '+':
break;
case '-':
break;
case '*':
break;
case '/':
try {
if(Oper2 == 0)
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()
cout << "This program allows you to perform a division of two numbers\n";
try {
if( Operand2 == 0 )
cout << "\n" << Operand1 << " / " << Operand2 << " = " << Result;
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>
int main()
cout << "This program allows you to perform a division of two numbers\n";
// Start an exception
try {
Division(Operand1, Operand2);
return 0;
double Result;
// If an exception occurred,
Result = a / b;
cout << "\n" << a << " / " << b << " = " << Result;
In this program, the Division function receives two values that it is asked to perform and division with. The Division function
analyzes the second argument that represents the denominator. If this argument is zero, an exception is fund and the
Division functions throws a string back to the function that sent the arguments.
C++ (as described in the C++ Standards), allows you to specify that a function is an exception carrier. If you write a function
that carries an exception, you can type the throw keyword followed by parentheses on the right side of the function. Here is
an example:
#include <iostream.h>
int main()
cout << "This program allows you to perform a division of two numbers\n";
// Start an exception
try {
Division(Operand1, Operand2);
return 0;
double Result;
// If an exception occurred,
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>
int main()
char Operator;
cout << "This program allows you to perform an operation on two numbers\n";
try {
throw Number1;
Operand1 = atof(Number1);
throw Number2;
Operand2 = atof(Number2);
throw Operator;
try {
catch(const char n)
cout << "\nOperation Error: " << n << " is not a valid operator";
cout << "\nError: " << BadOperand << " is not a valid number";
return 0;
double Value;
switch(Symbol)
case '+':
break;
case '-':
break;
case '*':
break;
case '/':
if(Oper2 == 0)
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;
throw Symbol;
switch(Symbol)
case '+':
break;
case '-':
break;
case '*':
break;
case '/':
if(Oper2 == 0)
break;
return Value;
As you can see, this function throws two different types of exceptions: a character and a string. When writing such a function
that throws, but 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>
int main()
char Operator;
cout << "This program allows you to perform an operation on two numbers\n";
try {
Operand1 = Validate(Number1);
Operand2 = Validate(Number2);
try {
catch(const char n)
cout << "\nOperation Error: " << n << " is not a valid operator";
cout << "\nError: " << BadOperand << " is not a valid number";
return 0;
double Value;
throw Symbol;
switch(Symbol)
case '+':
break;
case '-':
break;
case '*':
break;
case '/':
if(Oper2 == 0)
break;
double Valid;
throw N;
Valid = atof(N);
return Valid;
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:
And the program that defines a shoe box object could be:
#include <iostream>
#include <iomanip>
#include <string>
int main()
cout << "\n\tLength = " << Length << "\n\tWidth = " << Width
<< "\n\tHeight = " << Height << "\n\tVolume = " << Length * Width * Height
<< "\n\tColor = " << Color << "\n\tSize = " << ShoeSize << "\n\n";
return 0;
Length = 12.55
Width = 6.32
Height = 8.74
Volume = 693.22
Size = 10.50
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{};
class ClassName {
};
or
class ClassName
{
};
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
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:
string Color;
private:
float ShoeSize;
};
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:
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:
or you can request its value from the user, using the cin operator. Here is an example:
Using the cout extractor to display the values of the object members, our program could be as follows:
#include <iostream>
#include <string>
class ShoeBox
public:
string Color;
private:
float ShoeSize;
};
int main()
<< "\n\n";
return 0;
At this time, because of trying to access a private member, the program would produce the following error
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...
#include <iostream>
#include <string>
class ShoeBox
public:
string Color;
float ShoeSize;
private:
};
int main()
ShoeBox Shake;
Shake.Length = 12.55;
Shake.Width = 6.32;
Shake.Height = 8.74;
Shake.ShoeSize = 10.50;
return 0;
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>
class ShoeBox
public:
string Color;
float ShoeSize;
private:
};
int main()
return 0;
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.
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;
};
There are at least two techniques you can use to implement a method member
#include <string>
class ShoeBox
public:
float ObtainShoeSize();
double CalcVolume()
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.
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.
class ShoeBox
public:
float ObtainShoeSize();
double CalcVolume();
string Color;
private:
double Length;
double Width;
double Height;
};
double ShoeBox::CalcVolume()
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:
class ShoeBox
public:
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:
void Display();
private:
double Length;
double Width;
double Height;
string Color;
};
On the other hand, if you omit the inline keyword, the C++ compiler would take care of it. Normally, any function
implemented in the body of the class is considered inline.
#include <iostream>
#include <string>
class ShoeBox
public: . . .
};
void ShoeBox::Display()
Length = 12.55;
Width = 6.32;
Height = 8.74;
duble ShoeBox::CalcVolume()
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
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:
In the Display() method, we could display the area of the length by the height using:
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:
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:
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:
#include <iostream>
#include <string>
class ShoeBox
public:
double CalcVolume()
float CalcShoeSize()
void Display();
private:
double Length;
double Width;
double Height;
char Color[32];
};
cout << "\nThe area of the " << N << " side is: " << S1 * S2;
void ShoeBox::Display()
Length = 10.42;
Width = 5.28;
Height = 5.88;
<< Length << " * " << Height << " * " << Width;
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:
The CalcVolume() and the CalcShoeSize() methods do not modify the member variables they receive. You can reinforce this
by declaring them as const:
When implementing the method, type the const keyword on the right side of the method’s closing parenthesis:
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:
void Display();
private:
double Length;
double Width;
double Height;
string Color;
};
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();
void GetHourlySalary();
void CalcTotalHours();
void Display();
void CalcNetPay()
else
NetPay = GrossPay;
private:
void CalcGrossPay();
string FirstName;
string LastName;
double TotalHours;
double HourlySalary;
double WeeklySalary;
double GrossPay;
double NetPay;
};
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).
#include <iostream>
#include <string>
class ShoeBox
public:
void Display();
private:
double Length;
double Width;
double Height;
string Color;
};
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"
cout << "\nThe area of the " << N << " side is = " << S1 * S2;
void ShoeBox::Display()
Length = 14.32;
Width = 8.36;
Height = 6.54;
<< Length << " * " << Height << " * "
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;
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>
struct TBrick
public:
private:
double Length;
double Height;
double Width;
};
//---------------------------------------------------------------------------
Length = l;
Height = h;
Width = w;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TBrick RedBrick;
RedBrick.Properties();
return 0;
//---------------------------------------------------------------------------
Length = 124.45
Height = 56.25
Thickness = 32.55
Volume = 227860.17
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:
//---------------------------------------------------------------------------
TBrick GoneSand;
GoneSand.Properties();
return 0;
//---------------------------------------------------------------------------
Length: 8.95
Height: 6.85
Width: 6.25
Length = 8.95
Height = 6.85
Thickness = 6.25
Volume = 383.17
Initializing an Object
1. To create a new project, on the main menu, click File -> New or File -> New -> Other...
2. On the New Items dialog box, double-click Console Wizard.
3. On the Console Wizard dialog box, make sure the C++ radio button is selected. In the right section, click only the Console
Application check box and click OK.
4. To save the project, on the Standard toolbar, click the Save All button.
5. Click the Create New Folder button, type Students2 and press Enter twice to put the new folder name in the Save In combo
box.
6. Change the File Name content to Main and press Enter.
7. For the name of the project, type Student and press Enter.
8. To add a new unit, on the main menu, click File -> New or File -> New -> Other...
9. In the New Items dialog box, double-click Unit.
10. To save the unit, on the Standard toolbar, click the Save button.
11. Type Students as the unit name and press Enter.
12. Click the Students.h tab and change its content as follows:
//---------------------------------------------------------------------------
#ifndef StudentsH
#define StudentsH
#include <string>
//---------------------------------------------------------------------------
class TStudent
public:
void Display();
private:
string FirstName;
string LastName;
int DayOfBirth;
int MonthOfBirth;
int YearOfBirth;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include <iostream>
#include "Students.h"
//---------------------------------------------------------------------------
FirstName = fn;
LastName = ln;
DayOfBirth = DOB;
MonthOfBirth = MOB;
YearOfBirth = YOB;
//---------------------------------------------------------------------------
void TStudent::Display()
cout << "\nFull Name: " << FirstName << " " << LastName;
<< "/" << MonthOfBirth << "/" << YearOfBirth << "\n";
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
#include "Students.h"
//---------------------------------------------------------------------------
void Exit()
//---------------------------------------------------------------------------
TStudent FirstGrade;
FirstGrade.Display();
Exit();
return 0;
//---------------------------------------------------------------------------
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>
//---------------------------------------------------------------------------
struct TBook
public:
TBook(); // Constructor
};
//---------------------------------------------------------------------------
TBook::TBook()
//---------------------------------------------------------------------------
TBook B;
return 0;
//---------------------------------------------------------------------------
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:
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.
//---------------------------------------------------------------------------
#ifndef BricksH
#define BricksH
//---------------------------------------------------------------------------
struct TBrick
public:
double CementVolume();
void ShowProperties();
private:
double Length;
double Height;
double Thickness;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include "Bricks.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TBrick::TBrick()
//---------------------------------------------------------------------------
Length = l;
Height = h;
Thickness = t;
//---------------------------------------------------------------------------
double TBrick::CementVolume()
double Enclosure = 0.50; // This includes both walls of the brick itself
return ValidVolume;
//---------------------------------------------------------------------------
void TBrick::ShowProperties()
}//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
#include "Bricks.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TBrick Foundation;
Foundation.ShowProperties();
return 0;
//---------------------------------------------------------------------------
Length = 4.24
Height = 3.55
Thickness = 3.45
//---------------------------------------------------------------------------
#ifndef StudentsH
#define StudentsH
#include <string>
//---------------------------------------------------------------------------
class TStudent
public:
TStudent();
void Display();
private:
string FirstName;
string LastName;
int DayOfBirth;
int MonthOfBirth;
int YearOfBirth;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include <iostream>
#include "Students.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TStudent::STudent()
//---------------------------------------------------------------------------
FirstName = fn;
LastName = ln;
DayOfBirth = DOB;
MonthOfBirth = MOB;
YearOfBirth = YOB;
//---------------------------------------------------------------------------
void TStudent::Display()
cout << "\nFull Name: " << FirstName << " " << LastName;
<< "/" << MonthOfBirth << "/" << YearOfBirth << "\n";
//---------------------------------------------------------------------------
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:
//---------------------------------------------------------------------------
#ifndef BricksH
#define BricksH
//---------------------------------------------------------------------------
struct TBrick
public:
double CementVolume();
void ShowProperties();
private:
double Length;
double Height;
double Thickness;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include "Bricks.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TBrick::TBrick()
//---------------------------------------------------------------------------
Length = l;
Height = h;
Thickness = t;
//---------------------------------------------------------------------------
double TBrick::CementVolume()
double Enclosure = 0.50; // This includes both walls of the brick itself
return ValidVolume;
//---------------------------------------------------------------------------
void TBrick::ShowProperties()
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
#include "Bricks.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
Solid.ShowProperties();
return 0;
//---------------------------------------------------------------------------
Length = 4.15
Height = 3.35
Thickness = 3.05
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:
//---------------------------------------------------------------------------
#ifndef BricksH
#define BricksH
//---------------------------------------------------------------------------
struct TBrick
public:
double CementVolume();
void ShowProperties();
private:
double Length;
double Height;
double Thickness;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include "Bricks.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TBrick::TBrick()
//---------------------------------------------------------------------------
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
return ValidVolume;
//---------------------------------------------------------------------------
void TBrick::ShowProperties()
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
#include "Bricks.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
Solid.ShowProperties();
return 0;
//---------------------------------------------------------------------------
Length = 4.15
Height = 3.35
Thickness = 3.05
//---------------------------------------------------------------------------
#ifndef StudentsH
#define StudentsH
#include <iostream>
//---------------------------------------------------------------------------
class TStudent
public:
void Display();
private:
string FirstName;
string LastName;
int DayOfBirth;
int MonthOfBirth;
int YearOfBirth;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include "Students.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
FirstName = fn;
LastName = ln;
DayOfBirth = DOB;
MonthOfBirth = MOB;
YearOfBirth = YOB;
//---------------------------------------------------------------------------
void TStudent::Display()
cout << "\nFull Name: " << FirstName << " " << LastName;
<< "/" << MonthOfBirth << "/" << YearOfBirth << "\n";
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
#include "Students.h"
//---------------------------------------------------------------------------
void Exit()
//---------------------------------------------------------------------------
SecondGrade.Display();
Exit();
return 0;
//---------------------------------------------------------------------------
Characteristics of this student Full Name: John Doe Date of Birth: 1/1/1990Press any key to continue...
5. Return to your programming environment.
Constructor Overloading
Like an ordinary method, a construction can be overloaded. This means that you can have different constructors following the rules
of overloading a function. Since we saw that a constructor can be used to initialize the member variables of its object, you can use
multiple constructors to apply different initializations.
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>
#include "Bricks.h"
//---------------------------------------------------------------------------
TBrick::TBrick()
//---------------------------------------------------------------------------
double TBrick::CementVolume()
double Enclosure = 0.50; // This includes both walls of the brick itself
return ValidVolume;
//---------------------------------------------------------------------------
void TBrick::ShowProperties()
//---------------------------------------------------------------------------
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:
//---------------------------------------------------------------------------
#include <iostream>
#include "Bricks.h"
//---------------------------------------------------------------------------
TBrick Mango;
Mango.ShowProperties();
return 0;
//---------------------------------------------------------------------------
Length = nan
Height = 2.53988e-314
Thickness = 2.122e-314
To make sure that a calling function does not have to supply values for the member variables, you can also use the empty
constructor to supply default values to these variables. If you simply use the default constructor to get the values of the member
variables, the object would use the values given in the empty constructor and perform all necessary operations:
TBrick::TBrick()
Length = 4.15;
Height = 3.55;
Thickness = 3.75;
Length = 4.15
Height = 3.55
Thickness = 3.75
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:
//---------------------------------------------------------------------------
#ifndef BricksH
#define BricksH
//---------------------------------------------------------------------------
class TBrick
public:
TBrick();
TBrick(double L);
double CementVolume();
void ShowProperties();
private:
double Length;
double Height;
double Thickness;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include <iostream>
#include "Bricks.h"
//---------------------------------------------------------------------------
TBrick::TBrick()
Length = 4.15;
Height = 3.55;
Thickness = 3.75;
//---------------------------------------------------------------------------
TBrick::TBrick(double L)
Length = L;
Height = 5.25;
Thickness = 4.55;
//---------------------------------------------------------------------------
double 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:
//---------------------------------------------------------------------------
#include <iostream>
#include "Bricks.h"
//---------------------------------------------------------------------------
TBrick Mather;
Mather.ShowProperties();
TBrick BedTimer(5.55);
BedTimer.ShowProperties();
return 0;
//---------------------------------------------------------------------------
Length = 4.15
Height = 3.55
Thickness = 3.75
Length = 5.55
Height = 5.25
Thickness = 4.55
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:
//---------------------------------------------------------------------------
#ifndef BricksH
#define BricksH
//---------------------------------------------------------------------------
class TBrick
public:
TBrick();
TBrick(double L);
double CementVolume();
void ShowProperties();
private:
double Length;
double Height;
double Thickness;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
Length = L;
Height = h;
Thickness = t;
}//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
#include "Bricks.h"
//---------------------------------------------------------------------------
TBrick GrayMatte;
GrayMatte.ShowProperties();
TBrick OldTimer(5.55);
OldTimer.ShowProperties();
Fantasma.ShowProperties();
return 0;
//---------------------------------------------------------------------------
Length = 4.15
Height = 3.55
Thickness = 3.75
Length = 5.55
Height = 5.25
Thickness = 4.55
Length = 3.25
Height = 3.05
Thickness = 3.25
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:
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>
#include "Bricks.h"
//---------------------------------------------------------------------------
TBrick GrayMatte;
GrayMatte.ShowProperties();
Fantasma.ShowProperties();
return 0;
//---------------------------------------------------------------------------
Therefore, if you want to access a default constructor of an object, you have two alternatives:
● If you don't create any constructor at all on an object, the default constructor would always be available whenever you
invoke that object.
● If you create at least one constructor on an object and supply at least one argument to that constructor, you must explicitly
create a default constructor for your object.
Based on what we have learned already, here is our complete program with set and get methods.
//---------------------------------------------------------------------------
#ifndef BricksH
#define BricksH
//---------------------------------------------------------------------------
class TBrick
public:
TBrick();
TBrick(double L);
double CementVolume();
void ShowProperties();
private:
double Length;
double Height;
double Thickness;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#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;
//---------------------------------------------------------------------------
Length = L;
Height = h;
Thickness = t;
//---------------------------------------------------------------------------
return Length;
//---------------------------------------------------------------------------
Length = l;
//---------------------------------------------------------------------------
return Height;
//---------------------------------------------------------------------------
Height = h;
//---------------------------------------------------------------------------
return Thickness;
//---------------------------------------------------------------------------
Thickness = t;
//---------------------------------------------------------------------------
double TBrick::CementVolume()
double Enclosure = 0.50; // This includes both walls of the brick itself
return ValidVolume;
//---------------------------------------------------------------------------
void TBrick::ShowProperties()
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
#include "Bricks.h"
//---------------------------------------------------------------------------
TBrick GrayMatte;
GrayMatte.ShowProperties();
TBrick OldTimer(5.55);
OldTimer.ShowProperties();
Fantasma.ShowProperties();
return 0;
//---------------------------------------------------------------------------
Length = 4.15
Height = 3.55
Thickness = 3.75
Length = 5.55
Height = 5.25
Thickness = 4.55
Length: 6.25
Height: 5.85
Thickness: 4.55
Length = 6.25
Height = 5.85
Thickness = 4.55
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();
void Display();
private:
string FirstName;
string LastName;
int DayOfBirth;
int MonthOfBirth;
int YearOfBirth;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
_fastcall TStudent::TStudent()
FirstName = "Paul";
LastName = "Kamus";
DayOfBirth = 28;
MonthOfBirth = 5;
YearOfBirth = 1986;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
#include "Students.h"
//---------------------------------------------------------------------------
void Exit()
//---------------------------------------------------------------------------
TStudent SampleStudent;
SampleStudent.Display();
Complete.Display();
Exit();
return 0;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#ifndef StudentsH
#define StudentsH
#include <iostream>
//---------------------------------------------------------------------------
class TStudent
public:
void Display();
private:
string FirstName;
string LastName;
int DayOfBirth;
int MonthOfBirth;
int YearOfBirth;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include "Students.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
_fastcall TStudent::TStudent()
FirstName = "John";
LastName = "Doe";
DayOfBirth = 1;
MonthOfBirth = 1;
YearOfBirth = 1990;
//---------------------------------------------------------------------------
FirstName = FN;
LastName = LN;
DayOfBirth = 1;
MonthOfBirth = 1;
YearOfBirth = 1985;
//---------------------------------------------------------------------------
FirstName = "William";
LastName = "Smith";
DayOfBirth = DOB;
MonthOfBirth = MOB;
YearOfBirth = YOB;
//---------------------------------------------------------------------------
FirstName = fn;
LastName = ln;
DayOfBirth = DOB;
MonthOfBirth = MOB;
YearOfBirth = YOB;
//---------------------------------------------------------------------------
void TStudent::Display()
cout << "\nFull Name: " << FirstName << " " << LastName;
<< "/" << MonthOfBirth << "/" << YearOfBirth << "\n";
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
#include "Students.h"
//---------------------------------------------------------------------------
void Exit()
//---------------------------------------------------------------------------
TStudent DefaultStudent;
DefaultStudent.Display();
WithNameOnly.Display();
ByDateOfBirth.Display();
Typical.Display();
Exit();
return 0;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#ifndef BricksH
#define BricksH
//---------------------------------------------------------------------------
class TBrick
public:
double CementVolume();
void ShowProperties();
private:
double Length;
double Height;
double Thickness;
};
//---------------------------------------------------------------------------
#endif
There is another technique you can use to initialize the member variables in a constructor. To initialize the list of members, after
defining the constructor, which is after the parentheses, type a colon, followed by the name of an argument and include the initial
value in parentheses. The initializations are separated by a comma. Since the constructor is a method, make sure you provide its
body.
//---------------------------------------------------------------------------
#ifndef BricksH
#define BricksH
//---------------------------------------------------------------------------
class TBrick
public:
double CementVolume();
void ShowProperties();
private:
double Length;
double Height;
double Thickness;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include "Bricks.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
return Length;
//---------------------------------------------------------------------------
Length = l;
//---------------------------------------------------------------------------
return Height;
//---------------------------------------------------------------------------
Height = h;
//---------------------------------------------------------------------------
return Thickness;
//---------------------------------------------------------------------------
Thickness = t;
//---------------------------------------------------------------------------
double TBrick::CementVolume()
double Enclosure = 0.50; // This includes both walls of the brick itself
return ValidVolume;
//---------------------------------------------------------------------------
void TBrick::ShowProperties()
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
#include "Bricks.h"
//---------------------------------------------------------------------------
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.
//---------------------------------------------------------------------------
#ifndef BricksH
#define BricksH
//---------------------------------------------------------------------------
class TBrick
public:
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
//---------------------------------------------------------------------------
#include <iostream>
#include "Bricks.h"
//---------------------------------------------------------------------------
TBrick Lott;
Lott.ShowProperties();
// This time, the program will use the constructor that has one argument
TBrick Motto(6.12);
Motto.ShowProperties();
Hott.ShowProperties();
return 0;
//---------------------------------------------------------------------------
Length = 0.00
Height = 0.00
Thickness = 0.00
Length = 6.12
Height = 4.35
Thickness = 3.05
Length = 5.25
Height = 3.55
Thickness = 3.55
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:
//---------------------------------------------------------------------------
#ifndef BricksH
#define BricksH
//---------------------------------------------------------------------------
class TBrick
public:
TBrick();
TBrick(double L);
double CementVolume();
void ShowProperties();
private:
double Length;
double Height;
double Thickness;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include "Bricks.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
. . .
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>
//---------------------------------------------------------------------------
class TStudent
public:
DayOfBirth = 1; MonthOfBirth = 1;
YearOfBirth = 1990;
{ FirstName = fn;
LastName = ln;
DayOfBirth = DOB;
MonthOfBirth = MOB;
YearOfBirth = YOB;
void Display();
private:
string FirstName;
string LastName;
int DayOfBirth;
int MonthOfBirth;
int YearOfBirth;
};
//---------------------------------------------------------------------------
#endif
3. To use the new technique of initializing the member variables, implement the constructors in the Students.cpp file as follows:
//---------------------------------------------------------------------------
#include "Students.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
FirstName = FN;
LastName = LN;
DayOfBirth = 1;
MonthOfBirth = 1;
YearOfBirth = 1985;
//---------------------------------------------------------------------------
FirstName = "William";
LastName = "Smith";
DayOfBirth = DOB;
MonthOfBirth = MOB;
YearOfBirth = YOB;
//---------------------------------------------------------------------------
void TStudent::Display()
cout << "\nFull Name: " << FirstName << " " << LastName;
<< "/" << MonthOfBirth << "/" << YearOfBirth << "\n";
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#ifndef StudentsH
#define StudentsH
#include <iostream>
//---------------------------------------------------------------------------
class TStudent
public:
TStudent() : FirstName("John"),
LastName("Doe"),
DayOfBirth(1),
MonthOfBirth(1),
YearOfBirth(1990)
{}
: FirstName(fn),
LastName(ln),
DayOfBirth(DOB),
MonthOfBirth(MOB),
YearOfBirth(YOB)
{}
void Display();
private:
string FirstName;
string LastName;
int DayOfBirth;
int MonthOfBirth;
int YearOfBirth;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#ifndef StudentsH
#define StudentsH
#include <string>
//---------------------------------------------------------------------------
class TStudent
public:
TStudent();
void Display();
private:
string FirstName;
string LastName;
int DayOfBirth;
int MonthOfBirth;
int YearOfBirth;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include "Students.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
DayOfBirth(1), MonthOfBirth(1),
YearOfBirth(1990)
//---------------------------------------------------------------------------
: FirstName(FN), LastName(LN),
//---------------------------------------------------------------------------
: FirstName("William"), LastName("Smith"),
//---------------------------------------------------------------------------
: FirstName(fn),
LastName(ln),
DayOfBirth(DOB),
MonthOfBirth(MOB),
YearOfBirth(YOB)
//---------------------------------------------------------------------------
void TStudent::Display()
cout << "\nFull Name: " << FirstName << " " << LastName;
<< "/" << MonthOfBirth << "/" << YearOfBirth << "\n";
//---------------------------------------------------------------------------
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:
//---------------------------------------------------------------------------
#include <iostream>
#include "Bricks.h"
//---------------------------------------------------------------------------
Hott.ShowProperties();
Bosco.ShowProperties();
return 0;
//---------------------------------------------------------------------------
Length = 5.25
Height = 3.55
Thickness = 3.55
Length = 5.25
Height = 3.55
Thickness = 3.55
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>
//---------------------------------------------------------------------------
int CheeseSteak = 2;
int TunaSalad(4);
int TurkeyHam(TunaSalad);
double PriceCS(3.12);
double PriceTH(PriceTS);
cout << CheeseSteak << " orders of Cheese Steak, Price = $"
cout << TunaSalad << " orders of Tuna Salad, Price = $"
cout << TurkeyHam << " orders of Turkey Ham, Price = $" << TotalTH << endl;
return 0;
//---------------------------------------------------------------------------
Total Order
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:
//---------------------------------------------------------------------------
#ifndef BricksH
#define BricksH
//---------------------------------------------------------------------------
class TBrick
public:
TBrick();
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:
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include "Bricks.h"
//---------------------------------------------------------------------------
Beam.ShowProperties();
Hoyt = Beam;
Hoyt.ShowProperties();
TBrick Mollo(Beam);
Hoyt.ShowProperties();
return 0;
//---------------------------------------------------------------------------
Length = 7.25
Height = 4.85
Thickness = 5.15
Length = 7.25
Height = 4.85
Thickness = 5.15
Length = 7.25
Height = 4.85
Thickness = 5.15
1. To use the default copy constructor created by the compiler, change the content of the main() function as follows:
//---------------------------------------------------------------------------
#include <iostream>
#include "Students.h"
//---------------------------------------------------------------------------
Student1.Display();
TStudent DefaultStudent;
DefaultStudent.Display();
DuplicateHer.Display();
return 0;
//---------------------------------------------------------------------------
#ifndef StudentsH
#define StudentsH
#include <iostream>
//---------------------------------------------------------------------------
class TStudent
public:
TStudent();
void Display();
private:
string FirstName;
string LastName;
int DayOfBirth;
int MonthOfBirth;
int YearOfBirth;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
: FirstName(Stud.FirstName), LastName(Stud.LastName),
DayOfBirth(Stud.DayOfBirth), MonthOfBirth(Stud.MonthOfBirth),
YearOfBirth(Stud.YearOfBirth)
//---------------------------------------------------------------------------
Destructors
Introduction
As opposed to a constructor, a destructor is called when a program has finished using an instance of an object. A destructor does the
cleaning behind the scenes. Like the default constructor, the compiler always create a default destructor if you don't create one. Like
the default constructor, a destructor also has the same name as its object. This time, the name of the destructor starts with a tilde.
To create your own destructor, in the header file, type ~ followed by the name of the object. Here is an example:
//---------------------------------------------------------------------------
#ifndef BricksH
#define BricksH
//---------------------------------------------------------------------------
class TBrick
public:
TBrick();
~TBrick();
double 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:
//---------------------------------------------------------------------------
#ifndef BricksH
#define BricksH
//---------------------------------------------------------------------------
class TBrick
public:
...
~TBrick() {}
...
private:
...
};
//---------------------------------------------------------------------------
#endif
Otherwise, you can also implement it in the cpp file with empty parentheses. Here is an example:
//---------------------------------------------------------------------------
TBrick::~TBrick()
//---------------------------------------------------------------------------
Using Destructors
1. To illustrate the construction and destruction effects of an object, create a new Console Application named Library
2. Change the content of the file as follows:
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
class TBook
public:
TBook(); // Constructor
~TBook(); // Destructor
};
//---------------------------------------------------------------------------
TBook::TBook()
//---------------------------------------------------------------------------
TBook::~TBook()
//---------------------------------------------------------------------------
TBook A;
cout << "\nI didn't like that book. I will try another\n\n";
TBook B;
B.Message();
return 0;
//---------------------------------------------------------------------------
I am at the library
//---------------------------------------------------------------------------
#ifndef StudentsH
#define StudentsH
#include <iostream>
//---------------------------------------------------------------------------
class TStudent
public:
TStudent();
~TStudent();
void Display();
private:
string FirstName;
string LastName;
int DayOfBirth;
int MonthOfBirth;
int YearOfBirth;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
TStudent::~TStudent()
//---------------------------------------------------------------------------
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.
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.
//---------------------------------------------------------------------------
#ifndef ConeH
#define ConeH
//---------------------------------------------------------------------------
struct TCone
public:
~TCone(); // Destructor
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.
//---------------------------------------------------------------------------
#include <math>
#include "Cone.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TCone::TCone()
: Radius(0.00), Height(0.00)
//---------------------------------------------------------------------------
TCone::TCone(double r, double h)
: Radius(r), Height(h)
//---------------------------------------------------------------------------
TCone::TCone(const TCone& c)
: Radius(c.Radius), Height(c.Height)
//---------------------------------------------------------------------------
TCone::~TCone()
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
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:
//---------------------------------------------------------------------------
#include <iostream>
#include "Cone.h"
//---------------------------------------------------------------------------
TCone Conic;
return 0;
//---------------------------------------------------------------------------
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:
//---------------------------------------------------------------------------
#include <iostream>
#include "Cone.h"
//---------------------------------------------------------------------------
return 0;
//---------------------------------------------------------------------------
With an object as complete as our cone, you can let the user provide the dimensions for the tent:
//---------------------------------------------------------------------------
#include <iostream>
#include "Cone.h"
//---------------------------------------------------------------------------
TCone Camper;
double r, h;
cin >> r;
cin >> h;
Camper.setRadius(r);
Camper.setHeight(h);
return 0;
//---------------------------------------------------------------------------
Radius: 7.24
Radius: 4.88
Radius: 7.24
Height: 4.88
//---------------------------------------------------------------------------
#ifndef StudentsH
#define StudentsH
#include <iostream>
//---------------------------------------------------------------------------
class TStudent
public:
TStudent();
~TStudent();
private:
string FirstName;
string LastName;
int DayOfBirth;
int MonthOfBirth;
int YearOfBirth;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include "Students.h"
//---------------------------------------------------------------------------
TStudent::TStudent()
FirstName = "John";
LastName = "Doe";
DayOfBirth = 1;
MonthOfBirth = 1;
YearOfBirth = 1990;
//---------------------------------------------------------------------------
: FirstName(fn), LastName(ln),
//---------------------------------------------------------------------------
TStudent::~TStudent()
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
#include "Students.h"
//---------------------------------------------------------------------------
TStudent St;
return 0;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
#include "Students.h"
//---------------------------------------------------------------------------
return 0;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
#include "Students.h"
//---------------------------------------------------------------------------
return 0;
//---------------------------------------------------------------------------
Day of Birth: 22
Month of Birth: 6
Student Information
//---------------------------------------------------------------------------
#ifndef StudentsH
#define StudentsH
#include <iostream>
//---------------------------------------------------------------------------
class TStudent
public:
TStudent();
~TStudent();
private:
string FirstName;
string LastName;
int DayOfBirth;
int MonthOfBirth;
int YearOfBirth;
};
//---------------------------------------------------------------------------
#endif
16. To request values of the Tstudents object, change the Main.cpp file as follows:
#include <iostream>
#include "Students.h"
//---------------------------------------------------------------------------
TStudent St;
St.setFirstName(FN);
St.setLastName(LN);
St.setDayOfBirth(Day);
St.setMonthOfBirth(Month);
St.setYearOfBirth(Year);
return 0;
//---------------------------------------------------------------------------
Day of Birth: 2
Month of Birth: 2
Student Information
An object as an Argument
After creating an object, it becomes a data type, sometimes referred to as a programmer defined data type. As an identifier, you
can declare an object inside of a function and use it. That is what we have done so far when using objects inside of the main()
function.
There are two techniques used to involve an object with a function. You can pass a member of an object as argument to a
function, or you can pass the whole object as an argument. When passing an object as a parameter, you should be familiar with
the construction of the object. Know its members and which ones you need to use. The code completion feature is highly useful
in this circumstance.
Instead of displaying the characteristics of the tent in the main() function, we can use an external function to perform that
assignment.
//---------------------------------------------------------------------------
#include <iostream>
#include "Cone.h"
//---------------------------------------------------------------------------
void ShowTent(TCone c)
//---------------------------------------------------------------------------
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:
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include "Cone.h"
//---------------------------------------------------------------------------
void ShowTent(TCone c)
//---------------------------------------------------------------------------
TCone Tent;
double r, h;
cin >> r;
cin >> h;
Tent.setRadius(r);
Tent.setHeight(h);
ShowTent(Tent);
return 0;
//---------------------------------------------------------------------------
Radius: 10.24
Height: 6.84
Radius: 10.24
Height: 6.84
//---------------------------------------------------------------------------
#include <iostream>
#include "Students.h"
//---------------------------------------------------------------------------
ShowStudent(St);
return 0;
//---------------------------------------------------------------------------
void ShowStudent(TStudent s)
}//---------------------------------------------------------------------------
Day of Birth: 18
Month of Birth: 4
Student Registration
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.
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include "Cone.h"
//---------------------------------------------------------------------------
void Exit()
//---------------------------------------------------------------------------
void ShowTent(TCone c)
//---------------------------------------------------------------------------
TCone ObtainDimensions()
double r, h;
//---------------------------------------------------------------------------
TCone Tent;
Tent = ObtainDimensions();
ShowTent(Tent);
Exit();
return 0;
//---------------------------------------------------------------------------
Radius: 8.44
Radius: 5.26
Radius: 8.44
Height: 5.26
Another version of the ObainDimensions() function would consist of assigning the values of the member variables of the object to
the right access methods:
//---------------------------------------------------------------------------
TCone ObtainDimensions()
double r, h;
TCone Tonic;
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:
//---------------------------------------------------------------------------
TCone ObtainDimensions()
double r, h;
return Copper;
//---------------------------------------------------------------------------
Any of these techniques should allow you to return the desired object from a function and be able to use that object somewhere
else, including displaying its properties using another function:
Radius: 18.12
Height: 10.26
Radius: 18.12
Height: 10.26
//---------------------------------------------------------------------------
#include <iostream>
#include "Students.h"
//---------------------------------------------------------------------------
TStudent Stud;
TStudent Register();
Stud = Register();
ShowStudent(Stud);
return 0;
//---------------------------------------------------------------------------
void ShowStudent(TStudent s)
//---------------------------------------------------------------------------
TStudent Register()
TStudent s;
s.setFirstName(FN);
s.setLastName(LN);
s.setDayOfBirth(Day);
s.setMonthOfBirth(Month);
s.setYearOfBirth(Year);
return s;
//---------------------------------------------------------------------------
Day of Birth: 2
Month of Birth: 4
Student Registration
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:
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include "Cone.h"
//---------------------------------------------------------------------------
void Exit()
//---------------------------------------------------------------------------
void ShowTent(TCone c)
//---------------------------------------------------------------------------
double r, h;
Tone.setRadius(r);
Tone.setHeight(h);
//---------------------------------------------------------------------------
TCone Tent;
ObtainDimensions(Tent);
ShowTent(Tent);
Exit();
return 0;
//---------------------------------------------------------------------------
Radius: 5.12
Radius: 3.84
Radius: 5.12
Height: 3.84
//---------------------------------------------------------------------------
#include <iostream>
#include "Students.h"
//---------------------------------------------------------------------------
TStudent Stud;
void Register(TStudent&);
Register(Stud);
ShowStudent(Stud);
return 0;
//---------------------------------------------------------------------------
void Register(TStudent& S)
S.setFirstName(FN);
S.setLastName(LN);
S.setDayOfBirth(Day);
S.setMonthOfBirth(Month);
S.setYearOfBirth(Year);
//---------------------------------------------------------------------------
void ShowStudent(TStudent s)
//---------------------------------------------------------------------------
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>
//---------------------------------------------------------------------------
class TForSale
public:
private:
int Qty;
double UnitPrice;
};
//---------------------------------------------------------------------------
: Qty(Quantity), UnitPrice(Price)
//---------------------------------------------------------------------------
double TotalPrice(TForSale i)
//---------------------------------------------------------------------------
return 0;
//---------------------------------------------------------------------------
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.
//---------------------------------------------------------------------------
#ifndef TriangleH
#define TriangleH
//---------------------------------------------------------------------------
struct TTriangle
public:
~TTriangle();
private:
double Base;
double Height;
};
//---------------------------------------------------------------------------
#endif
Once the friends have been declared, you can define them in the header file of the object as if they were part of the interface.
Here is an example:
//---------------------------------------------------------------------------
#ifndef TriangleH
#define TriangleH
//---------------------------------------------------------------------------
struct TTriangle
public:
~TTriangle();
private:
double Base;
double Height;
};
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#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
public:
~TTriangle();
private:
double Base;
double Height;
};
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#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>
#include "Triangle.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TTriangle::TTriangle(double B, double H)
: Base(B), Height(H)
//---------------------------------------------------------------------------
TTriangle::TTriangle(const TTriangle& t)
: Base(t.Base), Height(t.Height)
//---------------------------------------------------------------------------
TTriangle::~TTriangle()
//---------------------------------------------------------------------------
return Base;
//---------------------------------------------------------------------------
return Height;
//---------------------------------------------------------------------------
Friends are called like any other regular global functions, by their names. They do not need to be qualified with the period
operator. Therefore, they can be called by any function. They can be passed any variable declared from the friendly object; and
as you know already, they have access to all members of the object. Here is a declaration of the TTriangle object in the main()
function, 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>
#include "Triangle.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
Characteristics(Trng);
return 0;
//---------------------------------------------------------------------------
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
public:
~TTriangle();
private:
double Base;
double Height;
};
//---------------------------------------------------------------------------
#endif
Of course, remember that the const keyword is used both when declaring the function and when defining it:
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
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:
//---------------------------------------------------------------------------
#ifndef TriangleH
#define TriangleH
//---------------------------------------------------------------------------
struct TTriangle
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
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
public:
~TTriangle();
private:
double Base;
double Height;
};
//---------------------------------------------------------------------------
#endif
The function would be defined as a regular function that returns the object:
//---------------------------------------------------------------------------
TTriangle GetDimensions()
double 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>
#include "Triangle.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TTriangle Slice;
double b, h;
Slice = GetDimensions();
Characteristics(Slice);
return 0;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#ifndef StudentsH
#define StudentsH
#include <iostream>
//---------------------------------------------------------------------------
class TStudent
public:
TStudent();
~TStudent();
private:
string FirstName;
string LastName;
int DayOfBirth;
int MonthOfBirth;
int YearOfBirth;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include "Students.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TStudent Registration()
TStudent S;
return S;
//---------------------------------------------------------------------------
TStudent::TStudent()
FirstName = "John";
LastName = "Doe";
DayOfBirth = 1;
MonthOfBirth = 1;
YearOfBirth = 1990;
//---------------------------------------------------------------------------
: FirstName(FN), LastName(LN),
//---------------------------------------------------------------------------
: FirstName(fn), LastName(ln),
//---------------------------------------------------------------------------
: FirstName(Stud.FirstName),
LastName(Stud.LastName),
DayOfBirth(Stud.DayOfBirth),
MonthOfBirth(Stud.MonthOfBirth),
YearOfBirth(Stud.YearOfBirth)
//---------------------------------------------------------------------------
TStudent::~TStudent()
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
#include "Students.h"
//---------------------------------------------------------------------------
TStudent Stud;
Stud = Registration();
StudentInfo(Stud);
return 0;
//---------------------------------------------------------------------------
void StudentInfo(TStudent s)
//---------------------------------------------------------------------------
Day of Birth: 10
Month of Birth: 12
Student Registration
//---------------------------------------------------------------------------
#ifndef StudentsH
#define StudentsH
#include <iostream>
//---------------------------------------------------------------------------
class TStudent
public:
. . .
private:
. . .
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
An office supplies store has hired you to write a program that will allow customers to create their own business labels using a
computer located somewhere in the store. We will use two objects for our program. TDimensions will define the dimensions of
the label and another object called TLabelType will define the paper quality.
A classic label has dimensions set by a length and a width. When a user or another part of the program calls the label, it mostly
uses constructors; and we will use them. The first constructor takes no argument; it is used to set the default dimensions for the
label. The second constructor will make sure that the supplied dimensions, if any, are correct. To protect our dimensions, the
length and the width will be private; we will provide access methods to get the dimensions:
//---------------------------------------------------------------------------
#ifndef RectangleH
#define RectangleH
//---------------------------------------------------------------------------
class TRectangle
public:
TRectangle();
~TRectangle();
private:
double Length;
double Height;
};
//---------------------------------------------------------------------------
#endif
The source file initializes the object, controls the dimensions, and calculates the area:
//---------------------------------------------------------------------------
#include "Rectangle.h"
//---------------------------------------------------------------------------
TRectangle::TRectangle()
: Length(3.25), Height(2.55)
//---------------------------------------------------------------------------
TRectangle::TRectangle(double L, double H)
: Length(L), Height(H)
//---------------------------------------------------------------------------
TRectangle::TRectangle(const TRectangle& r)
: Length(r.Length), Height(r.Height)
//---------------------------------------------------------------------------
TRectangle::~TRectangle()
//---------------------------------------------------------------------------
return 2 * (x + 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.
//---------------------------------------------------------------------------
#ifndef LabelTypeH
#define LabelTypeH
#include <string>
//---------------------------------------------------------------------------
class TLabelType
public:
TLabelType();
~TLabelType();
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.
//---------------------------------------------------------------------------
#include "LabelType.h"
//---------------------------------------------------------------------------
TLabelType::TLabelType()
: ModelNumber(0), Color("White"),
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TLabelType::~TLabelType()
//---------------------------------------------------------------------------
return ModelNumber;
//---------------------------------------------------------------------------
return Name;
//---------------------------------------------------------------------------
return Color;
//---------------------------------------------------------------------------
return Adhesive;
//---------------------------------------------------------------------------
Once you have objects, you can declare each when desired and supply its properties if needed. In our main() function, we will
first call the TDimension and the TLabelType objects using empty contructors. Whenever any function or object calls an object
without specifying the properties, each object will display its default values:
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include "Rectangle.h"
#include "LabelType.h"
//---------------------------------------------------------------------------
TRectangle Dim;
TLabelType LabelType;
return 0;
//---------------------------------------------------------------------------
Area: 8.2875
Model No.: 0
Color: White
The program can also provide the values of each object, using their methods:
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include "Rectangle.h"
#include "LabelType.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
return 0;
//---------------------------------------------------------------------------
An example label
Area: 10.2375
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:
//---------------------------------------------------------------------------
#ifndef StudentsH
#define StudentsH
#include <iostream>
//---------------------------------------------------------------------------
class TStudent
public:
TStudent();
~TStudent();
private:
string FirstName;
string LastName;
int DayOfBirth;
int MonthOfBirth;
int YearOfBirth;
string Address;
string City;
string State;
string ZIPCode;
string Country;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include "Students.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
getline(cin, S.Address);
getline(cin, S.City);
getline(cin, S.State);
getline(cin, S.ZIPCode);
getline(cin, S.Country);
//---------------------------------------------------------------------------
TStudent::TStudent()
FirstName = "John";
LastName = "Doe";
DayOfBirth = 1;
MonthOfBirth = 1;
YearOfBirth = 1990;
ZIPCode = "01234-0001";
Country = "USA";
//---------------------------------------------------------------------------
: FirstName(FN), LastName(LN),
City("This State"),
State("Unkown"),
ZIPCode("00001-0001"),
Country("USA")
//---------------------------------------------------------------------------
: FirstName(fn), LastName(ln),
City("This State"),
State("Unkown"),
ZIPCode("00001-0001"),
Country("USA")
//---------------------------------------------------------------------------
: 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()
//---------------------------------------------------------------------------
3. Create a new
4. class called TGrades object and change the Grades.h file as follows:
//---------------------------------------------------------------------------
#ifndef GradesH
#define GradesH
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
class TGrades
public:
TGrades();
~TGrades();
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;
};
//---------------------------------------------------------------------------
#include <iostream>
#include "Grades.h"
//---------------------------------------------------------------------------
TGrades::TGrades()
: English(0.00),
SecondLng(0.00),
History(0.00),
Geography(0.00),
Chemistry(0.00),
Sociology(0.00),
Math(0.00),
CompSc(0.00),
Morale(0.00),
Sports(0.00)
//---------------------------------------------------------------------------
: English(e),
SecondLng(s),
History(h),
Geography(g),
Chemistry(c),
Sociology(o),
Math(m),
CompSc(p),
Morale(r),
Sports(t)
//---------------------------------------------------------------------------
TGrades::~TGrades()
//---------------------------------------------------------------------------
double TGrades::CalcTotal()
return Total;
//---------------------------------------------------------------------------
double TGrades::CalcMean()
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
6. To use both objects in the same program, implement the Main.cpp file as follows:
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include "Students.h"
#include "Grades.h"
//---------------------------------------------------------------------------
TStudent Stud;
TGrades Grade;
Registration(Stud);
GetGrades(Grade);
system("cls");
StudentInfo(Stud);
ShowGrades(Grade);
return 0;
//---------------------------------------------------------------------------
void StudentInfo(TStudent s)
<< "\n " << s.getCity() << ", " << s.getState()
//---------------------------------------------------------------------------
void ShowGrades(TGrades d)
cout << "\n\tTotal: " << d.CalcTotal() << "\tMean: " << d.CalcMean();
//---------------------------------------------------------------------------
First Screen:
Student Registration
Day of Birth: 28
Month of Birth: 2
State: MD
ZIPCode: 20910-4412
Country: USA
Student Grades
English: 12.50
History: 14.50
Geography: 13.00
Chemistry: 15.00
Sociology: 12.50
Mathematics: 16.50
Morale: 14.00
Sports: 15.50
Second Screen:
====================================
Student Report
------------------------------------
Student Registration
USA
------------------------------------
English: 12.50
Language 2: 10.25
History: 14.50
Geography: 13.00
Chemistry: 15.00
Sociology: 12.50
Mathematics: 16.50
Morale: 14.00
Sports: 15.50
------------------------------------
====================================
//---------------------------------------------------------------------------
#ifndef LabelTypeH
#define LabelTypeH
//---------------------------------------------------------------------------
#include <string>
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
class TLabelType
public:
TLabelType();
~TLabelType();
private:
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)
//---------------------------------------------------------------------------
: ModelNumber(m),
Name(n),
Color(c),
PrintType(t)
//---------------------------------------------------------------------------
: ModelNumber(Label.ModelNumber),
Name(Label.Name),
Color(Label.Color),
PrintType(Label.PrintType)
//---------------------------------------------------------------------------
TLabelType::~TLabelType()
//---------------------------------------------------------------------------
return ModelNumber;
//---------------------------------------------------------------------------
return Name;
//---------------------------------------------------------------------------
return Color;
//---------------------------------------------------------------------------
string PrintingType;
switch( PrintType )
case pcInkjet:
PrintingType = "Injet";
break;
case pcLaser:
PrintingType = "Laser";
break;
case pcMultiPurpose:
PrintingType = "Multi-Purpose";
break;
default:
PrintingType = "Unspeficied";
return PrintingType;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
#include "LabelType.h"
//---------------------------------------------------------------------------
TLabelType Label;
Label.setModelNumber(475832);
Label.setName("Blanc d'Azure");
Label.setColor("Old Sand");
Label.setPrintType(2);
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:
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;
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>
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
class TLabelType
public:
TLabelType();
~TLabelType();
private:
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)
//---------------------------------------------------------------------------
int t, TAdhesive a)
: ModelNumber(m),
Name(n),
Color(c),
PrintType(t),
Adhesive(a)
//---------------------------------------------------------------------------
: ModelNumber(Label.ModelNumber),
Name(Label.Name),
Color(Label.Color),
PrintType(Label.PrintType),
Adhesive(Label.Adhesive)
//---------------------------------------------------------------------------
. . .
//---------------------------------------------------------------------------
return Adhesive;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
#include "LabelType.h"
//---------------------------------------------------------------------------
TLabelType Label;
Label.setModelNumber(475832);
Label.setName("Blanc d'Azure");
Label.setColor("Old Sand");
Label.setPrintType(2);
Label.setAdhesive(adRemovable);
return 0;
//---------------------------------------------------------------------------
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>
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
class TStudents
public:
TStudents();
~TStudents();
private:
string FirstName;
string LastName;
int DayOfBirth;
int MonthOfBirth;
int YearOfBirth;
int Gender;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include "Students.h"
//---------------------------------------------------------------------------
TStudents::TStudents()
: FirstName("John"),
LastName("Doe"),
DayOfBirth(5),
MonthOfBirth(10),
YearOfBirth(1988),
Gender(0)
//---------------------------------------------------------------------------
: FirstName(fn), LastName(ln),
//---------------------------------------------------------------------------
: FirstName(fn), LastName(ln),
//---------------------------------------------------------------------------
FirstName = "Peter";
LastName = "Mukoko";
DayOfBirth = DOB;
MonthOfBirth = MOB;
YearOfBirth = YOB;
//---------------------------------------------------------------------------
: FirstName(Stud.FirstName), LastName(Stud.LastName),
DayOfBirth(Stud.DayOfBirth), MonthOfBirth(Stud.MonthOfBirth),
YearOfBirth(Stud.YearOfBirth), Gender(Stud.Gender)
//---------------------------------------------------------------------------
TStudents::~TStudents()
//---------------------------------------------------------------------------
return "Male";
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>
//---------------------------------------------------------------------------
#include "Students.h"
//---------------------------------------------------------------------------
TStudents S;
S.setFirstName(FN);
S.setLastName(LN);
S.setDayOfBirth(Day);
S.setMonthOfBirth(Month);
S.setYearOfBirth(Year);
S.setGender(Gdr);
system("cls");
<< S.getLastName();
<< S.getYearOfBirth();
return 0;
//---------------------------------------------------------------------------
7. To test the program, on the main menu, click Run -> Run.
8. After testing the program, return to your programming environment.
//---------------------------------------------------------------------------
#ifndef LabelDimensionsH
#define LabelDimensionsH
//---------------------------------------------------------------------------
class TDimensions
public:
~TDimensions();
private:
Double Length;
Double Height;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include "LabelDimensions.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TDimensions::TDimensions(Double L, Double W)
: Length(L), Height(H)
//---------------------------------------------------------------------------
TDimensions::~TDimensions()
//---------------------------------------------------------------------------
Length = L;
Height = H;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#ifndef LabelTypeH
#define LabelTypeH
//---------------------------------------------------------------------------
#include <iostream>
#include "LabelDimensions.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
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:
//---------------------------------------------------------------------------
#include <iomanip>
//---------------------------------------------------------------------------
#include "LabelType.h"
#include "LabelDimensions.h"
//---------------------------------------------------------------------------
TLabelType LblType;
string AdhesiveType;
LblType.Dim.setDimensions(4.25, 2.50);
LblType.setModelNumber(38946);
LblType.setName("Coast Layer");
LblType.setColor("Bone White");
LblType.setPrintType(2);
LblType.setAdhesive(adRemovable);
AdhesiveType = "Removable";
AdhesiveType = "Non-Removable";
else
AdhesiveType = "None";
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.
//---------------------------------------------------------------------------
#ifndef GradesH
#define GradesH
#include "Students.h"
//---------------------------------------------------------------------------
class TGrades
public:
TGrades();
~TGrades();
TStudents Identification;
private:
double English;
double SecondLng;
double History;
double Geography;
double Chemistry;
double Sociology;
double Math;
double CompSc;
double Morale;
double Sports;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include "Grades.h"
//---------------------------------------------------------------------------
TGrades::TGrades()
English = 0.00;
SecondLng = 0.00;
History = 0.00;
Geography = 0.00;
Chemistry = 0.00;
Sociology = 0.00;
Math = 0.00;
CompSc = 0.00;
Morale = 0.00;
Sports = 0.00;
//---------------------------------------------------------------------------
English = e;
SecondLng = s;
History = h;
Geography = g;
Chemistry = c;
Sociology = o;
Math = m;
CompSc = p;
Morale = r;
Sports = t;
//---------------------------------------------------------------------------
TGrades::~TGrades()
//---------------------------------------------------------------------------
return Total;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iomanip>
#include <conio.h>
//---------------------------------------------------------------------------
#include "Grades.h"
//---------------------------------------------------------------------------
TGrades G;
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);
G.setEnglish(Language1);
G.setSecondLng(Language2);
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");
<< G.Identification.getLastName();
<< G.Identification.getYearOfBirth();
return 0;
//---------------------------------------------------------------------------
5. To test the program, on the Debug toolbar, click the Run button . An example would be:
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
//---------------------------------------------------------------------------
class TLabels
public:
TLabels();
~TLabels();
void ProcessALabel();
void ShowReceipt();
private:
Double Price;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include "Labels.h"
//---------------------------------------------------------------------------
TLabels::TLabels()
: Price(0.00)
//---------------------------------------------------------------------------
TLabels::TLabels(const TLabels& L)
: Price(L.Price)
//---------------------------------------------------------------------------
TLabels::~TLabels()
//---------------------------------------------------------------------------
void TLabels::ProcessALabel()
//---------------------------------------------------------------------------
void TLabels::ShowReceipt()
<< 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
The keywords friend and class are required. The ClassName is the name of the class that needs friendship. Here is an example:
//---------------------------------------------------------------------------
#ifndef LabelDimensionsH
#define LabelDimensionsH
//---------------------------------------------------------------------------
class TDimensions
public:
~TDimensions();
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>
#include "LabelDimensions.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
class TLabelType
public:
. . .
private:
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();
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>
#include "Labels.h"
//---------------------------------------------------------------------------
TLabels::TLabels()
: Price(0.00)
//---------------------------------------------------------------------------
TLabels::TLabels(const TLabels& L)
: Price(L.Price)
//---------------------------------------------------------------------------
TLabels::~TLabels()
//---------------------------------------------------------------------------
Double A = Rect.Area();
Price = 10.95;
Price = 12.95;
Price = 14.95;
Price = 18.95;
else
Price = 26.95;
//---------------------------------------------------------------------------
int AdhesiveType;
int PrtType;
gets(LabelName);
gets(LabelColor);
if( AdhesiveType == 1 )
Label.Adhesive = adRemovable;
Label.Adhesive = adNonRemovable;
else
Label.Adhesive = adNone;
Label.Name = LabelName;
Label.Color = LabelColor;
//---------------------------------------------------------------------------
else
//---------------------------------------------------------------------------
The composition of classes performed on our objects allows us now to process an order and display its receipt:
//---------------------------------------------------------------------------
#include <iomanip>
#include <conio.h>
//---------------------------------------------------------------------------
#include "Labels.h"
//---------------------------------------------------------------------------
TLabels Label;
TDimensions Dim;
TLabelType Type;
cout << "This machine allows you to create labels\nto the desired "
Label.GetLabelDimensions(Dim);
Label.GetLabelCharacteristics(Type);
system("cls");
Label.ShowReceipt(Dim, Type);
return 0;
//---------------------------------------------------------------------------
Combining Objects
1. To prepare a class that woud handle student and grade registration, add a new class. Save it as GradeReport
2. In the GradeReport.h file, create the foundation of the class as follows:
//---------------------------------------------------------------------------
#ifndef GradeReportH
#define GradeReportH
//---------------------------------------------------------------------------
class TGradeReport
public:
private:
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#ifndef StudentsH
#define StudentsH
#include <iostream>
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
class TStudents
public:
. . .
private:
. . .
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#ifndef GradesH
#define GradesH
#include "Students.h"
//---------------------------------------------------------------------------
class TGrades
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;
};
//---------------------------------------------------------------------------
class TGradeReport
public:
TGradeReport();
~TGradeReport();
TStudents Registration();
TGrades GetGrades();
private:
TGradeInfo LevelInfo;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include <iomanip>
#include "GradeReport.h"
//---------------------------------------------------------------------------
TGradeReport::TGradeReport()
//---------------------------------------------------------------------------
TGradeReport::~TGradeReport()
//---------------------------------------------------------------------------
TStudents TGradeReport::Registration()
TStudents Student;
int Gender;
Student.setGender(Gender);
getline(cin, LevelInfo.MajorName);
return Student;
//---------------------------------------------------------------------------
TGrades TGradeReport::GetGrades()
TGrades Grade;
return Grade;
//---------------------------------------------------------------------------
<< Student.getLastName();
<< Student.getYearOfBirth();
<< LevelInfo.MajorName;
//---------------------------------------------------------------------------
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>
//---------------------------------------------------------------------------
#include "Grades.h"
#include "Students.h"
#include "GradeReport.h"
//---------------------------------------------------------------------------
TGradeReport Report;
TStudents Student;
TGrades Grade;
Student = Report.Registration();
Grade = Report.GetGrades();
system("cls");
Report.ShowReport(Student, Grade);
return 0;
//---------------------------------------------------------------------------
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.
//---------------------------------------------------------------------------
#ifndef RectangleH
#define RectangleH
//---------------------------------------------------------------------------
class TRectangle
public:
~TRectangle();
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:
//---------------------------------------------------------------------------
#include "Rectangle.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TRectangle::TRectangle(double L, double H)
: Length(L), Height(H)
//---------------------------------------------------------------------------
: Length(Rect.Length), Height(Rect.Height)
//---------------------------------------------------------------------------
TRectangle::~TRectangle()
//---------------------------------------------------------------------------
Length = L;
//---------------------------------------------------------------------------
Height = H;
//---------------------------------------------------------------------------
setLength(L);
setHeight(H);
//---------------------------------------------------------------------------
return Length;
//---------------------------------------------------------------------------
return 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.
//---------------------------------------------------------------------------
#include <iomanip>
//---------------------------------------------------------------------------
#include "Rectangle.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TRectangle Rect1;
RectProperties(Rect1);
RectProperties(Rect2);
Rect3 = Rect2;
RectProperties(Rect3);
return 0;
//---------------------------------------------------------------------------
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();
private:
string FirstName;
string LastName;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include "Person.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
: FirstName(fn), LastName(ln)
//---------------------------------------------------------------------------
TPerson::TPerson(const TPerson& P)
: FirstName(P.FirstName), LastName(P.LastName)
//---------------------------------------------------------------------------
TPerson::~TPerson()
//---------------------------------------------------------------------------
FirstName = f;
//---------------------------------------------------------------------------
return FirstName;
//---------------------------------------------------------------------------
LastName = l;
//---------------------------------------------------------------------------
return LastName;
//---------------------------------------------------------------------------
6. To find out whether the new class work, change the Main.cpp file as follows:
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
#include "Person.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
ShowInfo(P);
return 0;
//---------------------------------------------------------------------------
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:
The word structORclass will be replaced by struct or class depending on the object type you are trying to create.
The NewObject element represents the name of the object you are creating.
The colon (:) is read “is based on”. It lets the compiler know that the new object gets its starting behavior and properties from another
object.
The word AccessLevel specifies whether the object will use the public or private (or protected) level of access. The most common
inheritance, which is also the most we will study, is the public inheritance. If you are creating an object whose parent is a structure, you
can usually omit this access level because a structure is public by default. Otherwise, you should specify the level of access.
The ParentObject is the name of the object that the new object is based or is inheriting from.
When inheriting from another object, the new object is considered a child. To get the properties of the parent object, you should declare an
instance of the parent. This instance will provide access to the members of the original object. The new object will not have access to the
private members of the parent.
As we now have a good working rectangle, we will use it as the base of our
brick. The header file of TBox creates an object whose base is the TRectangle
object.
//---------------------------------------------------------------------------
#ifndef BoxH
#define BoxH
#include "Rectangle.h"
//---------------------------------------------------------------------------
public:
~TBox();
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:
//---------------------------------------------------------------------------
#include "Box.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TBox::~TBox()
//---------------------------------------------------------------------------
Width = 0.00;
else
Width = W;
//---------------------------------------------------------------------------
setLength(L);
setHeight(H);
setWidth(W);
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
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>
//---------------------------------------------------------------------------
#include "Rectangle.h"
#include "Box.h"
//---------------------------------------------------------------------------
. . .
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TBox RedBox;
BoxProperties(RedBox);
BoxProperties(GrayBox);
return 0;
//---------------------------------------------------------------------------
In the past, we learned that the public level allows the client of a class to access any member of the public section of the class. We also
learned to hide other members by declaring them in the private section, which prevents the clients of class from accessing such variables.
You can create a special access level that allows only the children of a class to have access to certain members of the parent class. This
new access level is called protected and created with that keyword.
The box we created and inherited from the TRectangle object needs to be able to initialize a parallelepiped rectangle with the length,
height, and the self-added width. To allow this relationaship, you would change the TRectangle class as follows:
//---------------------------------------------------------------------------
#ifndef RectangleH
#define RectangleH
//---------------------------------------------------------------------------
class TRectangle
public:
~TRectangle();
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:
//---------------------------------------------------------------------------
#include "Box.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TBox::TBox(const TBox& B)
: Width(B.Width)
Length = B.Length;
Height = B.Height;
//---------------------------------------------------------------------------
TBox::~TBox()
//---------------------------------------------------------------------------
Width = 0.00;
else
Width = W;
//---------------------------------------------------------------------------
setLength(L);
setHeight(H);
setWidth(W);
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
As you can see, the derived class now has access to the member variables of the parent class and can use them to safely perform the
needed calculations.
Inheriting Objects
1. To create a protected access level on the parent object, make the following change in the Person.h file:
//---------------------------------------------------------------------------
#ifndef PersonH
#define PersonH
#include <iostream>
//---------------------------------------------------------------------------
class TPerson
public:
~TPerson();
protected:
string FirstName;
string LastName;
private:
};
//---------------------------------------------------------------------------
#endif
#define StudentH
#include "Person.h"
//---------------------------------------------------------------------------
public:
TStudent();
~TStudent();
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:
//---------------------------------------------------------------------------
#include "Student.h"
//---------------------------------------------------------------------------
TStudent::TStudent()
: TPerson("John", "Doe"),
DayOfBirth(1),
MonthOfBirth(1),
YearOfBirth(1990),
Gender(0)
//---------------------------------------------------------------------------
: TPerson(fn, ln),
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
: TPerson(Stud.FirstName, Stud.LastName),
DayOfBirth(Stud.DayOfBirth), MonthOfBirth(Stud.MonthOfBirth),
YearOfBirth(Stud.YearOfBirth), Gender(Stud.Gender)
//---------------------------------------------------------------------------
TStudent::~TStudent()
//---------------------------------------------------------------------------
if( Gender == 1 )
return "Male";
return "Female";
else
return "Unspecified";
//--------------------------------------------------------------------------
5. To prepare the program for a test, change the Main.cpp file as follows:
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
#include "Student.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TStudent P;
P.setFirstName("Hermine");
P.setLastName("Akono");
P.setDayOfBirth(12);
P.setMonthOfBirth(5);
P.setYearOfBirth(1988);
P.setGender(2);
ShowInfo(P);
return 0;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "Student.h"
//---------------------------------------------------------------------------
TStudent::TStudent()
: TPerson("John", "Doe"),
DayOfBirth(1),
MonthOfBirth(1),
YearOfBirth(1990),
Gender(0)
//---------------------------------------------------------------------------
: TPerson(fn, ln),
//---------------------------------------------------------------------------
: TPerson(fn, ln),
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
: TPerson(Stud.FirstName, Stud.LastName),
DayOfBirth(Stud.DayOfBirth), MonthOfBirth(Stud.MonthOfBirth),
YearOfBirth(Stud.YearOfBirth), Gender(Stud.Gender)
//---------------------------------------------------------------------------
TStudent::~TStudent()
//---------------------------------------------------------------------------
if( Gender == 1 )
return "Male";
return "Female";
else
return "Unspecified";
//--------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
#include "Student.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TStudent P;
P.setFirstName("Hermine");
P.setLastName("Akono");
P.setDayOfBirth(12);
P.setMonthOfBirth(5);
P.setYearOfBirth(1988);
P.setGender(2);
ShowInfo(P);
return 0;
//---------------------------------------------------------------------------
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.
//---------------------------------------------------------------------------
#ifndef AddressH
#define AddressH
#include <iostream>
//---------------------------------------------------------------------------
class TAddress
public:
string s = "MD",
string z = "20900");
~TAddress();
protected:
string Address;
string City;
string State;
string ZIPCode;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include "Address.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TAddress::TAddress(const TAddress& d)
//---------------------------------------------------------------------------
TAddress::~TAddress()
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#ifndef StaffH
#define StaffH
#include <iostream>
#include "Person.h"
#include "Address.h"
//---------------------------------------------------------------------------
public:
TStaff();
~TStaff();
protected:
double Salary;
char EmploymentStatus;
int MaritalStatus;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include "Staff.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TStaff::TStaff()
//---------------------------------------------------------------------------
: TPerson(fn, ln),
TAddress(a, c, s, z),
//---------------------------------------------------------------------------
TStaff::TStaff(const TStaff& S)
: Salary(S.Salary),
EmploymentStatus(S.EmploymentStatus),
MaritalStatus(S.MaritalStatus)
//---------------------------------------------------------------------------
TStaff::~TStaff()
//---------------------------------------------------------------------------
return 12.42;
else
return 12.42;
//---------------------------------------------------------------------------
string EStatus;
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 MStatus;
switch(MaritalStatus)
case 1:
MStatus = "Single";
break;
case 2:
MStatus = "Married";
break;
case 3:
MStatus = "Widow";
break;
case 4:
MStatus = "Divorcé";
break;
default:
return MStatus;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
#include "Staff.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TStaff Empl;
Empl.setFirstName("Mark");
Empl.setLastName("Azzuri");
Empl.setCity("Hyattsville");
Empl.setState("MD");
Empl.setZIPCode("20740");
Empl.setSalary(18.05);
Empl.setEmplStatus('F');
Empl.setMaritalStatus(1);
ShowInfo(Empl);
return 0;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
#include "Staff.h"
//---------------------------------------------------------------------------
double Salary;
char EmplStatus;
int 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);
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TStaff Empl;
NewEmployee(Empl);
system("cls");
ShowInfo(Empl);
return 0;
//---------------------------------------------------------------------------
Inheritance Review
//---------------------------------------------------------------------------
#ifndef CircleH
#define CircleH
//---------------------------------------------------------------------------
class TCircle
public:
TCircle(double r = 0.00);
~TCircle();
protected:
double Radius;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include <iomanip>
#include "Circle.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TCircle::TCircle(double r)
: Radius(r)
//---------------------------------------------------------------------------
TCircle::~TCircle()
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#ifndef SphereH
#define SphereH
#include "Circle.h"
//---------------------------------------------------------------------------
public:
TSphere(double x);
~TSphere() {}
private:
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include <iomanip>
#include "Sphere.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TSphere::TSphere(double n)
: TCircle(n)
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#ifndef CylinderH
#define CylinderH
#include "Circle.h"
//---------------------------------------------------------------------------
public:
~TCylinder() {}
private:
double Height;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include <iomanip>
#include "Cylinder.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TCylinder::TCylinder(double x, double y)
: TCircle(x), Height(y)
//---------------------------------------------------------------------------
return TCircle::Area();
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
12. To prepare a test, change the main() function in the Main.cpp file as follows:
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
#include "Circle.h"
#include "Sphere.h"
#include "Cylinder.h"
TCircle e(12.55);
TSphere s(22.25);
e.ShowCharacteristics();
s.ShowCharacteristics();
c.ShowCharacteristics();
return 0;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
#include "Circle.h"
#include "Sphere.h"
#include "Cylinder.h"
e->ShowCharacteristics();
s->ShowCharacteristics();
c->ShowCharacteristics();
return 0;
//---------------------------------------------------------------------------
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>
//---------------------------------------------------------------------------
#include "Circle.h"
#include "Sphere.h"
#include "Cylinder.h"
TCircle *e = s;
e->ShowCharacteristics();
e = c;
e->ShowCharacteristics();
return 0;
//---------------------------------------------------------------------------
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.
1. Click the Circle.h tab and change the declaration of the Area() function as follows:
//---------------------------------------------------------------------------
#ifndef CircleH
#define CircleH
//---------------------------------------------------------------------------
class TCircle
public:
TCircle(double r = 0.00);
~TCircle();
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);
~TCircle();
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);
virtual ~TCircle();
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:
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
};
//---------------------------------------------------------------------------
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
};
//---------------------------------------------------------------------------
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).
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:
//---------------------------------------------------------------------------
#ifndef PolygonH
#define PolygonH
//---------------------------------------------------------------------------
namespace Shapes
class TPolygon
public:
virtual ~TPolygon();
protected:
int NbrOfSides;
char *PolyName;
double Radius;
};
//---------------------------------------------------------------------------
#endif
5. Click the Polygon.cpp tab and implement the member functions as follows:
//---------------------------------------------------------------------------
#include <iostream>
#include "Polygon.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
namespace Shapes
NbrOfSides = s;
Radius = r;
setPolyName(n);
//---------------------------------------------------------------------------
TPolygon::~TPolygon()
delete [] PolyName;
//---------------------------------------------------------------------------
// equilateral triangle
if( n < 3 )
NbrOfSides = 0;
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 )
else //if( n == 11 || n == 12 )
//---------------------------------------------------------------------------
strcpy(PolyName, n);
//---------------------------------------------------------------------------
if( r < 0 )
Radius = 0.00;
else
Radius = r;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
//---------------------------------------------------------------------------
#include "Polygon.h"
Pol->setRadius(15.55);
Pol->setNbrOfSides(25);
Pol->setPolyName("Unknown");
return 0;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#ifndef PolygonH
#define PolygonH
//---------------------------------------------------------------------------
namespace Shapes
class TPolygon
public:
virtual ~TPolygon();
double Area();
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>
#include "Polygon.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
namespace Shapes
. . .
//---------------------------------------------------------------------------
. . .
//---------------------------------------------------------------------------
double TPolygon::Area()
double p = Perimeter();
double r = Apothem();
return p * r / 2;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#ifndef TriangleH
#define TriangleH
#include "Polygon.h"
//---------------------------------------------------------------------------
public:
TTriangle();
TTriangle(double r);
~TTriangle();
double Height();
protected:
private:
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include <math.h>
#include "Triangle.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TTriangle::TTriangle()
setNbrOfSides(3);
setPolyName("Equilateral Triangle");
setRadius(getRadius());
//---------------------------------------------------------------------------
TTriangle::TTriangle(double r)
setNbrOfSides(3);
setPolyName("Equilateral Triangle");
setRadius(r);
//---------------------------------------------------------------------------
TTriangle::~TTriangle()
//---------------------------------------------------------------------------
double TTriangle::Side()
//---------------------------------------------------------------------------
double TTriangle::Apothem()
return Radius / 2;
//---------------------------------------------------------------------------
double TTriangle::Perimeter()
double S = Side();
return 3 * S;
//---------------------------------------------------------------------------
double TTriangle::Height()
//---------------------------------------------------------------------------
void TTriangle::ShapeCharacteristics()
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
#include "Triangle.h"
Tri->setRadius(15.55);
Tri->ShapeCharacteristics();
return 0;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#ifndef SquareH
#define SquareH
#include "Polygon.h"
//---------------------------------------------------------------------------
public:
TPolySquare();
TPolySquare(double r);
~TPolySquare() {}
protected:
private:
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include <math.h>
//---------------------------------------------------------------------------
#include "Square.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TPolySquare::TPolySquare()
setNbrOfSides(4);
setPolyName("Square");
setRadius(getRadius());
//---------------------------------------------------------------------------
TPolySquare::TPolySquare(double r)
setNbrOfSides(4);
setPolyName("Square");
setRadius(r);
//---------------------------------------------------------------------------
double TPolySquare::Side()
//---------------------------------------------------------------------------
double TPolySquare::Apothem()
//---------------------------------------------------------------------------
double TPolySquare::Perimeter()
double S = Side();
return 4 * S;
//---------------------------------------------------------------------------
void TPolySquare::ShapeCharacteristics()
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#ifndef HexagonH
#define HexagonH
#include "Polygon.h"
//---------------------------------------------------------------------------
public:
THexagon();
THexagon(double r);
~THexagon() {}
protected:
private:
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include <math.h>
#include "Hexagon.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
THexagon::THexagon()
setNbrOfSides(6);
setPolyName("Hexagon");
setRadius(getRadius());
//---------------------------------------------------------------------------
THexagon::THexagon(double r)
setNbrOfSides(6);
setPolyName("Hexagon");
setRadius(r);
//---------------------------------------------------------------------------
double THexagon::Side()
return Radius;
//---------------------------------------------------------------------------
double THexagon::Apothem()
//---------------------------------------------------------------------------
double THexagon::Perimeter()
double S = Side();
return 6 * S;
//---------------------------------------------------------------------------
void THexagon::ShapeCharacteristics()
//---------------------------------------------------------------------------
24. Before testing the program, change the Main.cpp file as follows:
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
#include "Triangle.h"
#include "Square.h"
#include "Hexagon.h"
//---------------------------------------------------------------------------
Tri->setRadius(15.55);
Tri->ShapeCharacteristics();
Sq->ShapeCharacteristics();
clrscr();
Hx->setRadius(36.08);
Hx->ShapeCharacteristics();
return 0;
//---------------------------------------------------------------------------
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.
//---------------------------------------------------------------------------
struct TCountry
string Name;
double Population;
string Capital;
char Government;
};
//---------------------------------------------------------------------------
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).
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
//---------------------------------------------------------------------------
struct TSquare
public:
private:
double Side;
};
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TSquare CupHolder;
CupHolder.setSide(35.55);
Properties(CupHolder);
return 0;
//---------------------------------------------------------------------------
To start, if you do not create a constructor, the compiler would create one for you. This is called the default constructor.
Otherwise, you can create your own:
//---------------------------------------------------------------------------
struct TSquare
public:
TSquare();
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:
//---------------------------------------------------------------------------
struct TSquare
public:
TSquare();
virtual ~TSquare();
private:
double Side;
};
//---------------------------------------------------------------------------
TSquare::TSquare()
//---------------------------------------------------------------------------
TSquare::~TSquare()
//---------------------------------------------------------------------------
To allow making copies of objects, the compiler also creates an appropriate constructor for you if you do not define one for your
object. This is called the copy constructor. You can still explicitly create one as follows:
//---------------------------------------------------------------------------
struct TSquare
public:
TSquare();
virtual ~TSquare();
private:
double Side;
};
//---------------------------------------------------------------------------
TSquare::TSquare()
//---------------------------------------------------------------------------
: Side(Sq.Side)
//---------------------------------------------------------------------------
TSquare::~TSquare()
//---------------------------------------------------------------------------
In reality, there are four default functions that the compiler creates for you if you do not define them yourself. Besides the
default constructor, the copy constructor, and the destructor, the compiler also create an overloaded assignment operator
function for you. This can be easily seen on the code completion if you have not yet created this function for an object:
So far, we have been able to assign a variable declared from a class to another variable of the same type. Here is an example:
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
Holder.setSide(35.55);
Properties(Holder);
Loop.setSide(18.04);
TSquare Base(Loop);
Properties(Base);
Properties(Sink);
return 0;
//---------------------------------------------------------------------------
This assignment operation is possible because the compiler is configured to take care of it, using its own default created
overloaded assignment operator function.
Overloading an Operator
The C++ language recognizes 45 operators of various types. The most usual and the most regular operator is the output
extraction operator << used to display anything in C++. The input >> operator is used to retrieve data input. Arithmetic
operators are used to perform numeric operations. The unary operators are used to control the sign or behavior of a variable.
There are many other binary and C++ specific operators. When customized, the arithmetic and any other operators can be
applied to varying circumstances.
When overloaded, the operators are implemented as functions using the operator keyword. For example, the syntax of
overloading the addition operator “+” would be operator+().
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
double A, B;
return 0;
//---------------------------------------------------------------------------
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
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>
//---------------------------------------------------------------------------
double A, B;
A = 266.52;
return 0;
//---------------------------------------------------------------------------
Values of variables
A: 266.52
B: 2.53936e-314
This time, once a variable has been initialized, it holds the appropriate value. Notice that the B variable that has not been
initialized is still holding garbage. If you want to give the value of one variable to another variable, you can use the = operator
between them as follows:
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
double A, B;
A = 266.52;
A = B;
return 0;
//---------------------------------------------------------------------------
The = sign implements the assignment operation. It works on two variables, one on each side of the symbol. After it has
operated, the value that the right variable holds is given to the left variable. An example of executing the above program would
be:
Values of variables
A: 266.52
B: 2.53936e-314
Values of variables
A: 2.53936e-314
B: 2.53936e-314
Notice that although the A variable had been initialized previously, by assigning it to another variable, its value changes. On its
second call, the A variable has lost its previous variable and hods whatever value the B variable was given.
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
double A, B;
A = 266.52;
B = A;
return 0;
//---------------------------------------------------------------------------
The first time the variables are called, the initialized A variable displays a recognizable value while B is still holding garbage. After
B has been initialized, on the second call, both variables hold the same value:
Values of variables
A: 266.52
B: 2.53936e-314
Values of variables
A: 266.52
B: 266.52
To use the assignment operator on your own object, you should (or must) let the compiler know how to handle the assignment
operator on a variable declared from such an object. To do this, create your own implementation of the assignment operator.
The assignment operator is defined using the operator keyword followed by the = symbol and the traditional parentheses of
every function. As a function, the operator must be declared in the body of the class, along with the other method members. In
order for this function to be accessible outside of the class, it should be listed in the public section. Like any member method, the
function should have a return value, at least void. Therefore it could be created as follows:
//---------------------------------------------------------------------------
#ifndef RectangleH
#define RectangleH
//---------------------------------------------------------------------------
class TRectangle
public:
: Length(L), Height(H) {}
TRectangle(const TRectangle& R)
: Length(R.Length), Height(R.Height) {}
~TRectangle() {}
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:
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:
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
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:
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:
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:
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:
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:
//---------------------------------------------------------------------------
Length = Rect.Length;
Height = Rect.Height;
return *this;
//---------------------------------------------------------------------------
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>
//---------------------------------------------------------------------------
double A, B;
A = 1266.52;
B = 3520.46;
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:
: Length(L), Height(H) {}
. . .
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
//---------------------------------------------------------------------------
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
public:
: Length(L), Height(H) {}
. . .
private:
double Length;
double Height;
};
//---------------------------------------------------------------------------
#endif
Since the operator+() is not a member of the class anymore, its implementation becomes:
//---------------------------------------------------------------------------
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:
//---------------------------------------------------------------------------
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:
//---------------------------------------------------------------------------
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>
//---------------------------------------------------------------------------
double A, B, C;
A = 1266.52;
B = 3520.46;
C = A + B;
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
public:
: Length(L), Height(H) {}
. . .
private:
double Length;
double Height;
};
//---------------------------------------------------------------------------
#endif
This time, the function must return a variable of the same type. During its implementation, you can declare a new variable of the
same type, assign each of its variables to the equivalent added variable of the arguments, and then return that variable. Here is
an example:
//---------------------------------------------------------------------------
TRectangle Room;
return Room;
//---------------------------------------------------------------------------
Now we can add two TRectangle variables and store the result in another variable:
//---------------------------------------------------------------------------
Properties(CDCase);
return 0;
//---------------------------------------------------------------------------
To declare the other arithmetic operators, use the same syntax. Here is the header file:
//---------------------------------------------------------------------------
#ifndef RectangleH
#define RectangleH
//---------------------------------------------------------------------------
class TRectangle
public:
: Length(L), Height(H) {}
TRectangle(const TRectangle& R)
: Length(R.Length), Height(R.Height) {}
~TRectangle() {}
private:
double Length;
double Height;
};
//---------------------------------------------------------------------------
#endif
The implementation of these functions also follows the same syntax applied to the addition operator:
//---------------------------------------------------------------------------
#include "Rectangle.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
Length = Rect.Length;
Height = Rect.Height;
return *this;
//---------------------------------------------------------------------------
TRectangle R;
return R;
//---------------------------------------------------------------------------
TRectangle R;
return R;
//---------------------------------------------------------------------------
TRectangle R;
return R;
}//---------------------------------------------------------------------------
TRectangle R;
R.Length = 0;
else
if( y.Height == 0 )
R.Height = 0;
else
return R;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
double A = 1266.52;
double D;
D = A + 350.44;
return 0;
//---------------------------------------------------------------------------
Suppose that, instead of adding two objects, you decide to add a constant number to a class’ variable, as follows:
//---------------------------------------------------------------------------
Properties(Plate);
return 0;
//---------------------------------------------------------------------------
By overloading the addition operator, you can apply this operation to a variable declared from a class. To add a constant to the
variable, you must create a version of the operator+() function that would take a constant and add it to the desired variable.
After the operation is performed, the function must return a new variable that holds the new value (if the function does not
return a value, the operation would be useless; you cannot display it on the console and you cannot assign the result to another
variable). Therefore, the function would be declared as follows:
//---------------------------------------------------------------------------
#ifndef RectangleH
#define RectangleH
//---------------------------------------------------------------------------
class TRectangle
public:
: Length(L), Height(H) {}
. . .
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:
//---------------------------------------------------------------------------
return *this;
//---------------------------------------------------------------------------
You can also add the constant argument to each member variable of the class:
//---------------------------------------------------------------------------
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:
//---------------------------------------------------------------------------
Properties(CDCase);
Properties(Plate);
return 0;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
double A = 1266.52;
double D = 560.25;
A += 350.44;
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>
//---------------------------------------------------------------------------
double A = 1266.52;
double D = 560.25;
A += 350.44;
A += 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.
//---------------------------------------------------------------------------
#ifndef RectangleH
#define RectangleH
//---------------------------------------------------------------------------
class TRectangle
public:
. . .
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:
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
public:
. . .
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:
//---------------------------------------------------------------------------
Length += R.Length;
Height += R.Height;
//---------------------------------------------------------------------------
After implementing this function, you can apply the += operator on a program as follows:
//---------------------------------------------------------------------------
Properties(Rect);
Properties(Plate);
Rect += Recto;
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:
. . .
private:
double Length;
double Height;
};
//---------------------------------------------------------------------------
#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:
//---------------------------------------------------------------------------
Length += d;
Height += d;
//---------------------------------------------------------------------------
Once again, you can apply this operator once the compiler knows what to do with it. Here is an example:
//---------------------------------------------------------------------------
Properties(Rect);
Properties(Plate);
Plate += 15.44;
Properties(Plate);
Rect += Recto;
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:
. . .
private:
. . .
};
//---------------------------------------------------------------------------
#endif
Because the variable that makes the call also gets modified and preserves the newly acquired value, you can reinforce this by
returning a reference instead of a regular object:
//---------------------------------------------------------------------------
#ifndef RectangleH
#define RectangleH
//---------------------------------------------------------------------------
class TRectangle
. . .
public:
. . .
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:
//---------------------------------------------------------------------------
Length += d;
Height += d;
return *this;
//---------------------------------------------------------------------------
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
public:
~TRectangle() {}
private:
double Length;
double Height;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include "Rectangle.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TRectangle::TRectangle(double L, double H)
: Length(L), Height(H)
//---------------------------------------------------------------------------
TRectangle::TRectangle(const TRectangle& R)
: Length(R.Length), Height(R.Height)
//---------------------------------------------------------------------------
Length = L, Height = H;
//---------------------------------------------------------------------------
Length = Rect.Length;
Height = Rect.Height;
return *this;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TRectangle R;
return R;
//---------------------------------------------------------------------------
TRectangle R;
return R;
//---------------------------------------------------------------------------
TRectangle R;
return R;
//---------------------------------------------------------------------------
TRectangle R;
R.Length = 0;
else
if( y.Height == 0 )
R.Height = 0;
else
return R;
//---------------------------------------------------------------------------
return *this;
//---------------------------------------------------------------------------
Length += d;
Height += d;
return *this;
//---------------------------------------------------------------------------
Length += R.Length;
Height += R.Height;
return *this;
//---------------------------------------------------------------------------
Length -= R.Length;
Height -= R.Height;
return *this;
//---------------------------------------------------------------------------
Length *= R.Length;
Height *= R.Height;
return *this;
//---------------------------------------------------------------------------
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>
#include "Rectangle.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
Rect.setDimensions(42.88, 36.14);
Recto.setDimensions(16.52, 22.65);
Rect += Recto;
Properties(Rect);
Rect.setDimensions(42.88, 36.14);
Recto.setDimensions(16.52, 22.65);
Rect -= Recto;
Properties(Rect);
Rect.setDimensions(42.88, 36.14);
Recto.setDimensions(16.52, 22.65);
Rect.setDimensions(42.88, 36.14);
Recto.setDimensions(16.52, 22.65);
Rect /= Recto;
Properties(Rect);
return 0;
//---------------------------------------------------------------------------
Length: 59.40
Height: 58.79
Perimeter: 236.38
Area: 3492.13
Length: 26.36
Height: 13.49
Perimeter: 79.70
Area: 355.60
Length: 708.38
Height: 818.57
Perimeter: 3053.90
Area: 579857.36
Length: 2.60
Height: 1.60
Perimeter: 8.38
Area: 4.14
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
double A = 1266.52;
double D = 560.25;
if( A >= D )
return 0;
//---------------------------------------------------------------------------
To perform this operation, the compiler examines the value of each variable. If the left variable has a value greater than that of
the right variable, the comparison returns true; otherwise, the comparison returns false. This means a comparison opration is in
fact a function that applies to two variables. Because the C++ compiler does not allow an overloaded operator to take two
arguments, the function must be declared outside of the class. Since the function needs to have access to the private (or
protected) members of the variables, it should be declared as a friend of the function. The data type common to Boolean
operations and functions is bool and will be used to return the result of comparison functions:
//---------------------------------------------------------------------------
#ifndef RectangleH
#define RectangleH
//---------------------------------------------------------------------------
class TRectangle
public:
. . .
private:
. . .
};
//---------------------------------------------------------------------------
Once again, the implementation of this function depends on the class or the intended result. For example, if the class is a square
or any regular polygon, because its sides are equal, you can perform the comparison on the length of the sides:
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
struct TSquare
public:
~TSquare() {}
private:
double Side;
};
//---------------------------------------------------------------------------
return false; // If you get here, the comparison was not successful
//---------------------------------------------------------------------------
Side = q.Side;
return *this;
//---------------------------------------------------------------------------
Side = Side + P;
return *this;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
return 0;
//---------------------------------------------------------------------------
If the program consists of a restaurant menu, you can perform the comparison on the number of items ordered. If the classes
are bank accounts, you can compare the balance on each account. In reality, every overloaded operator depends on your
intentions and can be applied on one or more member variables and you can decide what validates the truthfulness of the
comparison. For a geometric figure like the rectangle, we will compare the area of each rectangle. When the area of the left
rectangle is greater than the area of the right rectangle, we will decide that the left rectangle if greater than the right rectangle:
//---------------------------------------------------------------------------
return true;
return false;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
Rect.setDimensions(42.88, 36.14);
Recto.setDimensions(16.52, 22.65);
return 0;
//---------------------------------------------------------------------------
The other comparison operators can be overloaded following the same logic. For example, here are their declarations:
//---------------------------------------------------------------------------
#ifndef RectangleH
#define RectangleH
//---------------------------------------------------------------------------
class TRectangle
public:
. . .
private:
double Length;
double Height;
};
//---------------------------------------------------------------------------
#endif
Their implementations also follow the same logic applied to the += operator:
//---------------------------------------------------------------------------
#include "Rectangle.h"
//---------------------------------------------------------------------------
. . .
//---------------------------------------------------------------------------
return true;
return false;
//---------------------------------------------------------------------------
return true;
return false;
//---------------------------------------------------------------------------
return true;
return false;
//---------------------------------------------------------------------------
return true;
return false;
//---------------------------------------------------------------------------
return true;
return false;
//---------------------------------------------------------------------------
return true;
return false;
//---------------------------------------------------------------------------
. . .
//---------------------------------------------------------------------------
This allows you to perform any comparison on variables declared from the class. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include "Rectangle.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
cout << "Rect and Recto don't share the same size\n";
return 0;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
double A = 1266.52;
double D = 560.25;
return 0;
//---------------------------------------------------------------------------
As it does with regular variables, the compiler can be configured appropriately when the output operator is applied to a variable
declared from a class. This makes it possible to write a statement such as:
TCountry Pais;
cout << Pais;
To appropriately display a variable on the console, you must overloaded the output << operator and tell the compiler how to
behave when this operator is used on the variable. The function used to perform this operation is structured as operator<<().
Like any of the operators we have used so far, the compiler needs to know what variable is being worked on. Therefore, you
must at least pass this variable as argument. When the output operator is executed, the intention is only to display the value(s)
of the variable without modification. For this reason, the argument should be passed as a constant reference:
//---------------------------------------------------------------------------
#ifndef RectangleH
#define RectangleH
//---------------------------------------------------------------------------
class TRectangle
. . .
public:
. . .
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:
. . .
private:
. . .
};
//---------------------------------------------------------------------------
#endif
Since the ostream is an external class, make sure you include its header file, which is iostream.h. Now that the overloaded
operator function is using two variables, it cannot be part of the class: you must declare it outside of the class. In order for the
function to access private (and/or protected) member variables of the class, you should make it a friend of the class. The
function becomes:
//---------------------------------------------------------------------------
#ifndef RectangleH
#define RectangleH
#include <iostream>
//---------------------------------------------------------------------------
class TRectangle
. . .
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:
//---------------------------------------------------------------------------
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:
//---------------------------------------------------------------------------
return 0;
//---------------------------------------------------------------------------
In practical terms, the output operator “<<” is a binary operator: it operates on two values. Consequently, it provides a result in
the form of a third value. This means the operator<<() function should return a value. Because it is applied on the ostream class
which allows it to tell the ostream class how to display data on the right side of the operator, the ostream argument is the one
that gets modified and that is being worked on. The second argument, in this case the TRectangle is simply the source of data
that will be displayed. Therefore, the function should return an instance of the ostream class. This means the function should be
declared as follows:
//---------------------------------------------------------------------------
#ifndef RectangleH
#define RectangleH
#include <iostream>
//---------------------------------------------------------------------------
class TRectangle
. . .
public:
. . .
private:
. . .
};
//---------------------------------------------------------------------------
#endif
This time, the function should return the result of the operation:
//---------------------------------------------------------------------------
Ostr << "(" << R.Length << ", " << R.Height << ")";
return Ostr;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
double A;
cin >> 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
. . .
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:
//---------------------------------------------------------------------------
return Istr;
//---------------------------------------------------------------------------
Now the cin >> operator can use an instance of your class the same way it would request the value of a regular variable. The
cout and cin as defined can be called from any function. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include "Rectangle.h"
//---------------------------------------------------------------------------
cout << R;
//---------------------------------------------------------------------------
TRectangle Rect;
Properties(Rect);
return 0;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
//---------------------------------------------------------------------------
struct TCleaningOrder
int NumberOfShirts;
int NumberOfPants;
int NumberOfMisc;
};
TCleaningOrder Order;
double TotalOrder;
try {
if(Order.NumberOfMisc > 0)
else
TotalPriceMisc = 0.00;
catch(...)
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:
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
//---------------------------------------------------------------------------
struct TCleaningOrder
int NumberOfShirts;
int NumberOfPants;
int NumberOfMisc;
};
//---------------------------------------------------------------------------
TCleaningOrder Order;
double TotalOrder;
try {
if( isdigit(Order.NumberOfShirts) )
throw Order.NumberOfShirts;
if( isdigit(Order.NumberOfPants) )
throw Order.NumberOfPants;
if( isdigit(Order.NumberOfMisc) )
throw Order.NumberOfMisc;
if(Order.NumberMisc > 0)
else
TotalPriceMisc = 0.00;
catch(const int n)
catch(...)
return 0;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
class TCalculator
public:
double Operand1;
double Operand2;
char Operator;
};
//---------------------------------------------------------------------------
TCalculator Calc;
double Result;
cout << "This program allows you to perform an operation on two numbers\n";
try {
throw Calc.Operator;
if(Calc.Operator == '/')
if(Calc.Operand2 == 0)
throw 0;
switch(Calc.Operator)
case '+':
break;
case '-':
break;
case '*':
break;
case '/':
break;
cout << "\n" << Calc.Operand1 << " " << Calc.Operator << " "
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;
//---------------------------------------------------------------------------
To proceed, enter
Second number: 32
1450 / 32 = 45.3125
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
class TCalculator
public:
double Operand1;
double Operand2;
char Operator;
};
//---------------------------------------------------------------------------
double R;
switch(p)
case '+':
R = x + y;
break;
case '-':
R = x - y;
break;
case '*':
R = x * y;
break;
case '/':
if( y == 0 )
throw 0;
R = x / y;
break;
return R;
//---------------------------------------------------------------------------
TCalculator Calc;
double Result;
cout << "This program allows you to perform an operation of two numbers\n";
try {
throw Calc.Operator;
cout << "\n" << Calc.Operand1 << " " << Calc.Operator << " "
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;
//---------------------------------------------------------------------------
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>
//---------------------------------------------------------------------------
struct TCleaningOrder
public:
TCleaningOrder();
~TCleaningOrder();
void ProcessOrder();
void DisplayReceipt();
private:
int NumberOfShirts;
int NumberOfPants;
int NumberOfMisc;
double TotalPriceShirts;
double TotalPricePants;
double TotalPriceMisc;
double TotalOrder;
};
//---------------------------------------------------------------------------
TCleaningOrder::TCleaningOrder()
//---------------------------------------------------------------------------
TCleaningOrder::~TCleaningOrder()
//---------------------------------------------------------------------------
void TCleaningOrder::ProcessOrder()
double PriceMisc;
try {
if( isdigit(NumberOfShirts) )
throw NumberOfShirts;
if( isdigit(NumberOfPants) )
throw NumberOfPants;
if( isdigit(NumberOfMisc) )
throw NumberOfMisc;
if(NumberMisc > 0)
else
TotalPriceMisc = 0.00;
catch(const int n)
catch(...)
//---------------------------------------------------------------------------
void TCleaningOrder::DisplayReceipt()
//---------------------------------------------------------------------------
TCleaningOrder Order;
Order.ProcessOrder();
clrscr();
Order.DisplayReceipt();
return 0;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
class TCalculator
public:
TCalculator();
void RequestOperands();
private:
double Operand1;
double Operand2;
char Operator;
};
//---------------------------------------------------------------------------
TCalculator::TCalculator()
//---------------------------------------------------------------------------
void TCalculator::RequestOperands()
try {
throw Operator;
catch(const char c)
cout << "Bad Operator: " << c << " is not a valid operator";
//---------------------------------------------------------------------------
Operand1 = Num;
Operator = c;
Operand2 = Denom;
//---------------------------------------------------------------------------
double R;
switch(Operator)
case '+':
R = Operand1 + Operand2;
break;
case '-':
R = Operand1 - Operand2;
break;
case '*':
R = Operand1 * Operand2;
break;
case '/':
try {
if( Operand2 == 0 )
R = Operand1 / Operand2;
break;
return R;
//---------------------------------------------------------------------------
double Result;
CalcResult();
Result = CalcResult();
cout << "\n" << Operand1 << " " << Operator << " "
//---------------------------------------------------------------------------
TCalculator Calc;
char Oper;
cout << "This program allows you to perform an operation on two numbers\n";
Calc.RequestOperands();
Calc.DisplayResult();
return 0;
//---------------------------------------------------------------------------
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:
//---------------------------------------------------------------------------
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:
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
//---------------------------------------------------------------------------
struct TCleaningOrder
public:
TCleaningOrder();
~TCleaningOrder();
void ProcessOrder();
void DisplayReceipt();
private:
int NumberOfShirts;
int NumberOfPants;
int NumberOfMisc;
double TotalPriceShirts;
double TotalPricePants;
double TotalPriceMisc;
double TotalOrder;
};
//---------------------------------------------------------------------------
TCleaningOrder::TCleaningOrder()
//---------------------------------------------------------------------------
TCleaningOrder::~TCleaningOrder()
//---------------------------------------------------------------------------
if( isdigit(Shirts) )
throw Shirts;
NumberOfShirts = Shirts;
//---------------------------------------------------------------------------
if( isdigit(Pants) )
throw Pants;
NumberOfPants = Pants;
//---------------------------------------------------------------------------
if( isdigit(Misc) )
throw Misc;
NumberOfMisc = Misc;
//---------------------------------------------------------------------------
void TCleaningOrder::ProcessOrder()
double PriceMisc;
try {
setShirts(Shirts);
setPants(Pants);
setMisc(Misc);
if(getMisc() > 0)
else
TotalPriceMisc = 0.00;
catch(const int n)
catch(...)
//---------------------------------------------------------------------------
void TCleaningOrder::DisplayReceipt()
//---------------------------------------------------------------------------
TCleaningOrder Order;
Order.ProcessOrder();
clrscr();
Order.DisplayReceipt();
return 0;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
class TCalculator
public:
TCalculator();
void RequestOperands();
private:
double Operand1;
double Operand2;
char Operator;
};
//---------------------------------------------------------------------------
TCalculator::TCalculator()
//---------------------------------------------------------------------------
setOperand1(Oper1);
setOperator(Opr);
setOperand2(Oper2);
//---------------------------------------------------------------------------
void TCalculator::RequestOperands()
char Oper;
try {
setOperand1(Number1);
setOperator(Oper);
setOperand2(Number2);
CalcResult();
catch(const char n)
cout << "\nOperation Error: " << n << " is not a valid operator";
cout << "\nError: " << BadOperand << " is not a valid number";
catch(const int n)
cout << "\nBad Operation: Division by " << n << " not allowed";
//---------------------------------------------------------------------------
throw Oper1;
Operand1 = atof(Oper1);
//---------------------------------------------------------------------------
return Operand1;
//---------------------------------------------------------------------------
throw Oper2;
Operand2 = atof(Oper2);
//---------------------------------------------------------------------------
return Operand2;
//---------------------------------------------------------------------------
throw Symbol;
Operator = Symbol;
//---------------------------------------------------------------------------
return Operator;
//---------------------------------------------------------------------------
setOperand1(Oper1);
setOperator(Opr);
setOperand2(Oper2);
//---------------------------------------------------------------------------
double R;
switch(Operator)
case '+':
R = Operand1 + Operand2;
break;
case '-':
R = Operand1 - Operand2;
break;
case '*':
R = Operand1 * Operand2;
break;
case '/':
try {
if( Operand2 == 0 )
R = Operand1 / Operand2;
break;
return R;
//---------------------------------------------------------------------------
double Result;
CalcResult();
Result = CalcResult();
cout << "\n" << Operand1 << " " << Operator << " "
//---------------------------------------------------------------------------
TCalculator Calc;
char Oper;
cout << "This program allows you to perform an operation on two numbers\n";
Calc.RequestOperands();
Calc.DisplayResult();
return 0;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
//---------------------------------------------------------------------------
class TCalculator
public:
TCalculator();
void RequestOperands();
private:
double Operand1;
double Operand2;
char Operator;
};
//---------------------------------------------------------------------------
TCalculator::TCalculator()
//---------------------------------------------------------------------------
setOperand1(Oper1);
setOperator(Opr);
setOperand2(Oper2);
//---------------------------------------------------------------------------
void TCalculator::RequestOperands()
char Oper;
try {
setOperand1(Number1);
setOperator(Oper);
setOperand2(Number2);
CalcResult();
catch(const char n)
cout << "\nOperation Error: " << n << " is not a valid operator";
cout << "\nError: " << BadOperand << " is not a valid number";
catch(const int n)
cout << "\nBad Operation: Division by " << n << " not allowed";
//---------------------------------------------------------------------------
throw Oper1;
Operand1 = atof(Oper1);
//---------------------------------------------------------------------------
return Operand1;
//---------------------------------------------------------------------------
throw Oper2;
Operand2 = atof(Oper2);
//---------------------------------------------------------------------------
return Operand2;
//---------------------------------------------------------------------------
throw Symbol;
Operator = Symbol;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#ifndef CalculatorH
#define CalculatorH
//---------------------------------------------------------------------------
class TCalculator
public:
TCalculator();
void RequestOperands();
private:
double Operand1;
double Operand2;
char Operator;
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include <iostream>
#include "Calculator.h"
//---------------------------------------------------------------------------
TCalculator::TCalculator()
//---------------------------------------------------------------------------
setOperand1(Oper1);
setOperator(Opr);
setOperand2(Oper2);
//---------------------------------------------------------------------------
void TCalculator::RequestOperands()
char Oper;
try {
setOperand1(Number1);
setOperator(Oper);
setOperand2(Number2);
CalcResult();
catch(const char n)
cout << "\nOperation Error: " << n << " is not a valid operator";
cout << "\nError: " << BadOperand << " is not a valid number";
catch(const int n)
cout << "\nBad Operation: Division by " << n << " not allowed";
//---------------------------------------------------------------------------
throw Oper1;
Operand1 = atof(Oper1);
//---------------------------------------------------------------------------
return Operand1;
//---------------------------------------------------------------------------
throw Oper2;
Operand2 = atof(Oper2);
//---------------------------------------------------------------------------
return Operand2;
//---------------------------------------------------------------------------
throw Symbol;
Operator = Symbol;
//---------------------------------------------------------------------------
return Operator;
//---------------------------------------------------------------------------
setOperand1(Oper1);
setOperator(Opr);
setOperand2(Oper2);
//---------------------------------------------------------------------------
double R;
switch(Operator)
case '+':
R = Operand1 + Operand2;
break;
case '-':
R = Operand1 - Operand2;
break;
case '*':
R = Operand1 * Operand2;
break;
case '/':
try {
if( Operand2 == 0 )
R = Operand1 / Operand2;
break;
return R;
//---------------------------------------------------------------------------
double Result;
CalcResult();
Result = CalcResult();
cout << "\n" << Operand1 << " " << Operator << " "
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
#include "Calculator.h"
//---------------------------------------------------------------------------
TCalculator Calc;
char Oper;
cout << "This program allows you to perform an operation on two numbers\n";
Calc.RequestOperands();
Calc.DisplayResult();
return 0;
//---------------------------------------------------------------------------
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.
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>
//---------------------------------------------------------------------------
MachineIsWorking = false;
return 0;
//---------------------------------------------------------------------------
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>
//---------------------------------------------------------------------------
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
number 5:
#include <iostream>
//---------------------------------------------------------------------------
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>
//---------------------------------------------------------------------------
int Number;
switch (Number)
case 1:
break;
case 2:
break;
case 3:
break;
default:
cout << endl << Number << " is out of the requested range.";
return 0;
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>
void main()
PriceMoreThan100 = 0;
else
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:
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.
#include <iostream>
//---------------------------------------------------------------------------
return 0;
Number 0
Number 1
Number 2
Number 3
Number 4
Number 5
Number 6
Number 7
Number 8
Number 9
Number 10
Number 11
Number 12
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>
int main()
char StudentName[10];
char Answer[10];
for(;;)
Answer[0] = toupper(Answer[0]);
break;
return 0;
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>
double s = 0;
s += Numbers[i];
return s;
int main()
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>
int main()
return 0;
double s = 0;
s += Numbers[i];
return s;
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()
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()
void Function()
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>
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
union TRectangle
struct // Location
int x1;
int y1;
int x2;
int y2;
};
struct // Dimensions
double Length;
double Height;
};
};
//---------------------------------------------------------------------------
TRectangle Recto;
char Choice;
<< Recto.x1 << ", " << Recto.y1 << ") to B("
else
return 0;
//---------------------------------------------------------------------------
1 - Location
2 - Dimension
First point
X coordinate: -4
Y coordinate: 2
Second point
X coordinate: 5
Y coordinate: 1
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.
● 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:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
getch();
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:
//---------------------------------------------------------------------------
you should include the conio.h library that has the getch() function. */
#include <iostream>
#include <conio>
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
The current C++ Standard recommends that the main() function return
*/
/* Because we are using Borland C++, we will explicitly prompt the user
getch();
return 0;
//---------------------------------------------------------------------------
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.
#ifndef CIRCLE_H
#define CIRCLE_H
struct Circle
public:
Circle();
double getRadius();
double Diameter();
double Circumference();
double Area();
void Display();
protected:
double Radius;
private:
};
#endif
#include <iostream.h>
#include "circle.h"
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;
double Circle::Circumference()
double Circle::Area()
void Circle::Display()
#ifndef SPHERE_H
#define SPHERE_H
public:
double Volume();
void Show();
private:
};
#endif
#include <iostream.h>
#include "circle.h"
#include "sphere.h"
double Sphere::Volume()
void Sphere::Show()
#include "circle.h"
#include "sphere.h"
void main()
circle.Display();
circ.setRadius(12.50);
circ.Display();
Sphere sphere; // A sphere that has its own radius, using the functions
sphere.Show();
Circle Properties
Radius = 0
Diameter = 0
Circumference = 0
Area = 0
Circle Properties
Radius = 12.5
Diameter = 25
Circumference = 78.5397
Area = 490.873
Circle Properties
Radius = 8.95
Diameter = 17.9
Circumference = 56.2345
Area = 251.649
Volume = 3003.01
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()
return 0;
Version 2
#include <iostream>
int main()
return 0;
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()
PriceMoreThan100 = 0;
else
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>
string GetName()
return FN;
int main()
string FullName;
double Hours;
FullName = GetName();
Hours = GetHours(FullName);
cout << "\nWeekly Hours: " << Hours << " hours\n\n";
return 0;
return TotalHours;
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()
PassByValue(Boys, Girls);
Reference(Boys, Girls);
Pointers(&Boys, &Girls);
b += 3, g += 4;
b = b + 8, g = g + 5;
*b = 44, *g = 52;
Boys = 3
Girls = 5
Boys = 6
Girls = 9
Boys = 3
Girls = 5
Boys = 11
Girls = 10
Boys = 11
Girls = 10
Boys = 44
Girls = 52
Boys = 44
Girls = 52
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.
#ifndef CUBE_H
#define CUBE_H
class Cube
public:
Cube();
~Cube();
double getSide();
double Area();
double Volume();
void Properties();
private:
double Side;
};
#endif
#include <iostream.h>
#include "cube.h"
Cube::Cube()
Cube::~Cube()
void Cube::setSide(double s)
Side = s <= 0 ? 1 : s;
double Cube::getSide()
return Side;
double Cube::Area()
double Cube::Volume()
void Cube::Properties()
#include "cube.h"
void main()
Cube cube;
cube.setSide(-12.55);
cube.Properties();
Cube de;
de.setSide(28.15);
de.Properties();
Side = 1
Area = 6
Volume = 1
Side = 28.15
Area = 4754.53
Volume = 22306.7
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;
};
double w, h;
cin >> w;
cin >> h;
MagazineCover(Cover);
getchar();
return 0;
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).
#ifndef _SHAPE_H
#define _SHAPE_H
class FRectangle
public:
FRectangle(double l = 0, double w = 0)
: Length(l), Width(w) {}
void Properties();
private:
double Length;
double Width;
};
#endif // _SHAPE_H
#include <iostream.h>
#include "shape.h"
Length = lgt;
Width = wdt;
return Length;
return Width;
void FRectangle::Properties()
#ifndef BRICK_H_
#define BRICK_H_
#include "shape.h"
class Brick
public:
Brick() {}
void Display();
private:
FRectangle shape;
char* Color;
char* Texture;
double Thickness;
};
#endif // BRICK_H_
#include <iostream.h>
#include "brick.h"
Thickness = Tck;
Color = clr;
Texture = txr;
shape.setLength(l);
shape.setWidth(w);
setThickness(t);
return Color;
return Texture;
void Brick::Display()
#include "shape.h"
#include "brick.h"
void main()
Brick brick;
brick.setColor("Bone White");
brick.setTexture("Early Breeze");
brick.Display();
Brick characteristics
Length = 12.5
Width = 8.75
Area = 109.375
Volume = 607.031
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:
void Properties();
private:
double Length;
double Height;
double Width;
};
#endif
#include <iostream.h>
#include "box.h"
Length = l;
Height = h;
Width = w;
return Length;
return Height;
return Width;
void ShoeBox::Properties()
#include "box.h"
void main()
Size6.Properties();
Length = 8.65
Height = 4.25
Width = 4.15
Area = 162.12
Volume = 152.564
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>
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
class TListOfStudents
public:
class TStudent
private:
string FullName;
int Age;
char Gender;
public:
TStudent();
};
private:
TStudent Item[Maximum];
public:
TListOfStudents() : Count(0){}
inline ~TListOfStudents() {}
int Count;
};
//---------------------------------------------------------------------------
TListOfStudents::TStudent::TStudent()
FullName = "";
Age = 0.00;
Gender = 'M';
//---------------------------------------------------------------------------
FullName = FName;
Age = a;
Gender = g;
//---------------------------------------------------------------------------
Item[Count] = d;
Count++;
//---------------------------------------------------------------------------
return Item[n];
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TListOfStudents ListOfItems;
CreateList(ListOfItems);
DisplayList(ListOfItems);
return 0;
//---------------------------------------------------------------------------
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");
Pupil.setAge(16);
Pupil.setGender('M');
ListOfItems.Add(Pupil);
//---------------------------------------------------------------------------
<< "\t";
switch(ListOfItems.Retrieve(i).getGender())
case 'm':
case 'M':
break;
case 'f':
case 'F':
break;
default:
//---------------------------------------------------------------------------
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 Height;
double Width;
};
void Paper::GetDimensions()
void Paper::Properties()
void main()
int Samples;
Paper Label[100];
Label[i].GetDimensions();
Label[j].Properties();
Height: 3.25
Width: 3.25
Height: 2.15
Width: 4.55
Label No. 0
Height = 3.25
Width = 3.25
Perimeter = 12.5625
Area = 10.5625
Label No. 1
Height = 2.15
Width = 4.55
Perimeter = 11.7825
Area = 9.7825
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.
//---------------------------------------------------------------------------
#ifndef PersonH
#define PersonH
//---------------------------------------------------------------------------
class TPerson
private:
char* FirstName;
char* LastName;
char* Address;
char* City;
char* State;
long ZIPCode;
public:
TPerson();
virtual ~TPerson();
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
#include <iostream>
#pragma hdrstop
#include "Person.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
//---------------------------------------------------------------------------
strcpy(FName, FirstName);
strcat(FName, LastName);
return FName;
//---------------------------------------------------------------------------
__fastcall TPerson::TPerson()
: ZIPCode(0)
strcpy(FirstName, "John");
strcpy(LastName, "Doe");
//---------------------------------------------------------------------------
: ZIPCode(0)
strcpy(FirstName, FName);
strcpy(LastName, LName);
//---------------------------------------------------------------------------
: ZIPCode(ZIP)
strcpy(FirstName, FName);
strcpy(LastName, LName);
strcpy(Address, Adr);
strcpy(City, Ct);
strcpy(State, St);
//---------------------------------------------------------------------------
: ZIPCode(Pers.ZIPCode)
strcpy(FirstName, Pers.FirstName);
strcpy(LastName, Pers.LastName);
strcpy(Address, Pers.Address);
strcpy(City, Pers.City);
strcpy(State, Pers.State);
//---------------------------------------------------------------------------
strcpy(FirstName, FN);
//---------------------------------------------------------------------------
strcpy(LastName, LN);
//---------------------------------------------------------------------------
strcpy(Address, Adr);
//---------------------------------------------------------------------------
strcpy(City, CT);
//---------------------------------------------------------------------------
strcpy(State, St);
//---------------------------------------------------------------------------
ZIPCode = ZIP;
//---------------------------------------------------------------------------
__fastcall TPerson::~TPerson()
delete [] FirstName;
delete [] LastName;
delete [] Address;
delete [] City;
delete [] State;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <iostream>
#pragma hdrstop
#include "Person.h"
//---------------------------------------------------------------------------
#pragma argsused
TPerson ProcessRegistration();
//---------------------------------------------------------------------------
DisplayInformation(Employee);
return 0;
//---------------------------------------------------------------------------
TPerson ProcessRegistration()
long ZC;
cin.getline(Addr, 40);
cin.getline(CT, 32);
cin.getline(St, 30);
return Pers;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
City: Washington
State: DC
Employee Identification
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
//---------------------------------------------------------------------------
class FList
public:
FList();
virtual ~FList();
private:
int Counter;
ItemType Item[MaxItems];
};
//---------------------------------------------------------------------------
#endif
#pragma hdrstop
#include "List.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
FList::FList()
: Counter(0)
//---------------------------------------------------------------------------
FList::~FList()
}//---------------------------------------------------------------------------
return Counter;
//---------------------------------------------------------------------------
return Pos-1;
//---------------------------------------------------------------------------
return false;
else
Item[Counter] = NewItem;
Counter++;
return true;
//---------------------------------------------------------------------------
return 0;
else
return Item[Pos];
//---------------------------------------------------------------------------
return false;
else
Item[Index(i-1)] = Item[Index(i)];
Counter--;
return true;
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
#pragma hdrstop
#include "List.h"
//---------------------------------------------------------------------------
#pragma argsused
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 << "\nItem No." << i + 1 << ": " << List.Retrieve(i);
cout << "\nNumber of items: " << List.Count() << " items\n\n";
List.Delete(5);
List.Delete(2);
cout << "\nItem No." << i + 1 << ": " << List.Retrieve(i);
cout << "\nNumber of items: " << List.Count() << " items\n\n";
getch();
return 0;
//---------------------------------------------------------------------------
FunctionX
- Car Rental Order Processing Exercise
Practical
Learning
Logo File: car.h
Header
#define CAR_H
class Car
public:
Car();
virtual ~Car();
private:
char* MakeModel;
int CarYear;
int Category;
};
#endif // CAR_H
#include <iostream>
#include <string>
#include "Car.h"
//--------------------------------------------------------------------
Car::Car()
setCarYear(2000);
setCategory(1);
//--------------------------------------------------------------------
setMakeModel(MM);
setCarYear(Y);
setCategory(Cat);
//--------------------------------------------------------------------
Car::~Car()
// delete [] MakeModel;
//--------------------------------------------------------------------
strcpy(MakeModel, m);
//--------------------------------------------------------------------
return MakeModel;
//--------------------------------------------------------------------
CarYear = y;
//--------------------------------------------------------------------
return CarYear;
//--------------------------------------------------------------------
Category = c;
//--------------------------------------------------------------------
return Category;
//--------------------------------------------------------------------
#define CUSTOMER_H
class Customer
private:
char* FirstName;
char* LastName;
char* Address;
char* City;
char* State;
long ZIPCode;
public:
Customer();
~Customer();
};
#endif // CUSTOMER_H
//---------------------------------------------------------------------------
#include <iostream>
#pragma hdrstop
#include "Customer.h"
//---------------------------------------------------------------------------
strcpy(FName, FirstName);
strcat(FName, LastName);
return FName;
//---------------------------------------------------------------------------
Customer::Customer()
: ZIPCode(0)
strcpy(FirstName, "John");
strcpy(LastName, "Doe");
//---------------------------------------------------------------------------
: ZIPCode(0)
strcpy(FirstName, FName);
strcpy(LastName, LName);
//---------------------------------------------------------------------------
: ZIPCode(ZIP)
strcpy(FirstName, FName);
strcpy(LastName, LName);
strcpy(Address, Adr);
strcpy(City, Ct);
strcpy(State, St);
//---------------------------------------------------------------------------
: ZIPCode(Pers.ZIPCode)
strcpy(FirstName, Pers.FirstName);
strcpy(LastName, Pers.LastName);
strcpy(Address, Pers.Address);
strcpy(City, Pers.City);
strcpy(State, Pers.State);
//---------------------------------------------------------------------------
strcpy(FirstName, FN);
//---------------------------------------------------------------------------
strcpy(LastName, LN);
//---------------------------------------------------------------------------
strcpy(Address, Adr);
//---------------------------------------------------------------------------
strcpy(City, CT);
//---------------------------------------------------------------------------
strcpy(State, St);
//---------------------------------------------------------------------------
ZIPCode = ZIP;
//---------------------------------------------------------------------------
Customer::~Customer()
delete [] FirstName;
delete [] LastName;
delete [] Address;
delete [] City;
delete [] State;
//---------------------------------------------------------------------------
#define INVOICE_H
#include "Customer.h"
#include "Car.h"
#include "RentDate.h"
class Invoice
public:
Invoice();
virtual ~Invoice();
Customer CustomerRegistration();
Car CarSelection();
void ProcessOrder();
void CarExamination();
void ShowOrder();
private:
long Mileage;
char *TankLevel;
char *CarCondition;
};
#endif // INVOICE_H
//
//////////////////////////////////////////////////////////////////////
#include <iostream>
#include <iomanip>
#include <string>
#include "Invoice.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
Invoice::Invoice()
setTankLevel("Empty");
setCarCondition("Good");
//--------------------------------------------------------------------
Invoice::~Invoice()
//--------------------------------------------------------------------
Customer Invoice::CustomerRegistration()
long ZC = 0;
cin.getline(Addr, 40);
cin.getline(CT, 32);
cin.getline(St, 30);
return Cust;
//--------------------------------------------------------------------
Car Invoice::CarSelection()
char strCarSelected[20];
do {
switch(CarType)
case ctEconomy:
if(ModelChosen == 1)
CarSelectedYear = 1999;
else
CarSelectedYear = 1998;
break;
case ctCompact:
if(ModelChosen == 1)
CarSelectedYear = 1999;
else if(ModelChosen == 2)
CarSelectedYear = 2001;
else if(ModelChosen == 3)
CarSelectedYear = 1998;
else
CarSelectedYear = 2002;
break;
case ctStandard:
if(ModelChosen == 1)
CarSelectedYear = 2000;
else
CarSelectedYear = 1998;
break;
case ctFullSize:
if(ModelChosen == 1)
CarSelectedYear = 2000;
else if(ModelChosen == 2)
CarSelectedYear = 1999;
else
CarSelectedYear = 2003;
break;
case ctMiniVan:
if(ModelChosen == 1)
CarSelectedYear = 2001;
else if(ModelChosen == 2)
CarSelectedYear = 2003;
else if(ModelChosen == 3)
CarSelectedYear = 2003;
else
CarSelectedYear = 2000;
break;
case ctSUV:
if(ModelChosen == 1)
CarSelectedYear = 1998;
else if(ModelChosen == 2)
CarSelectedYear = 2003;
else if(ModelChosen == 3)
CarSelectedYear = 2001;
else
CarSelectedYear = 2000;
break;
return Selected;
//--------------------------------------------------------------------
Mileage = g;
//--------------------------------------------------------------------
return Mileage;
//--------------------------------------------------------------------
strcpy(TankLevel, v);
//--------------------------------------------------------------------
return TankLevel;
//--------------------------------------------------------------------
strcpy(CarCondition, c);
//--------------------------------------------------------------------
return CarCondition;
//--------------------------------------------------------------------
void Invoice::ProcessOrder()
int NbrOfDays;;
CarExamination();
// This function works for both Borland C++ Builder and MSVC
system("cls");
CustomerInformation(Person);
CarSelected(Driving);
//--------------------------------------------------------------------
//--------------------------------------------------------------------
//--------------------------------------------------------------------
int &NumberOfDays)
// char WeekEndResponse;// Does the customer rent the car for the week-end?
WeekEnd = 0;// If renting for more than two days from Friday to
monday
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;
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;
WeekEnd = 50.95;
break;
return TotalRate;
//--------------------------------------------------------------------
void Invoice::CarExamination()
char Cond;
int GasLevel;
strcpy(CarCondition, "Excellent");
strcpy(CarCondition, "Good");
strcpy(CarCondition, "Driveable");
else
do {
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");
break;
//--------------------------------------------------------------------
#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.
class CRentDate
public:
CRentDate();
int getMonth();
int getDay();
int getYear();
virtual ~CRentDate();
private:
int Month;
int Day;
int Year;
};
//
//////////////////////////////////////////////////////////////////////
#include <iostream.h>
#include "RentDate.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CRentDate::CRentDate()
//---------------------------------------------------------------------
//---------------------------------------------------------------------
CRentDate::CRentDate(const CRentDate& d)
Month = d.Month;
Day = d.Day;
Year = d.Year;
//---------------------------------------------------------------------
CRentDate::~CRentDate()
//---------------------------------------------------------------------
Month = m;
Day = d;
Year = y;
//---------------------------------------------------------------------
int CRentDate::getMonth()
return Month;
//---------------------------------------------------------------------
int CRentDate::getDay()
return Day;
//---------------------------------------------------------------------
int CRentDate::getYear()
return Year;
//---------------------------------------------------------------------
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:
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:
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:
To use this function, you must let it know what instance of the FILE object you are closing.
Writing Data to a File
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:
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:
Here is an example of creating a file and letting the user supply data that would be saved to the file:
#include <iostream>
int main()
long Mileage;
fclose(CarInventory);
return 0;
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.
#include <iostream>
int main()
long Mileage;
/*
*/
fclose(CarInventory);
return 0;
//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
system("cls");
cout << "Full Name: " << FirstName << " " << LastName;
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
clrscr();
cout << "Full Name: " << FirstName << " " << LastName;
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>
int main()
system("cls");
cout << "Full Name: " << FirstName << " " << LastName << "\n\n";
return EXIT_SUCCESS;
A Console-Based
Multiple Choice Question
#include <algorithm>
#include <vector>
#include <functional>
#include <iostream>
#include <time.h>
void Verify(int);
int i, n;
IntVector QuestNbr(NbrOfQuestions);
QuestNbr[i] = i;
Start = QuestNbr.begin();
End = QuestNbr.end();
srand(time(0));
random_shuffle(Start, End);
do {
cin >> n;
system("cls");
system("cls");
AskQuestion(QuestNbr[i], Sum);
getchar();
system("cls");
return 0;
char Answer[10];
switch(q)
case 0:
if(Answer[0] == '3')
m += 1;
else
Verify(0);
break;
case 1:
if(Answer[0] == '4')
m += 1;
else
Verify(1);
break;
case 2:
if(Answer[0] == '4')
m += 1;
else
Verify(2);
break;
case 3:
if(Answer[0] == '4')
m += 1;
else
Verify(3);
break;
case 4:
cout << "\nWhat happened to Ananias and Sapphira after they lied "
<< "about the money\nthey collected from selling the land ?";
<< "\n3. They were abandoned by the other discples in the bush"
if(Answer[0] == '1')
m += 1;
else
Verify(4);
break;
case 5:
if(Answer[0] == '4')
m += 1;
else
Verify(5);
break;
case 6:
cout << "\nWhat was the craftiest of the wild animals "
if(Answer[0] == '2')
m += 1;
else
Verify(6);
break;
case 7:
cout << "\nTo which disciple did Jesus promise the key\n"
if(Answer[0] == '2')
m += 1;
else
Verify(7);
break;
case 8:
if(Answer[0] == '3')
m += 1;
else
Verify(8);
break;
case 9:
if(Answer[0] == '4')
m += 1;
else
Verify(9);
break;
case 10:
cout << "\nWho was the firstborn son of Adam and Eve?";
if(Answer[0] == '2')
m += 1;
else
Verify(10);
break;
case 11:
if(Answer[0] == '1')
m += 1;
else
Verify(11);
break;
case 12:
cout << "\nWhat did Micah from the hill country of Ephraim "
if(Answer[0] == '2')
m += 1;
else
Verify(12);
break;
case 13:
if(Answer[0] == '2')
m += 1;
else
Verify(13);
break;
case 14:
cout << "\nIn the parable of the weed, what does the field represent?";
if(Answer[0] == '2')
m += 1;
else
Verify(14);
break;
case 15:
cout << "\nHow many people (including Noah) got in the ark he built?";
if(Answer[0] == '2')
m += 1;
else
Verify(15);
break;
case 16:
if(Answer[0] == '3')
m += 1;
else
Verify(16);
break;
case 17:
cout << "\nIn how many pieces did the young Levite whose"
if(Answer[0] == '3')
m += 1;
else
Verify(17);
break;
case 18:
cout << "\n\"If anyone would come after me, he must deny\n"
if(Answer[0] == '3')
m += 1;
else
Verify(18);
break;
case 19:
if(Answer[0] == '1')
m += 1;
else
Verify(19);
break;
case 20:
cout << "\nWho said or wrote, \" You are the light of the world \"?";
if(Answer[0] == '3')
m += 1;
else
Verify(20);
break;
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?";
if(Answer[0] == '2')
m += 1;
else
Verify(20);
break;
getchar();
return Answer[q];
void Verify(int t)
switch(t)
case 0:
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";
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
cout << "\nPeter was promised the key to the kingdom of heaven";
break;
case 8:
cout << "\nIn 1Tm 1:2, Paul addresses Timothy as \"My true son\"";
break;
case 9:
break;
case 10:
break;
case 11:
break;
case 12:
break;
case 13:
break;
case 14:
break;
case 15:
cout << "\nNoah had 3 sons and each was married: 6 people";
break;
case 16:
break;
case 17:
break;
case 18:
break;
case 19:
break;
case 20:
case 21:
cout << "\nwhile Noah and his family were in the ark he built\n"
break;