C++ Basic
C++ Basic
This tutorial has been prepared for the beginners to help them understand the
basic to advanced concepts related to C++.
Prerequisites
Before you start practicing with various types of examples given in this
tutorial,we are making an assumption that you are already aware of the basicsof
computer program andcomputer programming language.
Copyright&Disclaimer
Copyright2014byTutorialsPoint(I)Pvt.Ltd.
All the content and graphics published in this e-book are the property
ofTutorialsPoint(I) Pvt.Ltd.Theuserofthise-bookisprohibitedtoreuse,retain, copy,
distribute or republish any contents or a part of contents of this e-book in any
manner without written consent of the publisher.
We strive to update the contents of our website and tutorials as timely and as
precisely as possible, however, the contents may contain inaccuracies or errors.
Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy,
timeliness or completeness of our website or its contents including this tutorial.If
you discover any errors on our website or in this tutorial, please notify us at
[email protected]
TableofContents
AbouttheTutorial................................................................................................................................... i
Audience............................................................................................................................................... i
Prerequisites......................................................................................................................................... i
i
Copyright&Disclaimer............................................................................................................................ i
TableofContents.................................................................................................................................... i
1. OVERVIEW.............................................................................................1
Object-OrientedProgramming............................................................................................................... 1
StandardLibraries................................................................................................................................. 1
TheANSIStandard................................................................................................................................. 1
LearningC++.......................................................................................................................................... 2
UseofC++.............................................................................................................................................. 2
2. ENVIORNMENTSETUP.............................................................................3
TryitOptionOnline................................................................................................................................. 3
LocalEnvironmentSetup........................................................................................................................ 3
InstallingGNUC/C++Compiler................................................................................................................ 4
3. BASICSYNTAX........................................................................................6
C++ProgramStructure........................................................................................................................... 6
Compile&ExecuteC++Program.............................................................................................................. 7
Semicolons&Blocksin C++..................................................................................................................... 7
C++Identifiers....................................................................................................................................... 8
C++Keywords........................................................................................................................................ 8
Trigraphs.............................................................................................................................................. 9
WhitespaceinC++................................................................................................................................ 10
4. COMMENTSIN C++
.............................................................................................................
11
5. DATATYPES..........................................................................................13
PrimitiveBuilt-inTypes......................................................................................................................... 13
ii
typedefDeclarations............................................................................................................................ 15
EnumeratedTypes............................................................................................................................... 16
6. VARIABLETYPES...................................................................................17
VariableDefinitioninC++...................................................................................................................... 17
VariableDeclarationinC++.................................................................................................................... 18
LvaluesandRvalues.............................................................................................................................. 20
7. VARIABLESCOPE..................................................................................21
LocalVariables..................................................................................................................................... 21
GlobalVariables.................................................................................................................................. 22
InitializingLocalandGlobalVariables..................................................................................................... 23
8. CONSTANTS/LITERALS.........................................................................24
IntegerLiterals..................................................................................................................................... 24
Floating-pointLiterals.......................................................................................................................... 24
BooleanLiterals................................................................................................................................... 25
CharacterLiterals................................................................................................................................. 25
StringLiterals....................................................................................................................................... 26
DefiningConstants............................................................................................................................... 27
9. MODIFIERTYPES...................................................................................29
TypeQualifiersinC++............................................................................................................................ 30
10. STORAGECLASSES...............................................................................31
TheautoStorageClass........................................................................................................................... 31
TheregisterStorageClass...................................................................................................................... 31
ThestaticStorageClass......................................................................................................................... 31
TheexternStorageClass........................................................................................................................ 33
ThemutableStorageClass..................................................................................................................... 34
iii
11. OPERATORS.........................................................................................35
ArithmeticOperators........................................................................................................................... 35
RelationalOperators............................................................................................................................ 37
LogicalOperators................................................................................................................................. 40
BitwiseOperators................................................................................................................................ 41
AssignmentOperators.......................................................................................................................... 44
MiscOperators.................................................................................................................................... 47
OperatorsPrecedenceinC++................................................................................................................. 48
12. LOOPTYPES..........................................................................................51
WhileLoop.......................................................................................................................................... 52
for Loop.............................................................................................................................................. 54
do…whileLoop...............................................................................................................................................56
nestedLoops....................................................................................................................................... 58
LoopControlStatements...................................................................................................................... 60
BreakStatement.................................................................................................................................. 61
continueStatement............................................................................................................................. 63
gotoStatement.................................................................................................................................... 65
TheInfiniteLoop.................................................................................................................................. 67
13. DECISION-MAKINGSTATEMENTS...........................................................69
IfStatement........................................................................................................................................ 70
if…elseStatement..........................................................................................................................................72
if...elseif...elseStatement.................................................................................................................... 73
SwitchStatement................................................................................................................................ 75
NestedifStatement.............................................................................................................................. 78
The?:Operator.................................................................................................................................... 81
14. FUNCTIONS..........................................................................................82
iv
DefiningaFunction............................................................................................................................... 82
FunctionDeclarations.......................................................................................................................... 83
CallingaFunction................................................................................................................................. 84
FunctionArguments............................................................................................................................ 85
CallbyValue......................................................................................................................................... 86
CallbyPointer...................................................................................................................................... 87
CallbyReference.................................................................................................................................. 89
DefaultValuesforParameters............................................................................................................... 90
15. NUMBERS.............................................................................................93
DefiningNumbersinC++....................................................................................................................... 93
MathOperationsin C++........................................................................................................................ 94
RandomNumbersinC++....................................................................................................................... 96
16. ARRAYS................................................................................................98
DeclaringArrays.................................................................................................................................. 98
InitializingArrays................................................................................................................................. 98
AccessingArrayElements..................................................................................................................... 99
PointertoanArray.............................................................................................................................. 103
PassingArraystoFunctions................................................................................................................. 105
ReturnArrayfromFunctions................................................................................................................ 107
17. STRINGS.............................................................................................111
TheC-StyleCharacterString................................................................................................................. 111
TheStringClassinC++.......................................................................................................................... 114
18. POINTERS...........................................................................................116
WhatarePointers?............................................................................................................................. 116
UsingPointersinC++........................................................................................................................... 117
v
Pointersin C++................................................................................................................................... 118
NullPointers...................................................................................................................................... 119
PointerArithmetic............................................................................................................................. 120
PointersvsArrays............................................................................................................................... 124
ArrayofPointers................................................................................................................................ 126
PointertoaPointer............................................................................................................................. 128
PassingPointerstoFunctions............................................................................................................... 130
ReturnPointerfromFunctions............................................................................................................. 132
19. REFERENCES......................................................................................135
ReferencesvsPointers........................................................................................................................ 135
CreatingReferencesinC++.................................................................................................................. 135
ReferencesasParameters................................................................................................................... 137
ReferenceasReturnValue................................................................................................................... 138
20. DATEANDTIME....................................................................................141
CurrentDateandTime........................................................................................................................ 142
FormatTimeusingstructtm................................................................................................................. 143
21. BASICINPUT/OUTPUT..........................................................................145
I/OLibraryHeaderFiles....................................................................................................................... 145
TheStandardOutputStream(cout)...................................................................................................... 145
TheStandardInputStream(cin)........................................................................................................... 146
TheStandardErrorStream(cerr).......................................................................................................... 147
TheStandardLogStream(clog)............................................................................................................ 148
22. DATASTRUCTURES
............................................................................................................
149
DefiningaStructure............................................................................................................................ 149
vi
AccessingStructureMembers............................................................................................................. 150
vii
StructuresasFunctionArguments........................................................................................................ 151
PointerstoStructures......................................................................................................................... 153
ThetypedefKeyword.......................................................................................................................... 155
23. CLASSESANDOBJECTS........................................................................157
DefineC++Objects.............................................................................................................................. 157
AccessingtheDataMembers............................................................................................................... 158
ClassAccessModifiers........................................................................................................................ 163
ThepublicMembers........................................................................................................................... 164
TheprivateMembers.......................................................................................................................... 165
TheprotectedMembers..................................................................................................................... 167
Constructor&Destructor.................................................................................................................... 169
ParameterizedConstructor................................................................................................................. 170
TheClassDestructor........................................................................................................................... 173
CopyConstructor............................................................................................................................... 174
FriendFunctions................................................................................................................................ 179
InlineFunctions................................................................................................................................. 181
thisPointer........................................................................................................................................ 182
PointertoC++Classes.......................................................................................................................... 184
StaticFunctionMembers.................................................................................................................... 187
24. INHERITANCE
............................................................................................................
190
Base&DerivedClasses........................................................................................................................ 190
viii
AccessControlandInheritance............................................................................................................ 192
ix
TypeofInheritance............................................................................................................................. 192
MultipleInheritance.......................................................................................................................... 193
25. OVERLOADING(OPERATOR&FUNCTION).............................................196
FunctionOverloadinginC++................................................................................................................ 196
OperatorsOverloadinginC++.............................................................................................................. 197
Overloadable/Non-overloadableOperators........................................................................................200
OperatorOverloadingExamples......................................................................................................... 201
UnaryOperatorsOverloading............................................................................................................. 201
Increment(++)andDecrement(--)Operators........................................................................................203
BinaryOperatorsOverloading............................................................................................................. 205
RelationalOperatorsOverloading....................................................................................................... 208
Input/OutputOperatorsOverloading................................................................................................... 210
++and--OperatorsOverloading........................................................................................................... 212
AssignmentOperatorsOverloading..................................................................................................... 214
FunctionCall()OperatorOverloading................................................................................................... 215
Subscripting[]OperatorOverloading................................................................................................... 217
ClassMemberAccessOperator->Overloading......................................................................................219
26. POLYMORPHISM.................................................................................223
VirtualFunction................................................................................................................................. 226
PureVirtualFunctions......................................................................................................................... 226
27. DATAABSTRACTION...........................................................................227
AccessLabelsEnforceAbstraction........................................................................................................ 228
BenefitsofDataAbstraction................................................................................................................ 228
DataAbstractionExample................................................................................................................... 228
DesigningStrategy............................................................................................................................. 230
28. DATAENCAPSULATION.......................................................................231
x
DataEncapsulationExample...................................................................................................................... 232
DesigningStrategy.................................................................................................................................... 233
29. INTERFACES.......................................................................................234
AbstractClassExample.............................................................................................................................. 234
DesigningStrategy.................................................................................................................................... 236
30. FILESANDSTREAMS............................................................................238
ClosingaFile............................................................................................................................................. 239
Read&WriteExample............................................................................................................................... 240
FilePositionPointers................................................................................................................................. 242
31................................................................................EXCEPTIONHANDLING
............................................................................................................243
ThrowingExceptions................................................................................................................................. 244
CatchingExceptions.................................................................................................................................. 244
C++StandardExceptions........................................................................................................................... 246
DefineNewExceptions.............................................................................................................................. 247
32. DYNAMICMEMORY..............................................................................249
ThenewanddeleteOperators.................................................................................................................... 249
DynamicMemoryAllocationforArrays....................................................................................................... 251
DynamicMemoryAllocationforObjects..................................................................................................... 251
33. NAMESPACES
............................................................................................................
253
xi
DefiningaNamespace............................................................................................................................... 253
Theusingdirective.................................................................................................................................... 254
xii
DiscontiguousNamespaces................................................................................................................. 256
NestedNamespaces........................................................................................................................... 256
34. TEMPLATES........................................................................................258
FunctionTemplate............................................................................................................................. 258
ClassTemplate................................................................................................................................... 259
35. PREPROCESSOR.................................................................................263
The#definePreprocessor.................................................................................................................... 263
Function-LikeMacros......................................................................................................................... 264
ConditionalCompilation..................................................................................................................... 264
The#and##Operators........................................................................................................................ 266
PredefinedC++Macros....................................................................................................................... 268
36. SIGNALHANDLING..............................................................................270
Thesignal()Function........................................................................................................................... 270
Theraise()Function............................................................................................................................ 272
37. MULTITHREADING..............................................................................274
CreatingThreads................................................................................................................................ 274
TerminatingThreads.......................................................................................................................... 275
PassingArgumentstoThreads............................................................................................................. 277
JoiningandDetachingThreads............................................................................................................. 278
38. WEBPROGRAMMING...........................................................................282
WebBrowsing................................................................................................................................... 282
CGIArchitectureDiagram................................................................................................................... 282
WebServerConfiguration................................................................................................................... 283
FirstCGIProgram................................................................................................................................ 284
xiii
MyFirstCGIprogram........................................................................................................................... 284
HTTPHeader...................................................................................................................................... 285
CGIEnvironmentVariables................................................................................................................. 285
C++CGILibrary................................................................................................................................... 289
GETandPOSTMethods....................................................................................................................... 289
PassingInformationUsingGETMethod................................................................................................ 289
SimpleURLExample:GetMethod........................................................................................................ 290
SimpleFORMExample:GETMethod.................................................................................................... 291
PassingInformationUsingPOSTMethod.............................................................................................. 292
PassingCheckboxDatatoCGIProgram.................................................................................................. 292
PassingRadioButtonDatatoCGIProgram.............................................................................................294
PassingTextAreaDatatoCGIProgram.................................................................................................. 296
PassingDropdownBoxDatatoCGIProgram..........................................................................................298
HowItWorks...................................................................................................................................... 299
SettingupCookies.............................................................................................................................. 300
RetrievingCookies.............................................................................................................................. 301
FileUploadExample........................................................................................................................... 303
39. STLTUTORIAL.....................................................................................306
40. STANDARDLIBRARY............................................................................309
TheStandardFunctionLibrary............................................................................................................. 309
TheObjectOrientedClassLibrary......................................................................................................... 309
xiv
C++
1. OVERVIEW
The ANSI standard has been stable for a while, and all the major C++ compiler
manufacturers support the ANSI standard.
LearningC++
ThemostimportantthingwhilelearningC++istofocusonconcepts.
The purpose of learning a programming language is to become a better
programmer; that is, to become more effective at designing and implementing
new systems and at maintaining old ones.
C++ supports a variety of programming styles. You can write in the style of
Fortran, C, Smalltalk, etc., in any language. Each style can achieve its aims
effectively while maintaining runtime and space efficiency.
UseofC++
C++ is used by hundreds of thousands of programmers in essentially every
application domain.
C++ is being highly used to write device drivers and other software that rely on
direct manipulation of hardware under real-time constraints.
C++ is widely used for teaching and research because it is clean enough for
successful teaching of basic concepts.
Anyone who has used either an Apple Macintosh or a PC running Windows has
indirectly used C++ because the primary user interfaces of these systems are
written in C++.
C++
2. ENVIORNMENTSETUP
TryitOptionOnline
You really do not need to set up your own environment to start learning C++
programming language. Reason is very simple, we have already set up C++
Programming environment online, so that you can compile and execute all the
available examples online at the same time when you are doing your theory
work. This gives you confidence in what you are reading and to check the result
with different options. Feel free to modify any example and execute it online.
Try the following example using our online compileroption available at
http://www.compileonline.com/
#include <iostream>
usingnamespacestd;
intmain()
{
cout<<"HelloWorld";
return 0;
}
For most of the examples given in this tutorial, you will findTry itoption in our
website code sections at the top right corner that will take you to the online
compiler. So just make use of it and enjoy your learning.
LocalEnvironmentSetup
If you are still willing to set up your environment for C++, you need to have the
following two softwares on your computer.
TextEditor:
Thiswillbeusedtotypeyourprogram.ExamplesoffeweditorsincludeWindows
Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
Name and version of text editor can vary on different operating systems. For
example, Notepad will be used on Windows and vim or vi can be used on
windows as well as Linux, or UNIX.
The files you create with your editor are called source files and for C++ they
typically are named with the extension .cpp, .cp, or .c.
AtexteditorshouldbeinplacetostartyourC++programming.
C++
C++Compiler:
This is an actual C++ compiler, which will be used to compile your source code
into final executable program.
MostC++compilersdon'tcarewhatextensionyougive toyour sourcecode,but if you
don't specify otherwise, many will use .cpp by default.
Most frequently used and free available compiler is GNU C/C++ compiler,
otherwise you can have compilers either from HP or Solaris if you have the
respective Operating Systems.
InstallingGNUC/C++Compiler:
UNIX/LinuxInstallation:
If you are usingLinux or UNIXthen check whether GCC is installed on your
system by entering the following command from the command line:
$g++-v
IfyouhaveinstalledGCC,thenitshouldprintamessagesuchasthe following:
If GCC is not installed, then you will have to install it yourself using the detailed
instructions available at http://gcc.gnu.org/install/ .
MacOSXInstallation:
If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode
developmentenvironmentfromApple'swebsiteandfollowthesimpleinstallation
instructions.
Xcodeiscurrentlyavailableatdeveloper.apple.com/technologies/tools/.
WindowsInstallation:
To install GCC at Windows you need to install MinGW. To install MinGW, go tothe
MinGW homepage,www.mingw.org, and follow the link to the MinGW download
page. Download the latest version of the MinGW installation program which
should be named MinGW-<version>.exe.
While installing MinGW, at a minimum, you must install gcc-core, gcc-g++,
binutils, and the MinGW runtime, but you may wish to install more.
C++
3. BASICSYNTAX
#include <iostream>
usingnamespacestd;
//main()iswhereprogramexecutionbegins.
intmain()
{
cout<<"HelloWorld";//printsHelloWorld
return 0;
}
Letuslookatthe variouspartsoftheaboveprogram:
6
C++
3. Open a command prompt and go to the directory where you saved thefile.
4. Type 'g++hello.cpp' andpress entertocompile yourcode.Ifthereare no
errors in your code the command prompt will take you to the next lineand
would generate a.out executable file.
5. Now,type'a.out'torunyourprogram.
6. Youwillbeabletosee'HelloWorld'printedonthewindow.
$g++hello.cpp
$ ./a.out
HelloWorld
Make sure that g++ is in your path and that you are running it in the directory
containing file hello.cpp.
You can compile C/C++ programs using makefile. For more details, you can check
our ‘Makefile Tutorial’.
Semicolons&BlocksinC++
In C++, the semicolon is a statement terminator. That is, each individual statement
must be ended with a semicolon. It indicates the end of one logical entity.
Forexample,followingarethreedifferentstatements:
x=y;
y=y+1;
7
C++
add(x, y);
{
cout<<"HelloWorld";//printsHelloWorld
return 0;
}
C++ does not recognizetheend of thelineas a terminator. For this reason,it does
not matter where you put a statement in a line. For example:
x=y;
y=y+1;
add(x, y);
isthesameas
x=y;y=y+1;add(x,y);
C++Identifiers
The following list shows the reserved words in C++. These reserved words may
not be used as constant or variable or any other identifier names.
8
C++
Trigraphs
A few characters have an alternative representation, called a trigraph sequence.
A trigraph is a three-character sequence that represents a single character and
the sequence always starts with two question marks.
Trigraphs are expanded anywhere they appear, including within string literals
and character literals, in comments, and in preprocessor directives.
Followingaremostfrequentlyusedtrigraphsequences:
Trigraph Replacement
9
C++
??= #
??/ \
??' ^
??( [
??) ]
??! |
??< {
??> }
??- ~
All the compilers do not support trigraphs and they are not advised to be used
because of their confusing nature.
WhitespaceinC++
A line containing only whitespace, possibly with a comment, is known as a blank
line, and C++ compiler totally ignores it.
Whitespace is the term used in C++ to describe blanks, tabs, newline characters
and comments. Whitespace separates one part of a statement from another and
enables the compiler to identify where one element in a statement, such as int,
ends and the next element begins. Statement 1:
intage;
Intheabovestatementtheremustbeatleastonewhitespacecharacter(usually a
space) between int and age for the compiler to be able to distinguish them.
Statement 2:
10
C++
4. COMMENTSINC++
Program comments are explanatory statements that you can include in the C++
code. These comments help anyone reading the source code. All programming
languages allow for some form of comments.
C++ supports single-line and multi-line comments. All characters availableinside
any comment are ignored by C++ compiler.
C++commentsstartwith/*andendwith */.Forexample:
/*Thisisacomment*/
/*C++commentscanalso
*spanmultiplelines
*/
Acommentcanalsostartwith//,extendingtotheendoftheline.Forexample:
#include <iostream>
usingnamespacestd;
main()
{
cout<<"HelloWorld";//printsHelloWorld
return0;
}
HelloWorld
/*CommentoutprintingofHelloWorld:
11
C++
cout<<"HelloWorld";//printsHelloWorld
*/
12
C++
5. DATATYPES
While writing program in any language, you need to use various variables to
store various information. Variables are nothing but reserved memory locations
to store values. This means that when you create a variable you reserve some
space in memory.
You may like to store information of various data types like character, wide
character, integer, floating point, double floating point, boolean etc. Based on
the data type of a variable, the operating system allocates memory and decides
what can be stored in the reserved memory.
PrimitiveBuilt-inTypes
C++ offers the programmer a rich assortment of built-in as well as user defined
data types. Following table lists down seven basic C++ data types:
Type Keyword
Boolean bool
Character char
Integer int
Floatingpoint float
Doublefloatingpoint double
Valueless void
Widecharacter wchar_t
Several of the basic types can be modified using one or more of these type
modifiers:
signed
unsigned
short
long
13
C++
The following table shows the variable type, how much memory it takes to store the
value in memory, and what is maximum and minimum value which can be stored
in such type of variables.
The size of variables might be different from those shown in the above table,
depending on the compiler and the computer you are using.
14
C++
#include <iostream>
usingnamespacestd;
intmain()
{
cout<<"Sizeofchar:"<<sizeof(char)<<endl; cout
<<"Size of int : "<< sizeof(int) << endl;
cout<<"Sizeofshortint:"<<sizeof(shortint)<<endl; cout
<<"Size of long int : "<< sizeof(long int) << endl;
cout <<"Size of float : "<< sizeof(float) << endl;
cout <<"Size of double : "<< sizeof(double) <<
endl;
cout<<"Sizeofwchar_t:"<<sizeof(wchar_t)<<endl;
return 0;
}
Thisexampleusesendl,whichinsertsanew-linecharacteraftereverylineand
<<operator is being usedtopassmultiple values outto the screen.We are also
usingsizeof()function to get size of various data types.
When the above code is compiled and executed, it produces the following result
which can vary from machine to machine:
Sizeofchar:1
Size of int : 4
Sizeofshortint:2
Size of long int :
4 Size of float : 4
Size of double : 8
Size of wchar_t : 4
typedefDeclarations
You can create a new name for an existing type usingtypedef. Following is the
simple syntax to define a new type using typedef:
typedeftypenewname;
Forexample,thefollowingtellsthecompilerthatfeetisanothernamefor int:
15
C++
typedefintfeet;
Now, the following declaration is perfectly legal and creates an integer variable
called distance:
feetdistance;
EnumeratedTypes
An enumerated type declares an optional type name and a set of zero or more
identifiers that can be used as values of the type. Each enumerator is a constant
whose type is the enumeration.
Creating an enumeration requires the use of the keywordenum. The general
form of an enumeration type is:
enumenum-name{listofnames}var-list;
Here,theenum-nameistheenumeration'stypename.Thelistofnamesis comma
separated.
For example, the following code defines an enumeration of colors called
colorsand the variable c of type color. Finally, c is assigned the value "blue".
enumcolor{red,green,blue}c; c =
blue;
By default, the value of the first name is 0, the second name has the value 1,
and the third has the value 2, and so on. But you can give a name, a specific
valuebyaddinganinitializer.Forexample,inthefollowing enumeration,green will
have the value 5.
enumcolor{red,green=5,blue};
16
C++
6. VARIABLETYPES
A variable provides us with named storage that our programs can manipulate.
Each variable in C++ has a specific type, which determines the size and layoutof
the variable's memory; the range of values that can be stored within that
memory; and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and
lowercase letters are distinct because C++ is case-sensitive:
TherearefollowingbasictypesofvariableinC++asexplainedinlast chapter:
Type Description
bool Storeseithervaluetrueorfalse.
float Asingle-precisionfloatingpointvalue.
double Adouble-precisionfloatingpointvalue.
void Representstheabsenceoftype.
wchar_t Awidecharactertype.
17
C++
typevariable_list;
Here,typemust be a valid C++ data type including char, w_char, int, float,
double, bool or any user-defined object, etc., andvariable_listmay consist of one
or more identifier names separated by commas. Some valid declarations are
shown here:
int i,j,k;
char c, ch;
floatf,salary;
double d;
typevariable_name=value;
Someexamplesare:
externintd=3,f=5; //declarationofdand f.
intd= 3,f=5; //definitionandinitializingdandf.
byte z = 22; charx='x'; //definitionandinitializesz.
//thevariablexhasthevalue'x'.
For definition without an initializer: variables with static storage duration are
implicitly initialized with NULL (all bytes have the value 0); the initial value of all
other variables is undefined.
VariableDeclarationinC++
A variable declaration is useful when you are using multiple files and you define
your variable in one of the files which will be available at the time of linking of
the program. You will useexternkeyword to declare a variable at any place.
Though you can declare a variable multiple times in your C++ program, but it
can be defined only once in a file, a function or a block of code.
Example:
C++
Try the following example where a variable has been declared at the top, but it
has been defined inside the main function:
#include <iostream>
usingnamespacestd;
//Variabledeclaration:
extern int a, b;
extern int c;
externfloatf;
intmain()
{
//Variabledefinition:
int a, b;
int c;
floatf;
//actualinitialization
a= 10;
b= 20;
c= a +b;
cout<<c<<endl;
f= 70.0/3.0;
cout<<f<<endl;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
30
23.3333
C++
//functiondeclaration
int func();
intmain()
{
//functioncall
int i = func();
}
//functiondefinition
int func()
{
return0;
}
LvaluesandRvalues
TherearetwokindsofexpressionsinC++:
Variables are lvalues and so may appear on the left-hand side of an assignment.
Numeric literals are rvalues and so may not be assigned and cannot appear on
the left-hand side. Following is a valid statement:
intg= 20;
Butthefollowingisnotavalidstatementandwouldgeneratecompile-time error:
10 =20;
C++
7. VARIABLESCOPE
A scope is a region of the program and broadly speaking there are three places,
where variables can be declared:
Insideafunctionorablockwhichiscalled localvariables,
Inthedefinitionoffunctionparameterswhichiscalledformalparameters.
Outsideofallfunctionswhichiscalledglobalvariables.
We willlearnwhatafunction is, and it'sparameterinsubsequentchapters.Here let us
explain what local and global variables are.
LocalVariables
Variables that are declared inside a function or block are local variables. They
can be used only by statements that are inside that function or block of code.
Local variables are not known to functions outside their own. Following is the
example using local variables:
#include <iostream>
usingnamespacestd;
intmain()
{
//Localvariabledeclaration:
int a, b;
intc;
//actualinitialization
a= 10;
b= 20;
c= a +b;
cout<<c;
return0;
}
21
C++
GlobalVariables
Global variables are defined outside of all the functions, usually on top of the
program. The global variables will hold their value throughout the life-time of
your program.
A global variable can be accessed by any function. That is, a global variable is
available for use throughout your entire program after its declaration. Following
is the example using global and local variables:
#include <iostream>
usingnamespacestd;
//Globalvariabledeclaration:
int g;
intmain()
{
//Localvariabledeclaration:
int a, b;
//actualinitialization
a= 10;
b= 20;
g= a +b;
cout<<g;
return0;
}
A program can have same name for local and global variables but value of local
variable inside a function will take preference. For example:
#include <iostream>
usingnamespacestd;
//Globalvariabledeclaration:
int g = 20;
22
C++
intmain()
{
//Localvariabledeclaration:
int g = 10;
cout<<g;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
10
InitializingLocalandGlobalVariables
When a local variable is defined, it is not initialized by the system, you must
initialize it yourself. Global variables are initialized automatically by the system
when you define them as follows:
DataType Initializer
int 0
char '\0'
float 0
double 0
pointer NULL
23
C++
8. CONSTANTS/LITERALS
Constants refer to fixed values that the program may not alter and they are
called literals.
Constants can be of any of the basic data types and can be divided into Integer
Numerals, Floating-Point Numerals, Characters, Strings and Boolean Values.
Again, constants are treated just like regular variables except that their values
cannot be modified after their definition.
IntegerLiterals
212 // Legal
215u // Legal
0xFeeL // Legal
078 // Illegal:8isnotanoctal digit
032UU // Illegal:cannotrepeatasuffix
FollowingareotherexamplesofvarioustypesofIntegerliterals:
85 // decimal
0213 // octal
0x4b // hexadecimal
30 // int
30u // unsignedint
30l // long
30ul // unsignedlong
Floating-pointLiterals
A floating-point literal has an integer part, a decimal point, a fractional part, and
an exponent part. You can represent floating point literals either in decimal form
or exponential form.
24
C++
While representing using decimal form, you must include the decimal point, the
exponent, or both and while representing using exponential form, you must
include the integer part, the fractional part, or both. The signed exponent is
introduced by e or E.
Herearesomeexamplesoffloating-pointliterals:
3.14159 //Legal
314159E-5L //Legal
510E //Illegal:incompleteexponent
210f //Illegal:nodecimalorexponent
.e55 //Illegal:missingintegerorfraction
BooleanLiterals
TherearetwoBooleanliteralsandtheyarepartofstandardC++keywords:
Avalueoftruerepresentingtrue.
Avalueoffalserepresentingfalse.
You should not consider the value of true equal to 1 and value of false equal to0.
CharacterLiterals
Character literals are enclosed in single quotes. If the literal begins with L
(uppercaseonly),itisawidecharacterliteral(e.g.,L'x')andshouldbestored
inwchar_ttype of variable. Otherwise, it is a narrow character literal (e.g., 'x')
and can be stored in a simple variable of chartype.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\
t'), or a universal character (e.g., '\u02C0').
There are certain characters in C++ when they are preceded by a backslashthey
will have special meaning and they are used to represent like newline (\n) or tab
(\t). Here, you have a list of some of such escape sequence codes:
Escapesequence Meaning
\\ \ character
\' 'character
\" "character
\? ?character
25
C++
\a Alertorbell
\b Backspace
\f Formfeed
\n Newline
\r Carriagereturn
\t Horizontaltab
\v Verticaltab
\ooo Octalnumberofonetothreedigits
\xhh.. . Hexadecimalnumberofoneormoredigits
Followingistheexampletoshowafewescapesequencecharacters:
#include <iostream>
usingnamespacestd;
intmain()
{
cout<<"Hello\tWorld\n\n";
return 0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Hello World
StringLiterals
String literals are enclosed in double quotes. A string contains characters that
are similar to character literals: plain characters, escape sequences, and
universal characters.
26
C++
"hello,dear"
"hello,\
dear"
"hello,""d""ear"
DefiningConstants
TherearetwosimplewaysinC++todefineconstants:
Using#definepreprocessor.
Usingconstkeyword.
The#definePreprocessor
Followingistheformtouse#definepreprocessortodefineaconstant:
#defineidentifiervalue
Followingexampleexplainsitindetail:
#include <iostream>
usingnamespacestd;
#defineLENGTH10
#define WIDTH5
#defineNEWLINE'\n'
intmain()
{
intarea;
area=LENGTH* WIDTH;
27
C++
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
50
TheconstKeyword
Youcanuseconstprefixtodeclareconstantswithaspecifictypeasfollows:
consttypevariable=value;
Followingexampleexplainsitindetail:
#include<iostream>
usingnamespacestd;
intmain()
{
constint constint
LENGTH=10;
WIDTH = 5;
constcharNEWLINE='\n';
intarea;
area=LENGTH* WIDTH;
cout << area; cout<<NEWLINE;
return0;
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
50
NotethatitisagoodprogrammingpracticetodefineconstantsinCAPITALS.
28
C++
9. MODIFIERTYPES
unsigned x;
unsignedinty;
Tounderstandthedifferencebetweenthewaysignedandunsignedinteger modifiers
are interpreted by C++, you should run the following short program:
#include <iostream>
usingnamespacestd;
/*Thisprogramshowsthedifferencebetween
*signedandunsignedintegers.
*/
intmain()
{
short int i; // a signed short integer
shortunsignedintj;//anunsignedshortinteger
29
C++
j= 50000;
i= j;
cout<<i<<""<<j;
return0;
}
Whenthisprogramis run,followingistheoutput:
-1553650000
Theaboveresultisbecausethebitpatternthatrepresents50,000asashort unsigned
integer is interpreted as -15,536 by a short.
TypeQualifiersinC++
Thetypequalifiersprovideadditionalinformationaboutthevariablesthey precede.
Qualifier Meaning
30
C++
10. STORAGECLASSES
A storage class defines the scope (visibility) and life-time of variables and/or
functions within a C++ Program. These specifiers precede the type that they
modify. There are following storage classes, which can be used in a C++
Program
auto
register
static
extern
mutable
TheautoStorageClass
Theautostorageclassisthedefaultstorageclassforalllocalvariables.
{
intmount;
autointmonth;
}
The example above defines two variables with the same storage class, auto can
only be used within functions, i.e., local variables.
TheregisterStorageClass
Theregisterstorage class is used to define local variables that should be stored
in a register instead of RAM. This means that the variable has a maximum size
equal to the register size (usually one word) and can't have the unary '&'
operator applied to it (as it does not have a memory location).
{
registerintmiles;
}
The register should only be used for variables that require quick access such as
counters. It should also be noted that defining 'register' does not mean that the
variable will be stored in a register. It means that it MIGHT be stored in a register
depending on hardware and implementation restrictions.
ThestaticStorageClass
31
C++
#include<iostream>
//Functiondeclaration
void func(void);
staticintcount=10;/*Globalvariable */
main()
{
while(count--)
{
func();
}
return0;
}
//Functiondefinition
void func( void )
{
staticinti=5;//localstaticvariable i++;
std::cout<<"iis"<<i;
std::cout<<"andcountis"<<count<< std::endl;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
iis6andcountis9
iis7andcountis8
32
C++
iis8andcountis7 iis9andcountis6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0
TheexternStorageClass
FirstFile:main.cpp
#include<iostream>
intcount;
externvoidwrite_extern();
main()
{
count = 5;
write_extern();
}
SecondFile:support.cpp
#include<iostream>
33
C++
externintcount;
voidwrite_extern(void)
{
std::cout<<"Countis"<<count<<std::endl;
}
$g++main.cppsupport.cpp-owrite
$./
write 5
ThemutableStorage Class
34
C++
11. OPERATORS
+ Addstwooperands A +Bwillgive 30
35
C++
-- Decrementoperator,decreases A--willgive9
integer value by one
Try the following example to understand all the arithmetic operators available in
C++.
Copy and paste the following C++ program in test.cpp file and compile and run
this program.
#include<iostream>
usingnamespacestd;
main()
{
inta=21; intb=10; int c ;
c=a+ b;
cout<< "Line 1 - Value of c is :"<<c<<endl;
c=a - b;
cout<< "Line 2 - Value of c is :"<<c<<endl;
c=a* b;
cout<< "Line 3 - Value of c is :"<<c<<endl;
c=a/ b;
cout<< "Line 4 - Value of c is :"<<c<<endl;
c=a% b;
cout<< "Line 5 - Value of c is :"<<c<<endl;
c=a++;
cout<<"Line6 -Valueofcis:"<<c<<endl; c = a--;
cout<<"Line7-Valueofcis:"<<c<<endl;
return0;
36
C++
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
RelationalOperators
TherearefollowingrelationaloperatorssupportedbyC++language
Assume variable A holds 10 and variable B holds 20, then:
37
C++
operandisgreaterthanorequal to
the value of right operand, if yes
then condition becomes true.
Try the following example to understand all the relational operators available in
C++.
Copy and paste the following C++ program in test.cpp file and compile and run
this program.
#include <iostream>
usingnamespacestd;
main()
{
inta=21;
intb=10;
int c ;
if(a==b)
{
cout<<"Line1-aisequaltob"<<endl;
}
else
{
cout<<"Line1 -aisnotequaltob"<<endl;
}
if(a<b)
{
cout<<"Line2 -aislessthanb"<<endl;
38
C++
}
else
{
cout<<"Line2 -aisnotlessthanb"<<endl;
}
if(a>b)
{
cout<<"Line3 -aisgreaterthanb"<<endl;
}
else
{
cout<<"Line3 -aisnotgreaterthanb"<<endl;
}
/*Let'schangethevaluesofaandb*/
a=5;
b=20;
if(a<=b)
{
cout<<"Line4-aiseitherlessthan\
orequaltob"<<endl;
}
if(b>=a)
{
cout<<"Line5 -biseithergreaterthan\
orequaltob"<<endl;
}
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
39
C++
Line5-biseithergreaterthanorequaltob
LogicalOperators
TherearefollowinglogicaloperatorssupportedbyC++language. Assume
variable A holds 1 and variable B holds 0, then:
Trythefollowingexampletounderstandallthelogicaloperatorsavailablein C++.
Copy and paste the following C++ program in test.cpp file and compile and run
this program.
#include <iostream>
usingnamespacestd;
main()
{
int a = 5;
intb=20;
int c ;
40
C++
if(a&&b)
{
cout<<"Line1-Conditionistrue"<<endl;
}
if(a||b)
{
cout<<"Line2-Conditionistrue"<<endl;
}
/*Let'schangethevaluesofaandb*/
a=0;
b=10;
if(a&&b)
{
cout<<"Line3-Conditionistrue"<<endl;
}
else
{
cout<<"Line4-Conditionisnottrue"<<endl;
}
if(!(a&&b))
{
cout<<"Line5 -Conditionistrue"<<endl;
}
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
BitwiseOperators
41
C++
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables
for &, |, and ^ are as follows:
p q p&q p|q p^ q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
AssumeifA=60;andB=13;nowinbinaryformattheywillbe as follows:
A=00111100
B=00001101
A&B=0000 1100
A|B=0011 1101
A^B=00110001
~A=11000011
TheBitwiseoperatorssupportedbyC++languagearelistedinthefollowing table.
Assume variable A holds 60 and variable B holds 13, then:
42
C++
Trythefollowingexampletounderstandallthebitwiseoperatorsavailablein C++.
Copy and paste the following C++ program in test.cpp file and compile and run
this program.
#include<iostream>
usingnamespacestd;
main()
{
unsignedinta=60; unsignedintb=13; int c = 0;
//60=00111100
//13=00001101
c=a&b; //12=00001100
cout<<"Line1-Valueofcis:"<<c<<endl;
c=a|b; //61=00111101
cout<<"Line2 -Valueofcis:"<<c<<endl;
c=a^b; //49=00110001
cout<<"Line3 -Valueofcis:"<<c<<endl;
43
C++
c=a>>2; //15=00001111
cout<<"Line6-Valueofcis:"<<c<<endl;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Line1-Valueofcis:12 Line
2 - Value of c is: 61
Line 3 - Value of c is:
49 Line4-Valueofcis:-61
Line5-Valueofcis:240 Line
6 - Value of c is: 15
AssignmentOperators
TherearefollowingassignmentoperatorssupportedbyC++language:
44
C++
Try the following example to understand all the assignment operators available
in C++.
45
C++
Copy and paste the following C++ program in test.cpp file and compile and run
this program.
#include
<iostream>
usingnamespacestd;
main()
{
inta =21;
intc ;
c = a;
cou <<"Line 1 - = Operator, Value of c =: " <<c<< endl ;
t
c+= a;
cou <<"Line 2 - += Operator, Value of c =: " <<c<< endl ;
t
c-= a;
cou <<"Line 3 --= Operator, Value of c =: " <<c<< endl ;
t
c*= a;
cou <<"Line 4 - *= Operator, Value of c =: " <<c<< endl ;
t
c/= a;
cou <<"Line 5 - /= Operator, Value of c =: " <<c<< endl ;
t
c= 200
;
c%=
a;
cou 6 - %= Operator, Value of c =: " <<c<< endl ;
<<"Line
t
c<<= 2;
46
C++
cout<<"Line7-<<=Operator,Valueofc=:"<<c<<endl;
c>>=2;
cout<<"Line8->>=Operator,Valueofc=:"<<c<<endl;
47
C++
c&=2;
cout<<"Line9 -&=Operator,Valueofc=:"<<c<<endl;
c^=2;
cout<<"Line10-^=Operator,Valueofc=:"<<c<<endl;
c|=2;
cout<<"Line11-|=Operator,Valueofc=:"<<c<<endl;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
MiscOperators
ThefollowingtablelistssomeotheroperatorsthatC++supports.
Operator Description
48
C++
.(dot)and->(arrow) Memberoperatorsareusedtoreferenceindividual
members of classes, structures, and unions.
* Pointeroperator*ispointertoavariable.For example
*var;willpointertoavariablevar.
OperatorsPrecedenceinC++
Operator precedence determines the grouping of terms in an expression. This
affects how an expression is evaluated. Certain operators have higher
precedence than others; for example, the multiplication operator has higher
precedence than the addition operator:
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has
higher precedence than +, so it first gets multiplied with 3*2 and then adds into
7.
Here, operators with the highest precedence appear at the top of the table,those
with the lowest appear at the bottom. Within an expression, higher precedence
operators will be evaluated first.
Multiplicative */ % Lefttoright
49
C++
Additive +- Lefttoright
Equality == != Lefttoright
BitwiseXOR ^ Lefttoright
BitwiseOR | Lefttoright
LogicalOR || Lefttoright
Conditional ?: Righttoleft
Comma , Lefttoright
Trythefollowingexampletounderstandoperator’sprecedenceconceptavailable in
C++. Copy and paste the following C++ program in test.cpp file and compile and
run this program.
Check the simple difference with and without parenthesis. This will produce
different results because (), /, * and + have different precedence. Higher
precedence operators will be evaluated first:
#include <iostream>
usingnamespacestd;
main()
{
inta=20;
50
C++
intb=10;
intc=15; int d = 5; int e;
e=(a+b)*c/d; //(30*15)/5
cout<<"Valueof(a+b)*c/dis:"<<e<<endl;
e=((a+b)*c)/d; //(30*15)/5
cout<<"Valueof((a+b)*c)/dis:"<<e<<endl;
e=(a+b)*(c/d);//(30)*(15/5)
cout<<"Valueof(a+b)*(c/d)is:"<<e<<endl;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Value of (a + b) * c / d is :90
Valueof((a+b)*c)/dis:90
Valueof(a+b)*(c/d)is:90 Value
of a + (b * c) / d is:50
51
12.LOOPTYPES C++
There may be a situation, when you need to execute a block of code several
number of times. In general, statements are executed sequentially: The first
statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements
multiple times and following is the general from of a loop statement in most of
the programming languages:
LoopType Description
52
C++
WhileLoop
Awhileloopstatementrepeatedlyexecutesatargetstatementaslongasa given
condition is true.
Syntax
Thesyntaxofawhile loopinC++is:
while(condition)
{
statement(s);
}
Here,statement(s)maybeasinglestatementorablockofstatements.
Theconditionmay be any expression, and true is any non-zero value. The loop
iterates while the condition is true.
When the condition becomes false, program control passes to the line
immediately following the loop.
Flow Diagram
C++
Here, key point of thewhileloop is that the loop might not ever run. When the
condition is tested and the result is false, the loop body will be skipped and the
first statement after the while loop will be executed.
Example
#include <iostream>
usingnamespacestd;
intmain()
{
//Localvariabledeclaration:
int a = 10;
//whileloopexecution
while( a < 20 )
{
cout<<"valueofa:"<<a<<endl; a++;
}
C++
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
valueofa:10
valueofa:11
valueofa:12
valueofa:13
valueofa:14
valueofa:15
valueofa:16
valueofa:17
valueofa:18
valueofa:19
forLoop
Syntax
ThesyntaxofaforloopinC++is:
for(init;condition;increment)
{
statement(s);
}
Hereistheflowofcontrolinafor loop:
1. Theinitstep is executed first, and only once. This step allows you to
declare and initialize any loop control variables. You are not required to
put a statement here, as long as a semicolon appears.
2. Next, theconditionis evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and flow of
control jumps to the next statement just after the for loop.
3. After the body of the for loop executes, the flow of control jumps back up
totheincrementstatement.Thisstatementallowsyoutoupdateany
C++
loopcontrolvariables.Thisstatementcanbeleftblank,aslongasa semicolon
appears after the condition.
4. The condition is now evaluated again. If it is true, the loop executes and
the process repeats itself (body of loop, then increment step, and then
again condition). After the condition becomes false, the for loop
terminates.
Flow Diagram
Example
#include <iostream>
usingnamespacestd;
intmain()
{
//forloopexecution
for(inta=10;a<20;a=a+1 )
C++
{
cout<<"valueofa:"<<a<<endl;
}
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
valueofa:10
valueofa:11
valueofa:12
valueofa:13
valueofa:14
valueofa:15
valueofa:16
valueofa:17
valueofa:18
valueofa:19
do…whileLoop
Unlikeforandwhileloops, which test the loop condition at the top of the loop, the
do...whileloop checks its condition at the bottom of the loop.
Ado...whileloopissimilartoawhileloop,exceptthatado...whileloopis guaranteed to
execute at least one time.
Syntax
Thesyntaxofado...whileloopinC++is:
do
{
statement(s);
}while(condition);
Noticethattheconditionalexpressionappearsattheendoftheloop,sothe statement(s)
in the loop execute once before the condition is tested.
C++
If the condition is true, the flow of control jumps back up to do, and the
statement(s) in the loop execute again. This process repeats until the given
condition becomes false.
Flow Diagram
Example
#include <iostream>
usingnamespacestd;
intmain()
{
//Localvariabledeclaration:
int a = 10;
//doloopexecution
do
{
cout<<"valueofa:"<<a<<endl; a = a
+ 1;
}while(a<20);
return0;
C++
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
valueofa:10
valueofa:11
valueofa:12
valueofa:13
valueofa:14
valueofa:15
valueofa:16
valueofa:17
valueofa:18
valueofa:19
nestedLoops
Aloopcanbenestedinsideofanotherloop.C++allowsatleast256levelsof nesting.
Syntax
ThesyntaxforanestedforloopstatementinC++isasfollows:
for(init;condition;increment)
{
for(init;condition;increment)
{
statement(s);
}
statement(s);//youcanputmorestatements.
}
ThesyntaxforanestedwhileloopstatementinC++isasfollows:
while(condition)
{
while(condition)
{
statement(s);
C++
}
statement(s);//youcanputmorestatements.
}
do
{
statement(s);//youcanputmorestatements. do
{
statement(s);
}while(condition);
}while(condition);
Example
The following program uses a nested for loop to find the prime numbers from 2
to 100:
#include <iostream>
usingnamespacestd;
intmain()
{
inti,j;
Thiswouldproducethefollowingresult:
C++
2 is prime
3 is prime
5 is prime
7 is prime
1 is prime
1
1 is prime
3
1 is prime
7
1 is prime
9
2 is prime
3
2 is prime
9
3 is prime
1
3 is prime
7
4 is prime
1
4 is prime
3
4 is prime
7
5 is prime
3
5 is prime
9
6 is prime
1
6 is prime
7
7 is prime
1
7 is prime
3
7 is prime
9
8 is prime
3
8 is prime
9
9 is prime
7
C++
LoopControlStatements
Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope
are destroyed.
C++supportsthefollowingcontrolstatements.
ControlStatement Description
followingthelooporswitch.
continuestatement Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
BreakStatement
ThebreakstatementhasthefollowingtwousagesinC++:
Syntax
ThesyntaxofabreakstatementinC++is:
break;
Flow Diagram
C++
Example
#include <iostream>
usingnamespacestd;
intmain()
{
//Localvariabledeclaration:
int a = 10;
//doloopexecution
do
{
cout<<"valueofa:"<<a<<endl; a = a
+ 1;
if(a >15)
{
//terminatetheloop
break;
}
}while(a<20);
C++
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
valueofa:prettyprintnotranslate10
value of a: 11
valueofa:12
valueofa:13
valueofa:14
valueofa:15
continueStatement
Syntax
ThesyntaxofacontinuestatementinC++is:
continue;
Flow Diagram
C++
Example
#include <iostream>
usingnamespacestd;
intmain()
{
//Localvariabledeclaration:
int a = 10;
//doloopexecution
do
{
if(a==15)
{
//skiptheiteration.
a = a + 1;
continue;
}
cout<<"valueofa:"<<a<<endl; a = a
+ 1;
}while(a<20);
C++
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
valueofa:10
valueofa:11
valueofa:12
valueofa:13
valueofa:14
valueofa:16
valueofa:17
valueofa:18
valueofa:19
goto Statement
Agotostatement provides an unconditional jump from the goto to a labeled
statement in the same function.
NOTE:Use ofgotostatement is highly discouraged because it makes difficult to
trace the controlflow ofaprogram,making the programhardto understandand hard
to modify. Any program that uses a goto can be rewritten so that it doesn't need
the goto.
Syntax
ThesyntaxofagotostatementinC++is:
gotolabel;
..
.
label:statement;
Flow Diagram
C++
Example
#include <iostream>
usingnamespacestd;
intmain()
{
//Localvariabledeclaration:
int a = 10;
//doloopexecution
LOOP:do
{
if(a==15)
{
//skiptheiteration.
a = a + 1;
gotoLOOP;
}
cout<<"valueofa:"<<a<<endl; a = a
+ 1;
}while(a<20);
C++
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
valueofa:10
valueofa:11
valueofa:12
valueofa:13
valueofa:14
valueofa:16
valueofa:17
valueofa:18
valueofa:19
for(...){
for(...) {
while(...){
if(...)goto stop;
.
.
.
}
}
}
stop:
cout<<"Errorin program.\n";
TheInfiniteLoop
the‘for’looparerequired,youcanmakeanendlessloopbyleavingthe conditional
expression empty.
#include <iostream>
usingnamespacestd;
intmain()
{
for(;;)
{
printf("Thisloopwillrunforever.\n");
}
return0;
}
13.DECISION-
MAKINGSTATEMENTS
Decision making structures require that the programmer specify one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and
optionally, other statements to be executed if the condition is determined to be
false.
Following is the general from of a typical decision making structure found inmost
of the programming languages:
Statement Description
71
switchstatement A‘switch’statementallowsavariabletobetested
72
C++
forequalityagainstalistofvalues.
IfStatement
Anifstatementconsistsofabooleanexpressionfollowedbyoneormore statements.
Syntax
ThesyntaxofanifstatementinC++is:
if(boolean_expression)
{
//statement(s)willexecuteifthebooleanexpressionistrue
}
If the boolean expression evaluates totrue, then the block of code inside the if
statement will be executed. If boolean expression evaluates tofalse, then the
first set of code after the end of the if statement (after the closing curly brace)
will be executed.
Flow Diagram
73
C++
Example
#include <iostream>
usingnamespacestd;
intmain()
{
//localvariabledeclaration:
inta=10;
//checkthebooleancondition
if( a < 20 )
{
//ifconditionistruethenprintthefollowing
cout <<"a is less than 20;"<< endl;
}
cout<<"valueofais:"<<a<<endl;
return0;
}
74
C++
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
aislessthan20;
valueofa is:10
if…elseStatement
Anifstatementcanbefollowedbyanoptionalelsestatement,whichexecutes when
the boolean expression is false.
Syntax
Thesyntaxofanif...elsestatementinC++is:
if(boolean_expression)
{
//statement(s)willexecuteifthebooleanexpressionistrue
}
else
{
//statement(s)willexecuteifthebooleanexpressionisfalse
}
Ifthebooleanexpressionevaluatestotrue,thentheifblockofcodewillbe executed,
otherwiseelse blockof code will be executed.
Flow Diagram
75
C++
Example
#include <iostream>
usingnamespacestd;
intmain()
{
//localvariabledeclaration:
inta=100;
//checkthebooleancondition
if( a < 20 )
{
//ifconditionistruethenprintthefollowing
cout <<"a is less than 20;"<< endl;
}
else
{
//ifconditionisfalsethenprintthefollowing cout
<<"a is not less than 20;"<< endl;
}
cout<<"valueofais:"<<a<<endl;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
aisnotlessthan20;
value of a is : 100
if...elseif...elseStatement
76
C++
Anifcanhavezerotomanyelseif'sandtheymustcomebeforetheelse.
Onceanelseifsucceeds,noneofheremainingelseif'sorelse'swillbe tested.
Syntax
Thesyntaxofanif...elseif...elsestatementinC++is:
if(boolean_expression1)
{
//Executeswhenthebooleanexpression1istrue
}
elseif(boolean_expression2)
{
//Executeswhenthebooleanexpression2is true
}
elseif(boolean_expression3)
{
//Executeswhenthebooleanexpression3istrue
}
else
{
//executeswhenthenoneoftheaboveconditionistrue.
}
Example
#include <iostream>
usingnamespacestd;
intmain()
{
//localvariabledeclaration:
int a = 100;
//checkthebooleancondition
if( a == 10 )
77
C++
{
//ifconditionistruethenprintthefollowing
cout <<"Value of a is 10"<< endl;
}
elseif(a==20)
{
// if else if condition is true
cout<<"Valueofais20"<<endl;
}
elseif(a==30)
{
// if else if condition is true
cout<<"Valueofais30"<<endl;
}
else
{
//ifnoneoftheconditionsistrue
cout<<"Valueofaisnotmatching"<< endl;
}
cout<<"Exactvalueofais:"<<a<< endl;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Valueofaisnotmatching
Exact value of a is : 100
SwitchStatement
Syntax
ThesyntaxforaswitchstatementinC++isasfollows:
78
C++
switch(expression){
caseconstant-expression statement(s);
:
break; //optional caseconstant-expression
statement(s);
break;//optional
//youcanhaveanynumberofcasestatements.
default://Optional statement(s);
Thefollowingrulesapplytoaswitchstatement:
Flow Diagram
79
C++
Example
#include <iostream>
usingnamespacestd;
intmain()
{
//localvariabledeclaration:
char grade = 'D';
switch(grade)
{
case'A':
cout<<"Excellent!"<<endl;
break;
case'B':
case'C':
cout<<"Welldone"<<endl;
break;
80
C++
case'D':
cout<<"Youpassed"<<endl;
break;
case'F':
cout<<"Bettertryagain"<<endl;
break;
default:
cout<<"Invalidgrade"<<endl;
}
cout<<"Yourgradeis"<<grade<<endl;
return0;
}
Thiswouldproducethefollowingresult:
YoupassedYour
gradeisD
NestedifStatement
It is always legal tonestif-else statements, which means you can use one if or
else if statement inside another if or else if statement(s).
Syntax
Thesyntaxforanestedifstatementisasfollows:
if(boolean_expression1)
{
//Executeswhenthebooleanexpression1istrue
if(boolean_expression 2)
{
//Executeswhenthebooleanexpression2istrue
}
}
Youcannestelseif...elseinthesimilarwayasyouhavenestedifstatement.
81
C++
Example
#include <iostream>
usingnamespacestd;
intmain()
{
//localvariabledeclaration:
inta=100;
intb=200;
//checkthebooleancondition
if( a == 100 )
{
//ifconditionistruethencheckthefollowing
if( b == 200 )
{
// if condition is true then print the
following
cout<<"Valueofais100andbis200"<<endl;
}
}
cout<<"Exactvalueofais :"<<a<<endl;
cout<<"Exactvalueofbis:"<<b<< endl;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Valueofais100andbis200
Exact value of a is : 100
Exact value of b is : 200
NestedswitchStatements
It is possible to have a switch as part of the statement sequence of an outer
switch. Even if the case constants of the inner and outer switch contain common
values, no conflicts will arise.
82
C++
C++specifiesthatatleast256levelsofnestingbeallowedforswitchstatements.
Syntax
Thesyntaxforanestedswitchstatementisasfollows:
switch(ch1)
{ case
'A':
cout<<"ThisAispartofouterswitch";
switch(ch2) {
case'A':
cout<<"ThisAispartofinnerswitch";
break;
case'B'://...
}
break;
case'B'://...
}
Example
#include <iostream>
usingnamespacestd;
intmain()
{
//localvariabledeclaration:
inta=100;
intb=200;
switch(a)
{ case100
:
cout<<"Thisispartofouterswitch"<<endl; switch(b) {
case200:
cout<<"Thisispartofinnerswitch"<<endl;
83
C++
}
}
cout<<"Exactvalueofais:"<<a<<endl;
cout<<"Exactvalueofbis:"<<b<< endl;
return0;
}
Thiswouldproducethefollowingresult:
Thisispartofouterswitch
Thisispartofinnerswitch
Exact value of a is : 100
Exact value of b is : 200
The?: Operator
Wehavecoveredconditionaloperator“?:”inpreviouschapterwhichcanbe used to
replace if...elsestatements. It has the following general form:
Exp1?Exp2:Exp3;
Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the
colon.
The value of a ‘?’ expression is determined like this: Exp1 is evaluated. If it is
true, then Exp2 is evaluated and becomes the value of the entire ‘?’ expression.
If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the
expression.
84
C++
14. FUNCTIONS
return_typefunction_name(parameterlist)
{
bodyofthefunction
}
85
C++
FunctionBody:Thefunctionbodycontainsacollectionofstatements that
define what the function does.
Example:
Following is the source code for a function calledmax(). This function takes two
parameters num1 and num2 and returns the maximum between the two:
//functionreturningthemaxbetweentwonumbers
intmax(intnum1,intnum2)
{
//localvariabledeclaration
int result;
returnresult;
}
FunctionDeclarations
A functiondeclarationtells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
Afunctiondeclarationhasthefollowingparts:
return_typefunction_name(parameterlist);
Fortheabovedefinedfunctionmax(),followingisthefunctiondeclaration:
intmax(intnum1,intnum2);
Parameternamesarenotimportantinfunctiondeclarationonlytheirtypeis required, so
following is also valid declaration:
intmax(int,int);
Function declaration is required when you define a function in one source fileand
you call that function in another file. In such case, you should declare the
function at the top of the file calling the function.
86
C++
CallingaFunction
While creating a C++ function, you give a definition of what the function has to
do. To use a function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called
function. A called function performs defined task and when it’s return statement
is executed or when its function-ending closing brace is reached, it returns
program control back to the main program.
To call a function, you simply need to pass the required parameters along with
function name, and if function returns a value, then you can store returned
value. For example:
#include <iostream>
usingnamespacestd;
//functiondeclaration
intmax(intnum1,intnum2);
intmain()
{
//localvariabledeclaration:
inta=100;
intb=200;
int ret;
//callingafunctiontogetmaxvalue.
ret = max(a, b);
cout<<"Maxvalueis:"<<ret<<endl;
return0;
}
//functionreturningthemaxbetweentwonumbers
int max(int num1, int num2)
{
//localvariabledeclaration
87
C++
intresult;
returnresult;
}
I kept max() function along with main() function and compiled the source code.
While running final executable, it would produce the following result:
Maxvalueis:200
FunctionArguments
CallType Description
88
C++
inthecall.Thismeansthatchangesmadetotheparameter
affect the argument.
CallbyValue
Thecall by value method of passing arguments to a function copies the actual
value of an argument into the formal parameter of the function. In this case,
changes made to the parameter inside the function have no effect on the
argument.
By default, C++ uses call by value to pass arguments. In general, this means
that code within a function cannot alter the arguments used to call the function.
Consider the function swap() definition as follows.
//functiondefinitiontoswapthevalues.
voidswap(intx,inty)
{
inttemp;
temp=x;/*savethevalueofx*/
x=y; /*putyintox*/
y=temp;/*putxintoy*/
return;
}
Now, let us call the functionswap() by passing actual values as in the following
example:
#include <iostream>
usingnamespacestd;
// function declaration
voidswap(intx,inty);
intmain()
{
//localvariabledeclaration:
int a = 100;
89
C++
intb=200;
cout<<"Beforeswap,valueofa:"<<a<<endl;
cout<<"Beforeswap,valueofb:"<<b<<endl;
//callingafunctiontoswapthevalues. swap(a,
b);
cout<<"Afterswap,valueofa:"<<a<<endl;
cout<<"Afterswap,valueofb:"<<b<<endl;
return0;
}
Beforeswap,valueofa:100
Beforeswap,valueofb:200
After swap, value of a :100
After swap, value of b :200
Which shows that there is no change in the values though they had been
changed inside the function.
CallbyPointer
//functiondefinitiontoswapthevalues.
void swap(int *x, int *y)
{
inttemp;
90
C++
temp=*x;/*savethevalueataddressx */
*x=*y;/*putyintox*/
*y=temp;/*putxintoy*/
return;
}
#include <iostream>
usingnamespacestd;
// function declaration
voidswap(int*x,int*y);
intmain()
{
//localvariabledeclaration:
inta=100;
intb=200;
cout<<"Beforeswap,valueofa:"<<a<<endl;
cout<<"Beforeswap,valueofb:"<<b<< endl;
/*callingafunctiontoswapthevalues.
* &aindicatespointertoaie.addressofvariablea and
* &bindicatespointertobie.addressofvariable b.
*/
swap(&a,&b);
cout<<"Afterswap,valueofa:"<<a<<endl;
cout<<"Afterswap,valueofb:"<<b<< endl;
91
C++
return0;
}
Beforeswap,valueofa:100
Beforeswap,valueofb:200
After swap, value of a :200
After swap, value of b :100
CallbyReference
//functiondefinitiontoswapthevalues.
voidswap(int&x,int&y)
{
inttemp;
temp=x;/*savethevalueataddressx*/
x=y; /*putyintox*/
y=temp;/*putxintoy*/
return;
}
#include <iostream>
usingnamespacestd;
// function declaration
voidswap(int&x,int&y);
92
C++
intmain()
{
//localvariabledeclaration:
inta=100;
intb=200;
cout<<"Beforeswap,valueofa:"<<a<<endl;
cout<<"Beforeswap,valueofb:"<<b<<endl;
/*callingafunctiontoswapthevaluesusingvariablereference.*/
swap(a, b);
cout<<"Afterswap,valueofa:"<<a<<endl;
cout<<"Afterswap,valueofb:"<<b<<endl;
return0;
}
Beforeswap,valueofa:100
Beforeswap,valueofb:200
After swap, value of a :200
After swap, value of b :100
93
C++
This is done by using the assignment operator and assigning values for the
arguments in the function definition. If a value for that parameter is not passed
when the function is called, the default given value is used, but if a value is
specified, this default value is ignored and the passed value is used instead.
Consider the following example:
#include <iostream>
usingnamespacestd;
intsum(inta,intb=20)
{
int result;
result=a+b;
return(result);
}
intmain()
{
//localvariabledeclaration:
inta=100;
intb=200;
int
result;
//callingafunctiontoaddthevalues.
result = sum(a, b);
cout<<"Totalvalueis:"<<result<< endl;
//callingafunctionagainasfollows.
result = sum(a);
cout<<"Totalvalueis:"<<result<< endl;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
94
C++
Totalvalueis:300
Totalvalueis:120
95
C++
15. NUMBERS
Normally, when we work with Numbers, we use primitive data types such as int,
short, long, float and double, etc. The number data types, their possible values
and number ranges have been explained while discussing C++ Data Types.
DefiningNumbersinC++
You have already defined numbers in various examples given in previous
chapters. Here is another consolidated example to define various types of
numbers in C++:
#include <iostream>
usingnamespacestd;
intmain()
{
//numberdefinition:
shorts;
inti;
longl;
floatf;
doubled;
//numberassignments;
s = 10;
i= 1000;
l= 1000000;
f= 230.47;
d= 30949.374;
//numberprinting;
cout<<"shorts:"<<s<<endl;
cout<<"inti:"<<i<<endl;
cout<<"longl:"<<l<<endl;
cout<<"floatf:"<<f<<endl;
96
C++
cout<<"doubled:"<<d<< endl;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
shorts:10
int i:1000
long l :1000000
floatf:230.47
doubled:30949.4
MathOperationsinC++
In addition to the various functions you can create, C++ also includes some
useful functions you can use. These functions are available in standard C and C+
+ libraries and calledbuilt-infunctions. These are functions that can be included
in your program and then use.
C++ has a rich set of mathematical operations, which can be performed on
various numbers. Following table lists down some useful built-in mathematical
functions available in C++.
Toutilizethesefunctionsyouneedtoincludethemathheaderfile<cmath>.
S.N. Function&Purpose
1 doublecos(double);
Thisfunctiontakesanangle(asadouble)andreturnsthecosine.
2 doublesin(double);
Thisfunctiontakesanangle(asadouble)andreturnsthesine.
3 doubletan(double);
Thisfunctiontakesanangle(asadouble)andreturnsthetangent.
4 doublelog(double);
Thisfunctiontakesanumberandreturnsthenaturallogofthat number.
97
C++
5 doublepow(double,double);
The first is a number you wish to raise and the second is the power you
wish to raise it t
6 doublehypot(double,double);
Ifyoupassthis functionthe lengthof twosides of arighttriangle, itwill return
you the length of the hypotenuse.
7 doublesqrt(double);
Youpassthisfunctionanumberanditgivesyouthesquare root.
8 intabs(int);
This function returns the absolute value of an integer that is passed toit.
9 doublefabs(double);
This function returns the absolute value of any decimal number passed
to it.
10 doublefloor(double);
Finds the integer which is less than or equal to the argument passed to
it.
Followingisasimpleexampletoshowfewofthemathematicaloperations:
#include
<iostream>
#include <cmath>
usingnamespacestd;
intmain()
{
//numberdefinition:
shorts = 10;
int i = -
1000; long
l=100000; 98
C++
doubled= 200.374;
//mathematicaloperations;
cout <<"sin(d) :"<< sin(d) << endl;
cout <<"abs(i):"<< abs(i) << endl;
cout<<"floor(d):"<<floor(d)<<endl;
cout <<"sqrt(f) :"<< sqrt(f) << endl;
cout<<"pow(d,2):"<<pow(d,2)<< endl;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
sign(d):-0.634939
abs(i):1000
floor(d):200
sqrt(f):15.1812
pow(d, 2) :40149.7
RandomNumbersinC++
There are many cases where you will wish to generate a random number. There
are actually two functions you will need to know about random number
generation. The first is rand(), this function will only return a pseudo random
number. The way to fix this is to first call the srand() function.
Following is a simple example to generate few random numbers. This example
makes use oftime()function to get the number of seconds on your system time,
to randomly seed the rand() function:
#include<iostream>
#include <ctime>
#include <cstdlib>
usingnamespacestd;
intmain()
{
inti,j;
99
C++
//settheseed
srand((unsigned)time(NULL) );
/*generate10randomnumbers.*/ for(
i = 0; i < 10; i++ )
{
//generateactualrandomnumber
j= rand();
cout<<"RandomNumber:"<<j<< endl;
}
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
RandomNumber:1748144778
Random Number: 630873888
Random Number: 213454064
6
Random Number: 219404170
Random Number: 902129458
Random Number: 920445370
Random Number: 131907266
1
Random Number: 257938873
Random Number: 125620110
1
Random Number: 580322989
10
0
C++
16. ARRAYS
To declare an array in C++, the programmer specifies the type of the elements
and the number of elements required by an array as follows:
typearrayName[arraySize];
doublebalance[10];
InitializingArrays
YoucaninitializeC++arrayelementseitheronebyoneorusingasingle statement as
follows:
doublebalance[5]={1000.0,2.0,3.4,17.0,50.0};
The number of values between braces { } cannot be larger than the number of
elements that we declare for the array between square brackets [ ]. Following is
an example to assign a single element of the array:
If you omit the size of the array, an array just big enough to hold the initialization
is created. Therefore, if you write:
doublebalance[]={1000.0,2.0,3.4,17.0,50.0};
Youwillcreateexactlythesamearrayasyoudid inthepreviousexample.
10
1
C++
balance[4]=50.0;
The above statement assigns element number 5th in the array a value of 50.0.
Array with 4th index will be 5th, i.e., last element because all arrays have 0 as
the index of their first element which is also called base index. Following is the
pictorial representation of the same array we discussed above:
AccessingArrayElements
An element is accessed by indexing the array name. This is done by placing the
index of the element within square brackets after the name of the array. For
example:
doublesalary=balance[9];
The above statement will take 10th element from the array and assign the value
to salary variable. Following is an example, which will use all the above-
mentioned three concepts viz. declaration, assignment and accessing arrays:
#include <iostream>
usingnamespacestd;
#include<iomanip>
using std::setw;
intmain()
{
intn[10];//nisanarrayof10 integers
//initializeelementsofarraynto0 for
( int i = 0; i < 10; i++ )
{
n[i]=i+100;//setelementatlocationitoi+100
}
cout<<"Element"<<setw(13)<<"Value"<< endl;
//outputeacharrayelement'svalue
102
C++
for(intj=0;j<10;j++)
{
cout<<setw(7)<<j<<setw( 13)<<n[j]<<endl;
}
return0;
}
Element Value
0 100
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109
ArraysinC++
Concept Description
Passingarraystofunctions Youcanpasstothefunctionapointertoan
103
C++
Returnarrayfromfunctions C++allowsafunctiontoreturnanarray.
Multi-dimensionalArrays
C++ allows multidimensional arrays. Here is the general form of a
multidimensional array declaration:
typename[size1][size2]...[sizeN];
Forexample,thefollowingdeclarationcreatesathreedimensional5.10.4 integer
array:
int threedim[5][10][4];
Two-DimensionalArrays
The simplest form of the multidimensional array is the two-dimensional array. A
two-dimensionalarrayis, inessence,alist ofone-dimensionalarrays.Todeclare a
two-dimensional integer array of size x,y, you would write something as follows:
typearrayName[x][y];
Thus,every elementinarrayaisidentifiedbyanelementnameoftheforma[i
][ j ], where a is the name of the array, and i and j are the subscripts that
uniquely identify each element in a.
InitializingTwo-DimensionalArrays
104
C++
Multidimensionedarraysmaybeinitializedbyspecifyingbracketedvaluesfor each
row. Following is an array with 3 rows and each row have 4 columns.
inta[3][4]={
{0,1,2,3},
/* initializersforrowindexedby0 */
{4,5,6,7},
/* initializersforrowindexedby1*/ initializersforrowindexedby
{8,9,10,11}
/*
};
The nested braces, which indicate the intended row, are optional. The following
initialization is equivalent to previous example:
inta[3][4]= {0,1,2,3,4,5,6,7,8,9,10,11};
AccessingTwo-DimensionalArrayElements
An element in 2-dimensional array is accessed by using the subscripts, i.e., row
index and column index of the array. For example:
intval=a[2][3];
#include <iostream>
usingnamespacestd;
intmain()
{
//anarraywith5rowsand2columns.
inta[5][2]={{0,0},{1,2},{2,4},{3,6},{4,8}};
//outputeacharrayelement'svalue
for ( int i = 0; i < 5; i++ )
for( int j=0; j< 2;j++ )
{
cout<<"a["<<i<<"]["<<j<<"]:";
cout<<a[i][j]<<endl;
}
105
C++
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
As explained above, you can have arrays with any number of dimensions,
although it is likely that most of the arrays you create will be of one or two
dimensions.
Pointertoan Array
It is most likely that you would not understand this chapter until you go through
the chapter related C++ Pointers.
So assuming you have bit understanding on pointers in C++, let us start: An
array name is a constant pointer to the first element of the array. Therefore, in
the declaration:
doublebalance[50];
double*p;
doublebalance[10];
p=balance;
Itislegaltousearraynamesasconstantpointers,andviceversa.Therefore,
*(balance+4)isalegitimatewayofaccessingthedataatbalance[4].
106
C++
Once you store the address of first element in p, you can access array elements
using *p, *(p+1), *(p+2) and so on. Below is the example to show all the
concepts discussed above:
#include <iostream>
usingnamespacestd;
intmain()
{
//anarraywith5 elements.
doublebalance[5]={1000.0,2.0,3.4,17.0,50.0};
double*p;
p=balance;
//outputeacharrayelement'svalue
cout<<"Arrayvaluesusingpointer"<<endl; for
( int i = 0; i < 5; i++ )
{
cout<<"*(p+"<<i<<"):"; cout <<
*(p + i) << endl;
}
cout<<"Arrayvaluesusingbalanceasaddress"<<endl; for (
int i = 0; i < 5; i++ )
{
cout<<"*(balance+"<<i<<"):"; cout <<
*(balance + i) << endl;
}
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Arrayvaluesusingpointer
*(p+0):1000
107
C++
*(p +1): 2
*(p +2): 3.4
*(p +3): 17
*(p +4): 50
Arrayvaluesusingbalanceasaddress
In the above example, p is a pointer to double which means it can store address
of a variable of double type. Once we have address in p, then *pwill give us
value available at the address stored in p, as we have shown in the above
example.
PassingArraystoFunctions
C++ does not allow to pass an entire array as an argument to a function.
However, You can pass a pointer to an array by specifying the array's name
without an index.
If you want to pass a single-dimension array as an argument in a function, you
would have to declare function formal parameter in one of following three ways
and all three declaration methods produce similar results because each tells the
compiler that an integer pointer is going to be received.
Way-1
Formalparametersasapointerasfollows:
voidmyFunction(int*param)
{
.
.
.
}
Way-2
Formalparametersasasizedarrayasfollows:
voidmyFunction(intparam[10])
108
C++
{
.
.
.
}
Way-3
Formalparametersasanunsizedarrayasfollows:
voidmyFunction(intparam[])
{
.
.
.
}
Now, consider the following function, which will take an array as an argument
along with another argument and based on the passed arguments, it will return
average of the numbers passed through the array as follows:
doublegetAverage(intarr[],intsize)
{
int i,sum=0;
doubleavg;
for(i=0;i<size;++i)
{
sum+= arr[i];
}
avg=double(sum)/ size;
returnavg;
}
Now,letuscalltheabovefunctionasfollows:
#include<iostream>
109
C++
usingnamespacestd;
//functiondeclaration:
doublegetAverage(intarr[],intsize);
intmain()
{
//anintarraywith5elements.
intbalance[5]={1000,2,3,17,50};
double avg;
//passpointertothearrayasanargument. avg =
getAverage( balance, 5 ) ;
//outputthereturnedvalue
cout<<"Averagevalueis:"<<avg<<endl;
return0;
}
Whentheabovecodeiscompiledtogetherandexecuted,itproducesthe following
result:
Averagevalueis:214.4
As you can see, the length of the array doesn't matter as far as the function is
concerned because C++ performs no bounds checking for the formalparameters.
ReturnArrayfromFunctions
int* myFunction()
{
.
110
C++
.
.
}
Second point to remember is that C++ does not advocate to return the address
of a local variable to outside of the function so you would have to define thelocal
variable as staticvariable.
Now, consider the following function, which will generate 10 random numbers
and return them using an array and call this function as follows:
#include<iostream>
#include <ctime>
usingnamespacestd;
//functiontogenerateandretrunrandomnumbers.
int * getRandom( )
{
staticintr[10];
//settheseed
srand((unsigned)time(NULL));
for (int i = 0; i < 10; ++i)
{
r[i]=rand();
cout<<r[i]<<endl;
}
returnr;
}
//mainfunctiontocallabovedefinedfunction.
int main ()
{
//apointertoanint. int
*p;
111
C++
p=getRandom();
for(inti =0;i< 10;i++)
{
cout<< "*(p+" <<i<<"):";
cout<< *(p+i) <<endl;
}
return0;
}
Whentheabovecodeiscompiledtogetherandexecuted,itproducesresult something
as follows:
624723190
1468735695
807113585
976495677
613357504
1377296355
1530315259
1778906708
1820354158
667126415
112
C++
113
C++
17. STRINGS
C++providesfollowingtwotypesofstringrepresentations:
TheC-stylecharacterstring.
ThestringclasstypeintroducedwithStandardC++. The
C-Style Character String
The C-style character string originated within the C language and continues tobe
supported within C++. This string is actually a one-dimensional array of
characters which is terminated by anullcharacter '\0'. Thus a null-terminated
string contains the characters that comprise the string followed by anull.
The following declaration and initialization create a string consisting of the word
"Hello". To hold the null character at the end of the array, the size of the
character array containing the string is one more than the number of characters
in the word "Hello."
chargreeting[6]={'H','e','l','l','o','\0'};
Ifyoufollowtheruleofarrayinitialization,thenyoucanwritetheabove statement as
follows:
chargreeting[]="Hello";
Followingisthememorypresentationofabovedefinedstringin C/C++:
Actually, you do not place the null character at the end of a string constant. The
C++ compiler automatically places the '\0' at the end of the string when it
initializes the array. Let us try to print above-mentioned string:
#include<iostream>
usingnamespacestd;
114
C++
intmain()
{
chargreeting[6]={'H','e','l','l','o','\0'};
cout<<"Greetingmessage:";
cout << greeting << endl;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Greetingmessage:Hello
C++supportsawiderangeoffunctionsthatmanipulatenull-terminatedstrings:
S.N. Function&Purpose
1 strcpy(s1,s2);
Copiesstrings2intostrings1.
2 strcat(s1,s2);
Concatenatesstrings2ontotheendofstrings1.
3 strlen(s1);
Returnsthelengthofstrings1.
4 strcmp(s1,s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0
if s1>s2.
5 strchr(s1,ch);
Returnsapointertothefirstoccurrenceofcharacterchinstrings1.
6 strstr(s1,s2);
115
C++
Returnsapointertothefirstoccurrenceofstrings2instrings1.
Followingexamplemakesuseoffewoftheabove-mentionedfunctions:
#include<iostream>
#include <cstring>
usingnamespacestd;
intmain()
{
charstr1[10]="Hello";
charstr2[10]="World";
char str3[10];
intlen;
//copystr1intostr3
strcpy( str3, str1);
cout<<"strcpy(str3,str1):"<<str3<<endl;
//concatenatesstr1andstr2
strcat( str1, str2);
cout<<"strcat(str1,str2):"<<str1<<endl;
//totallenghthofstr1afterconcatenation len
= strlen(str1);
cout<<"strlen(str1):"<<len<<endl;
return0;
}
When the above code is compiled and executed, it produces result something as
follows:
strcpy(str3,str1):Hello
116
C++
strcat(str1,str2):HelloWorld
strlen(str1) : 10
TheStringClassinC++
The standard C++ library provides astringclass type that supports all the
operations mentioned above, additionally much more functionality. Let us check
the following example:
#include<iostream>
#include <string>
usingnamespacestd;
intmain()
{
stringstr1="Hello";
stringstr2="World";
string str3;
intlen;
//copystr1intostr3
str3 = str1;
cout<<"str3:"<<str3<<endl;
//concatenatesstr1andstr2
str3 = str1 + str2;
cout<<"str1+str2:"<<str3<<endl;
//totallengthofstr3afterconcatenation
len = str3.size();
cout<<"str3.size():"<<len<<endl;
return0;
}
When the above code is compiled and executed, it produces result something as
follows:
117
C++
str3:Hello
str1+str2:HelloWorld
str3.size() :10
118
C++
18. POINTERS
C++ pointers are easy and fun to learn. Some C++ tasks are performed more
easily with pointers, and other C++ tasks, such as dynamic memory allocation,
cannot be performed without them.
As you know every variable is a memory location and every memory locationhas
its address defined which can be accessed using ampersand (&) operator which
denotes an address in memory. Consider the following which will print the
address of the variables defined:
#include<iostream>
usingnamespacestd;
intmain()
{
intvar1;char
var2[10];
cout<<"Addressofvar1variable:"; cout
<<&var1 << endl;
cout<<"Addressofvar2variable:"; cout
<<&var2 << endl;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Addressofvar1variable:0xbfebd5c0
Addressofvar2variable:0xbfebd5b6
Whatare Pointers?
Apointeris a variable whose value is the address of another variable. Like any
variableorconstant,youmustdeclareapointerbeforeyoucanworkwithit.The general
form of a pointer variable declaration is:
119
C++
type*var-name;
Here,typeis the pointer's base type; it must be a valid C++ type andvar-
nameis the name of the pointer variable. The asterisk you used to declare a
pointer is the same asterisk that you use for multiplication. However, in this
statement the asterisk is being used to designate a variable as a pointer.
Following are the valid pointer declaration:
The actual data type of the value of all pointers, whether integer, float,
character,orotherwise,isthe same,a longhexadecimalnumberthatrepresents a
memory address. The only difference between pointers of different data types is
the data type of the variable or constant that the pointer points to.
UsingPointersinC++
There are few important operations, which we will do with the pointers very
frequently.(a) We definea pointervariable.(b)Assign the address ofavariable to a
pointer. (c)Finally access the value at the address available in the pointer
variable. This is done by using unary operator*that returns the value of the
variable located at the address specified by its operand. Following example
makes use of these operations:
#include<iostream>
usingnamespacestd;
intmain()
{
intvar = 20;//actualvariabledeclaration. int*ip;// pointer variable
ip=&var; //storeaddressofvarinpointervariable
cout<<"Valueofvarvariable:";
cout<<var<<endl;
120
C++
//printtheaddressstoredinippointervariable
cout <<"Address stored in ip variable: ";
cout<<ip<< endl;
//accessthevalueattheaddressavailableinpointer cout
<<"Value of *ip variable: ";
cout<<*ip<<endl;
return0;
}
When the above code is compiled and executed, it produces result something as
follows:
Valueofvarvariable:20
Addressstoredinipvariable:0xbfc601ac
Value of *ip variable: 20
PointersinC++
Pointers have many but easy concepts and they are very important to C++
programming. There are following few important pointer concepts which should
be clear to a C++ programmer:
Concept Description
C++pointerarithmetic Therearefourarithmeticoperatorsthatcan be
used on pointers: ++, --, +, -
C++pointertopointer C++allowsyoutohavepointeronapointer
121
C++
andsoon.
NullPointers
#include<iostream>
usingnamespacestd;
intmain()
{
int*ptr=NULL;
cout<<"Thevalueofptris"<<ptr;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Thevalueofptris0
122
C++
if(ptr) //succeedsifpisnotnull
if(!ptr) //succeedsifpisnull
Thus, if all unused pointers are given the null value and you avoid the use of a
null pointer, you can avoid the accidental misuse of an uninitialized pointer.
Many times, uninitialized variables hold some junk values and it becomesdifficult
to debug the program.
PointerArithmetic
As you understood pointer is an address which is a numeric value; therefore,you
can perform arithmetic operations on a pointer just as you can a numeric
value.Therearefourarithmeticoperatorsthatcanbeusedonpointers:++,--,
+,and-
ptr++
theptrwill point to the location 1004 because each time ptr is incremented, it will
point to the next integer. This operation will move the pointer to next memory
location without impacting actual value at the memory location. If ptr points to a
character whose address is 1000, then above operation will point to the location
1001 because next character will be available at 1001.
IncrementingaPointer
We prefer using a pointer in our program instead of an array because the
variable pointer can be incremented, unlike the array name which cannot be
incremented because it is a constant pointer. The following program increments
the variable pointer to access each succeeding element of the array:
#include<iostream>
usingnamespacestd;
const int MAX = 3;
intmain()
{
intvar[MAX]={10,100,200};
123
C++
int*ptr;
//letushavearrayaddressinpointer.
ptr = var;
for(inti=0;i<MAX;i++)
{
cout<<"Addressofvar["<<i<<"]="; cout <<
ptr << endl;
cout<<"Valueofvar["<<i<<"]="; cout
<< *ptr << endl;
//pointtothenextlocation ptr+
+;
}
return0;
}
When the above code is compiled and executed, it produces result something as
follows:
Addressofvar[0] =0xbfa088b0
Valueofvar[0]= 10
Addressofvar[1] =0xbfa088b4
Valueofvar[1]= 100
Addressofvar[2] =0xbfa088b8
Valueofvar[2]= 200
DecrementingaPointer
Thesameconsiderationsapplytodecrementing apointer, whichdecreasesits value
by the number of bytes of its data type as shown below:
#include<iostream>
usingnamespacestd;
const int MAX = 3;
124
C++
intmain()
{
intvar[MAX]={10,100,200};
int*ptr;
//letushaveaddressofthelastelementinpointer. ptr =
&var[MAX-1];
for(inti=MAX;i>0;i--)
{
cout<<"Addressofvar["<<i<<"]="; cout <<
ptr << endl;
cout<<"Valueofvar["<<i<<"]="; cout
<< *ptr << endl;
//pointtothepreviouslocation
ptr--;
}
return0;
}
When the above code is compiled and executed, it produces result something as
follows:
Addressofvar[3] =0xbfdb70f8
Valueofvar[3]= 200
Addressofvar[2] =0xbfdb70f4
Valueofvar[2]= 100
Addressofvar[1] =0xbfdb70f0
Valueofvar[1]= 10
PointerComparisons
Pointers may be compared by using relational operators, such as ==, <, and >.
If p1 and p2 point to variables that are related to each other, such as elements of
the same array, then p1 and p2 can be meaningfully compared.
125
C++
The following program modifies the previous example one by incrementing the
variable pointer so long as the address to which it points is either less than or
equal to the address of the last element of the array, which is &var[MAX - 1]:
#include<iostream>
usingnamespacestd;
const int MAX = 3;
intmain()
{
intvar[MAX]={10,100,200};
int*ptr;
//letushaveaddressofthefirstelementinpointer. ptr =
var;
inti=0;
while(ptr<=&var[MAX-1])
{
cout<<"Addressofvar["<<i<<"]="; cout <<
ptr << endl;
cout<<"Valueofvar["<<i<<"]="; cout
<< *ptr << endl;
//pointtothepreviouslocation ptr+
+;
i++;
}
return0;
}
When the above code is compiled and executed, it produces result something as
follows:
Addressofvar[0]=0xbfce42d0
Value of var[0] = 10
126
C++
Addressofvar[1]=0xbfce42d4
Value of var[1] = 100
Addressofvar[2]=0xbfce42d8
Value of var[2] = 200
PointersvsArrays
Pointers and arrays are strongly related. In fact, pointers and arrays are
interchangeable in many cases. For example, a pointer that points to the
beginning of an array can access that array by using either pointer arithmetic or
array-style indexing. Consider the following program:
#include<iostream>
usingnamespacestd;
const int MAX = 3;
intmain()
{
intvar[MAX]={10,100,200};
int*ptr;
//letushavearrayaddressinpointer.
ptr = var;
for(inti=0;i<MAX;i++)
{
cout<<"Addressofvar["<<i<<"]="; cout <<
ptr << endl;
cout<<"Valueofvar["<<i<<"]="; cout
<< *ptr << endl;
//pointtothenextlocation ptr+
+;
}
return0;
}
127
C++
When the above code is compiled and executed, it produces result something as
follows:
Addressofvar[0] =0xbfa088b0
Valueofvar[0]= 10
Addressofvar[1] =0xbfa088b4
Valueofvar[1]= 100
Addressofvar[2] =0xbfa088b8
Valueofvar[2]= 200
However, pointers and arrays are not completely interchangeable. For example,
consider the following program:
#include<iostream>
usingnamespacestd;
constintMAX=3;
intmain()
{
intvar[MAX]={10,100,200};
for(inti=0;i<MAX;i++)
{
*var=i; //Thisisacorrectsyntax
var++; //Thisisincorrect.
}
return0;
*(var+2)=500;
128
C++
Abovestatementisvalidandwillcompilesuccessfullybecausevarisnot changed.
ArrayofPointers
Beforeweunderstandtheconceptofarrayofpointers,letusconsiderthefollowing
example, which makes use of an array of 3 integers:
#include<iostream>
usingnamespacestd;
const int MAX = 3;
intmain()
{
intvar[MAX]={10, 100,200};
for(inti=0;i<MAX;i++)
{
cout<<"Valueofvar["<<i<<"]="; cout
<< var[i] << endl;
}
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Value of var[0] = 10
Valueofvar[1]=100
Valueofvar[2]=200
There may be a situation, when we want to maintain an array, which can store
pointers to an int or char or any other data type available. Following is the
declaration of an array of pointers to an integer:
int*ptr[MAX];
#include<iostream>
129
C++
usingnamespacestd;
const int MAX = 3;
intmain()
{
intvar[MAX]={10,100,200};
int*ptr[MAX];
for(inti=0;i<MAX;i++)
{
ptr[i]=&var[i];//assigntheaddressofinteger.
}
for(inti=0;i<MAX;i++)
{
cout<<"Valueofvar["<<i<<"]="; cout
<< *ptr[i] << endl;
}
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Value of var[0] = 10
Valueofvar[1]=100
Valueofvar[2]=200
Youcanalsouseanarrayofpointerstocharactertostorealistofstringsas follows:
#include<iostream>
usingnamespacestd;
const int MAX = 4;
intmain()
{
130
C++
char*names[MAX]={
"ZaraAli"
,
"HinaAli"
,
"NuhaAli"
,
"SaraAli",
};
for(inti=0;i<MAX;i++)
{
cout<<"Valueofnames["<<i<<"]="; cout <<
names[i] << endl;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Valueofnames[0]=ZaraAli
Valueofnames[1]=HinaAli
Valueofnames[2]=NuhaAli
Valueofnames[3]=SaraAli
PointertoaPointer
A pointer to a pointer is a form of multiple indirection or a chain of pointers.
Normally, a pointer contains the address of a variable. When we define a pointer
to a pointer, the first pointer contains the address of the second pointer, which
points to the location that contains the actual value as shown below.
int**var;
131
C++
#include<iostream>
usingnamespacestd;
intmain()
{
intvar;
int*ptr;
int**pptr;
var=3000;
//taketheaddressofvar ptr
= &var;
//taketheaddressofptrusingaddressofoperator& pptr =
&ptr;
//takethevalueusing pptr
cout<<"Valueofvar:"<<var<<endl;
cout <<"Value available at *ptr :"<< *ptr << endl;
cout<<"Valueavailableat**pptr:"<<**pptr<<endl;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Valueofvar:3000
Value available at
*ptr :3000
Valueavailableat**pptr:3000
132
C++
PassingPointerstoFunctions
C++ allows you to pass a pointer to a function. To do so, simply declare the
function parameter as a pointer type.
Following a simple example where we pass an unsigned long pointer to a
function and change the value inside the function which reflects back in the
calling function:
#include<iostream>
#include <ctime>
usingnamespacestd;
voidgetSeconds(unsignedlong*par);
intmain()
{
unsignedlongsec;
getSeconds(&sec);
//printtheactualvalue
cout<<"Numberofseconds:"<<sec<<endl;
return0;
}
voidgetSeconds(unsignedlong*par)
{
//getthecurrentnumberofseconds
*par=time(NULL);
return;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Numberofseconds:1294450468
133
C++
Thefunctionwhichcanacceptapointer,canalsoacceptanarrayasshownin the
following example:
#include
<iostream>
usingnamespacestd;
//functiondeclaration:
doublegetAverage(int*arr,intsize);
intmain()
{
//anintarraywith5elements.
intbalance[5]={1000,2,3,17,50}; double
avg;
//passpointertothearrayasanargument. avg =
getAverage( balance, 5 ) ;
//outputthereturnedvalue
cout<<"Averagevalueis:"<<avg<<endl;
return0;
}
doublegetAverage(int*arr,intsize)
{
int i,sum=0;
double avg;
for(i=0;i<size;++i)
{
sum+=arr[i];
}
avg=double(sum)/ size;
134
C++
returnavg;
}
Whentheabovecodeiscompiledtogetherandexecuted,itproducesthe following
result:
Averagevalueis:214.4
ReturnPointerfromFunctions
As we have seen in last chapter how C++ allows to return an array from a
function, similar way C++ allows you to return a pointer from a function. To do
so, you would have to declare a function returning a pointer as in the following
example:
int* myFunction()
{
.
.
.
}
Second point to remember is that, it is not good idea to return the address of a
local variable to outside of the function, so you would have to define the local
variable as staticvariable.
Now, consider the following function, which will generate 10 random numbers
and return them using an array name which represents a pointer i.e., address of
first array element.
#include<iostream>
#include <ctime>
usingnamespacestd;
//functiontogenerateandretrunrandomnumbers.
int * getRandom( )
{
staticintr[10];
135
C++
//settheseed
srand((unsigned)time(NULL));
for (int i = 0; i < 10; ++i)
{
r[i]=rand();
cout<<r[i]<<endl;
}
returnr;
}
//mainfunctiontocallabovedefinedfunction.
int main ()
{
//apointertoanint. int
*p;
p=getRandom();
for(inti=0;i<10;i++)
{
cout<<"*(p+"<<i<<"):"; cout <<
*(p + i) << endl;
}
return0;
}
Whentheabovecodeiscompiledtogetherandexecuted,itproducesresult something
as follows:
624723190
1468735695
807113585
976495677
136
C++
613357504
1377296355
1530315259
1778906708
1820354158
667126415
137
C++
19. REFERENCES
A reference variable is an alias, that is, another name for an already existing
variable. Once a reference is initialized with a variable, either the variable name
or the reference name may be used to refer to the variable.
ReferencesvsPointers
Referencesareoftenconfusedwithpointersbutthreemajordifferencesbetween
references and pointers are:
YoucannothaveNULLreferences.Youmustalwaysbeabletoassume that a
reference is connected to a legitimate piece of storage.
Once a reference is initialized to an object, it cannot be changed to refer
to another object. Pointers can be pointed to another object at any time.
Areferencemustbeinitializedwhenitiscreated.Pointerscanbe initialized at
any time.
CreatingReferencesinC++
int i= 17;
Wecandeclarereferencevariablesforiasfollows.
int& r= i;
Read the & in these declarations asreference. Thus, read the first
declarationas"risanintegerreferenceinitializedtoi"andreadtheseconddeclarationas
"s is a double reference initialized to d." Following example makes use
ofreferences on int and double:
#include<iostream>
usingnamespacestd;
intmain()
{
138
C++
//declaresimple variables
int i;
doubled;
//declarereferencevariables
int& r =i;
double&s= d;
i= 5;
cout<<"Valueofi:"<<i<<endl;
cout<<"Valueofireference:"<<r<< endl;
d= 11.7;
cout<<"Valueofd:"<<d<<endl;
cout<<"Valueofdreference:"<<s<< endl;
return0;
}
Whentheabovecodeiscompiledtogetherandexecuted,itproducesthe following
result:
Valueofi:5
Valueofireference:5 Value
of d : 11.7
Valueofdreference:11.7
References are usually used for function argument lists and function return
values. So following are two important subjects related to C++ references which
should be clear to a C++ programmer:
Concept Description
139
C++
likeanyotherdatatype.
ReferencesasParameters
#include <iostream>
usingnamespacestd;
// function declaration
voidswap(int&x,int&y);
intmain()
{
//localvariabledeclaration:
inta=100;
intb=200;
cout<<"Beforeswap,valueofa:"<<a<<endl;
cout<<"Beforeswap,valueofb:"<<b<<endl;
/*callingafunctiontoswapthevalues.*/
swap(a, b);
cout<<"Afterswap,valueofa:"<<a<< endl;
cout<<"Afterswap,valueofb:"<<b<<endl;
return0;
}
//functiondefinitiontoswapthevalues.
void swap(int& x, int& y)
{
140
C++
inttemp;
temp=x;/*savethevalueataddressx*/
x=y; /*putyintox*/
y=temp;/*putxintoy*/
return;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Beforeswap,valueofa:100
Beforeswap,valueofb:200
After swap, value of a :200
After swap, value of b :100
ReferenceasReturnValue
A C++ program can be made easier to read and maintain by using references
ratherthanpointers.AC++functioncanreturnareferenceinasimilarwayasit returns a
pointer.
When a function returns a reference, it returns an implicit pointer to its return
value. This way, a function can be used on the left side of an assignment
statement. For example, consider this simple program:
#include<iostream>
#include <ctime>
usingnamespacestd;
doublevals[]={10.1,12.6,33.1,24.1,50.0};
double&setValues(inti)
{
returnvals[i]; //returnareferencetotheithelement
}
//mainfunctiontocallabovedefinedfunction.
int main ()
141
C++
cout<<"Valuebeforechange"<<endl; for
( int i = 0; i < 5; i++ )
{
cout<<"vals["<<i<<"]="; cout
<< vals[i] << endl;
}
setValues(1)=20.23;//change2ndelement
setValues(3)=70.8;//change4thelement
cout<<"Valueafterchange"<<endl; for
( int i = 0; i < 5; i++ )
{
cout<<"vals["<<i<<"]= "; cout
<< vals[i] << endl;
}
return0;
}
Whentheabovecodeiscompiledtogetherandexecuted,itproducesthe following
result:
Valuebeforechange
vals[0] = 10.1
vals[1] = 12.6
vals[2] = 33.1
vals[3] = 24.1
vals[4] = 50
Valueaftercha nge
vals[0] =
10.1
vals[1] = 20.23
vals[2] = 33.1
vals[3] = 70.8
142
C++
vals[4]= 50
int&func(){
int q;
//!returnq;//Compiletimeerror static int x;
143
C++
20. DATEANDTIME
The C++ standard library does not provide a proper date type. C++ inherits the
structs and functions for date and time manipulation from C. To access date and
time related functions and structures, you would need to include <ctime>header
file in your C++ program.
Therearefourtime-relatedtypes:clock_t, time_t, size_t,andtm.Thetypes- clock_t,
size_t and time_t are capable of representing the system time and date as some
sort of integer.
The structure typetmholds the date and time in the form of a C structurehaving
the following elements:
structtm{
int tm_sec; //secondsofminutesfrom0to61
int tm_min; // minutes of hour from 0 to
59 int tm_hour;// hours of day from 0 to 24
int tm_mday;// day of month from 1 to
31 int tm_mon;
//monthofyearfrom0to11 int
tm_year;// year since 1900
inttm_wday;//dayssincesunday
inttm_yday;//dayssinceJanuary1st
inttm_isdst;//hoursofdaylightsavingstime
}
Followingare the importantfunctions, whichweusewhile workingwith dateand time
in Cor C++. Allthese functions are partofstandard Cand C++ library and you can
check their detail using reference to C++ standard library given below.
SN Function&Purpose
1 time_ttime(time_t*time);
This returns the current calendar time of the system in number ofseconds
elapsed since January 1, 1970. If the system has no time, .1 is returned.
2 char*ctime(consttime_t*time);
This returns a pointer to a string of the formday month year
144
C++
hours:minutes:secondsyear\n\0.
3 structtm*localtime(consttime_t*time);
Thisreturnsapointertothetmstructurerepresentinglocaltime.
4 clock_tclock(void);
This returns a value that approximates the amount of time the calling
program has been running. A value of .1 is returned if the time is not
available.
5 char*asctime(conststructtm*time);
6 structtm*gmtime(consttime_t*time);
This returns a pointer to the time in the form of a tm structure. The time
is represented in Coordinated Universal Time (UTC), which is essentially
Greenwich Mean Time (GMT).
7 time_tmktime(structtm*time);
Thisreturnsthecalendar-timeequivalentofthetimefoundinthe structure
pointed to by time.
8 doubledifftime(time_ttime2,time_ttime1);
Thisfunctioncalculatesthedifferenceinsecondsbetweentime1and time2.
9 size_tstrftime();
Thisfunctioncanbeusedtoformatdateandtimeinaspecificformat.
CurrentDateand Time
Suppose youwanttoretrieve the currentsystemdateandtime, eitheras a local time
or as a Coordinated Universal Time (UTC). Following is the example to achieve
the same:
#include<iostream>
#include <ctime>
145
C++
usingnamespacestd;
intmain()
{
//currentdate/timebasedoncurrentsystem
time_t now = time(0);
//convertnowtostringform
char* dt = ctime(&now);
cout<<"Thelocaldateandtimeis:"<<dt<< endl;
//convertnowtotmstructforUTC tm
*gmtm = gmtime(&now);
dt=asctime(gmtm);
cout<<"TheUTCdateandtimeis:"<<dt<< endl;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Thelocaldateandtimeis:SatJan820:07:412011
TheUTCdateandtimeis:SunJan903:07:412011
FormatTimeusingstructtm
Thetmstructure is very important while working with date and time in either C or
C++. This structure holds the date and time in the form of a C structure as
mentioned above. Most of the time related functions makes use of tm structure.
Following is an example which makes use of various date and time related
functions and tm structure:
While using structure in this chapter, I'm making an assumption that you have
basic understanding on C structure and how to access structure members using
arrow -> operator.
#include<iostream>
#include <ctime>
146
C++
usingnamespacestd;
intmain()
{
//currentdate/timebasedoncurrentsystem time_t now = time(0);
cout<<"NumberofsecsinceJanuary1,1970:"<<now<<endl;
tm*ltm= localtime(&now);
//printvariouscomponentsoftmstructure.
cout << "Year:"<<1900+ltm->tm_year<<endl;
cout << "Month:"<<1+ltm->tm_mon<<endl;
cout << "Day:"<<ltm->tm_mday<<endl;
cout << "Time:"<<1+ltm->tm_hour<<":";
cout << 1+ltm->tm_min<<":";
cout << 1+ltm->tm_sec<<endl;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
NumberofsecsinceJanuary1,1970:1294548238
Year: 2011
Month:1
Day:8
Time:22:44:59
147
C++
21.BASICINPUT/OUTPUT
HeaderFile FunctionandDescription
<iomanip> This file declares services useful for performing formatted I/O
withso-calledparameterizedstreammanipulators,such as setw
and setprecision.
TheStandardOutputStream(cout)
The predefined objectcoutis an instance ofostreamclass. The cout object is said
to be "connected to" the standard output device, which usually is thedisplay
screen. Thecoutis used in conjunction with the stream insertion operator, which
is written as << which are two less than signs as shown in the following
example.
#include<iostream>
148
C++
usingnamespacestd;
intmain()
{
charstr[]="HelloC++";
cout<<"Valueofstris:"<<str<<endl;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Valueofstris:HelloC++
The C++ compiler also determines the data type of variable to be output and
selects the appropriate stream insertion operator to display the value. The <<
operator is overloaded to output data items of built-in types integer, float,
double, strings and pointer values.
The insertion operator << may be used more than once in a single statement as
shown above andendlis used to add a new-line at the end of the line.
TheStandardInputStream (cin)
#include<iostream>
usingnamespacestd;
intmain()
{
charname[50];
cout<<"Pleaseenteryourname:"; cin
>> name;
cout<<"Yournameis:"<<name<<endl;
149
C++
Pleaseenteryourname:cplusplus
Your name is: cplusplus
The C++ compiler also determines the data type of the entered value andselects
the appropriate streamextraction operator to extract the value andstore it in the
given variables.
The stream extraction operator >> may be used more than once in a single
statement. To request more than one datum you can use the following:
cin>>name>> age;
Thiswillbeequivalenttothefollowingtwo statements:
cin>>name;
cin >> age;
TheStandardErrorStream(cerr)
Thecerris also used in conjunction with the stream insertion operator as shown
in the following example.
#include<iostream>
usingnamespacestd;
intmain()
{
charstr[]="Unableto read.....";
cerr<<"Errormessage:"<<str<< endl;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
150
C++
Errormessage:Unabletoread....
TheStandardLogStream(clog)
#include<iostream>
usingnamespacestd;
intmain()
{
charstr[]="Unableto read.....";
clog<<"Errormessage:"<<str<< endl;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Errormessage:Unabletoread....
You would not be able to see any difference in cout, cerr and clog with these
small examples, but while writing and executing big programs the difference
becomes obvious. So it is good practice to display error messages using cerr
stream and while displaying other log messages then clog should be used.
151
C++
22. DATASTRUCTURES
C/C++ arrays allow you to define variables that combine several data items of
thesame kind, butstructureis another user defined datatype which allows you to
combine data items of different kinds.
Structures are used to represent a record, suppose you want to keep track of
your books in a library. You might want to track the following attributes about
each book:
Title
Author
Subject
Book ID
DefiningaStructure
To define a structure, you must use the struct statement. The struct statement
defines a new data type, with more than one member, for your program. The
format of the struct statement is this:
struct[structuretag]
{
memberdefinition;
memberdefinition;
...
memberdefinition;
}[oneormorestructurevariables];
structBooks
{
chartitle[50];
charauthor[50];
charsubject[100];
152
C++
int book_id;
}book;
AccessingStructureMembers
#include<iostream>
#include<cstring>
usingnamespacestd;
structBooks
{
chartitle[50]; charauthor[50]; charsubject[100]; intbook_id;
};
intmain()
{
structBooksBook1; structBooksBook2;
//DeclareBook1oftypeBook
//DeclareBook2oftypeBook
//book1specification
strcpy(Book1.title,"LearnC++Programming"); strcpy( Book1.author, "Chand Miya
strcpy(Book1.subject,"C++Programming");
Book1.book_id=6495407;
//book2specification
strcpy(Book2.title,"TelecomBilling");
153
C++
strcpy(Book2.author,"YakitSingha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
//PrintBook1info
cout <<"Book 1 title : "<< Book1.title <<endl;
cout <<"Book 1 author : "<< Book1.author
<<endl;
cout<<"Book1subject:"<<Book1.subject<<endl;
cout <<"Book 1 id : "<< Book1.book_id <<endl;
//PrintBook2info
cout <<"Book 2 title : "<< Book2.title <<endl;
cout <<"Book 2 author : "<< Book2.author
<<endl;
cout<<"Book2subject:"<<Book2.subject<<endl;
cout <<"Book 2 id : "<< Book2.book_id <<endl;
return0;
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Book 1 title:LearnC++Programming
Book 1 author:ChandMiyan
Book 1 subject:C++ Programming
Book 1 id: 6495407
Book 2 title:Telecom Billing
Book 2 author:YakitSingha
Book 2 subject:Telecom
Book 2 id: 6495700
StructuresasFunctionArguments
You can pass a structure as a function argument in very similar way as you pass
any other variable or pointer. You would access structure variables in the similar
way as you have accessed in the above example:
#include<iostream>
#include <cstring>
154
C++
usingnamespacestd;
voidprintBook(structBooksbook );
structBooks
{
chartitle[50];
charauthor[50];
charsubject[100];
int book_id;
};
intmain()
{
struct Books Book1; //DeclareBook1oftypeBook
structBooksBook2; //DeclareBook2oftypeBook
//book1specification
strcpy(Book1.title,"LearnC++Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy(Book1.subject,"C++Programming");
Book1.book_id = 6495407;
//book2specification
strcpy(Book2.title,"TelecomBilling");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
//PrintBook1info
printBook(Book1);
//PrintBook2info
printBook(Book2);
155
C++
return0;
}
voidprintBook(structBooksbook)
{
cout <<"Book title : "<< book.title <<endl;
cout <<"Book author : "<< book.author
<<endl;
cout<<"Booksubject:"<<book.subject<<endl;
cout <<"Book id : "<< book.book_id <<endl;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Booktitle:LearnC++Programming
Book author : Chand Miyan
Booksubject:C++Programming
Book id : 6495407
Booktitle:TelecomBilling
Book author : Yakit Singha
Book subject : Telecom
Bookid:6495700
PointerstoStructures
Youcandefinepointerstostructures in verysimilar way as you definepointer to any
other variable as follows:
structBooks*struct_pointer;
Now, you can store the address of a structure variable in the above defined
pointer variable. To find the address of a structure variable, place the ‘&’
operator before the structure's name as follows:
struct_pointer=&Book1;
struct_pointer->title;
Let us re-write above example using structure pointer, hope this will be easy for
you to understand the concept:
156
C++
#include<iostream>
#include <cstring>
usingnamespacestd;
voidprintBook(structBooks*book);
structBooks
{
chartitle[50];
charauthor[50];
charsubject[100];
int book_id;
};
intmain()
{
struct Books Book1; //DeclareBook1oftypeBook
structBooksBook2; //DeclareBook2oftypeBook
//Book1specification
strcpy(Book1.title,"LearnC++Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy(Book1.subject,"C++Programming");
Book1.book_id = 6495407;
//Book2specification
strcpy(Book2.title,"TelecomBilling");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
//PrintBook1info,passingaddressofstructure
printBook( &Book1 );
157
C++
//PrintBook1info,passingaddressofstructure
printBook( &Book2 );
return0;
}
//Thisfunctionacceptpointertostructureasparameter.
void printBook( struct Books *book )
{
cout <<"Book title : "<< book->title <<endl;
cout <<"Book author : "<< book->author
<<endl; cout<<"Booksubject:"<<book-
>subject<<endl; cout <<"Book id : "<< book-
>book_id <<endl;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Booktitle:LearnC++Programming
Book author : Chand Miyan
Booksubject:C++Programming
Book id : 6495407
Booktitle:TelecomBilling
Book author : Yakit Singha
Book subject : Telecom
Bookid:6495700
ThetypedefKeyword
Thereisaneasierwaytodefinestructsoryoucould"alias"typesyoucreate. For
example:
typedefstruct
{
chartitle[50];
charauthor[50];
charsubject[100];
int book_id;
}Books;
158
C++
BooksBook1,Book2;
Youcanusetypedefkeywordfornon-structsaswellasfollows:
typedeflongint*pint32;
pint32x,y,z;
x,yandzareallpointerstolongints.
159
C++
23. CLASSESANDOBJECTS
When you define a class, you define a blueprint for a data type. This doesn't
actually define any data, but it does define what the class name means, that is,
what an object of the class will consist of and what operations can be performed
on such an object.
A class definition starts with the keywordclassfollowed by the class name; and
the class body, enclosed by a pair of curly braces. A class definition must be
followed either by a semicolon or a list of declarations. For example, we define
the Box data type using the keywordclassas follows:
classBox
{
public:
double length; // Length of a
box
doublebreadth;//Breadthofabox
double height; // Height of a
box
The keywordpublicdetermines the access attributes of the members of the class
that follows it. A public member can be accessed from outside the class
anywherewithin the scope ofthe classobject.Youcanalso specifythe members of a
class asprivateor protectedwhich we will discuss in a sub-section.
DefineC++Objects
A class provides the blueprints for objects, so basically an object is created from
a class. We declare objects of a class with exactly the same sort of declaration
that we declare variables of basic types. Following statements declare two
objects of class Box:
BoxBox1; //DeclareBox1oftypeBox
BoxBox2; //DeclareBox2oftypeBox
160
C++
BothoftheobjectsBox1andBox2willhavetheirowncopyofdatamembers.
Accessing the Data Members
The public data members of objects of a class can be accessed using the direct
memberaccessoperator(.).Letustrythe followingexample tomake the things clear:
#include<iostream>
usingnamespacestd;
classBox
{
public:
double length;// Length of a box doublebreadth;//Breadthofabox double height;/
};
intmain()
{
BoxBox1; BoxBox2;
//DeclareBox1oftypeBox
//DeclareBox2oftypeBox
//box1 specification
Box1.height= 5.0;
Box1.length=6.0;
Box1.breadth=7.0;
//box2 specification
Box2.height=10.0;
Box2.length=12.0;
Box2.breadth=13.0;
//volumeofbox1
volume=Box1.height*Box1.length*Box1.breadth;
161
C++
cout<<"VolumeofBox1:"<<volume<<endl;
//volumeofbox2
volume=Box2.height*Box2.length*Box2.breadth;
cout <<"Volume of Box2 : "<< volume <<endl;
return 0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
So far, you have got very basic idea about C++ Classes and Objects. There are
further interesting concepts related to C++ Classes and Objects which we will
discuss in various sub-sections listed below:
Concept Description
162
C++
createdpreviously.
Classmemberfunctions
A member function of a class is a function that has its definition or its prototype
within the class definition like any other variable. It operates on any object ofthe
class of which it is a member, and has access to all the members of a class for
that object.
Let us take previously defined class to access the members of the class using a
member function instead of directly accessing them:
class Box
{
public:
doublelength;
doublebreadth; double height;
//Lengthofabox
//Breadthofabox
//Heightofabox
doublegetVolume(void);//Returnsboxvolume
};
Memberfunctionscanbedefinedwithintheclassdefinitionorseparately
usingscoperesolutionoperator,::.Definingamemberfunctionwithinthe
163
C++
class Box
{
public:
doublelength;
doublebreadth; double height;
//Lengthofabox
//Breadthofabox
//Heightofabox
doublegetVolume(void)
{
returnlength*breadth*height;
}
};
If you like, you can define the same function outside the class usingthe scope
resolution operator (::) as follows:
doubleBox::getVolume(void)
{
returnlength*breadth*height;
}
Here,onlyimportantpointisthatyouwouldhavetouseclassnamejustbefore
:: operator.Amemberfunctionwillbe calledusingadotoperator(.) onaobject where it
will manipulate data related to that object only as follows:
BoxmyBox; //Createanobject
myBox.getVolume();//Callmemberfunctionfortheobject
Let us put above concepts to set and get the value of different class members in
a class:
#include<iostream>
usingnamespacestd;
class Box
164
C++
{
public:
double length; // Length of a
box double breadth; //Breadthofabox
double height; // Height of a
box
//Memberfunctionsdeclaration
double getVolume(void);
void setLength( double len );
voidsetBreadth(doublebre);
void setHeight( double hei );
};
//Memberfunctionsdefinitions
double Box::getVolume(void)
{
returnlength*breadth*height;
}
voidBox::setLength(doublelen)
{
length= len;
}
voidBox::setBreadth(doublebre)
{
breadth=bre;
}
voidBox::setHeight(doublehei)
{
height= hei;
}
165
C++
//Mainfunctionfortheprogram
intmain()
{
BoxBox1; //DeclareBox1oftypeBox
BoxBox2; //DeclareBox2oftype Box
doublevolume=0.0; //Storethevolumeofabox here
//box1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0); Box1.setHeight(5.0);
//box2 specification
Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0);
//volumeofbox1
volume=Box1.getVolume();
cout<<"VolumeofBox1:"<<volume<<endl;
//volumeofbox2
volume=Box2.getVolume();
cout<<"VolumeofBox2:"<<volume<<endl; return 0;
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
ClassAccessModifiers
DatahidingisoneoftheimportantfeaturesofObjectOrientedProgramming
whichallowspreventingthefunctionsofaprogramtoaccessdirectlythe
166
C++
classBase{
public:
//publicmembersgo here
protected:
//protectedmembersgohere
private:
//privatemembersgohere
};
ThepublicMembers
#include<iostream>
usingnamespacestd;
classLine
{
public:
doublelength;
167
C++
voidsetLength(doublelen);
double getLength( void );
};
//Memberfunctionsdefinitions
double Line::getLength(void)
{
returnlength;
}
voidLine::setLength(doublelen)
{
length=len;
}
//Mainfunctionfortheprogram int
main( )
{
Lineline;
Length of line : 6
Lengthofline:10
TheprivateMembers
168
C++
classBox
{
doublewidth;
public:
doublelength;
voidsetWidth(doublewid);
double getWidth( void );
};
#include<iostream>
usingnamespacestd;
classBox
{
public:
doublelength;
voidsetWidth(doublewid);
double getWidth( void );
private:
doublewidth;
};
//Memberfunctionsdefinitions
double Box::getWidth(void)
169
C++
{
returnwidth;
}
voidBox::setWidth(doublewid)
{
width=wid;
}
//Mainfunctionfortheprogram int
main( )
{
Boxbox;
//setboxwidthwithoutmemberfunction
//box.width=10.0;//Error:becausewidthisprivate
box.setWidth(10.0);// Use member function to set
it. cout <<"Width of box : "<< box.getWidth()
<<endl;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Lengthofbox:10
Width of box : 10
TheprotectedMembers
170
C++
You will learn derived classes and inheritance in next chapter. For now you can
check following example where I have derived one child classSmallBoxfrom a
parent class Box.
Following example is similar to above example and herewidthmember will be
accessible by any member function of its derived class SmallBox.
#include <iostream>
usingnamespacestd;
classBox
{
protected:
doublewidth
;
};
classSmallBox:Box//SmallBoxisthederivedclass.
{
public:
voidsetSmallWidth(doublewid);
double getSmallWidth( void );
};
voidSmallBox::setSmallWidth(doublewid)
{
width=wid;
}
//Mainfunctionfortheprogram
int main( ) 171
C++
{
172
C++
SmallBoxbox;
//setboxwidthusingmemberfunction
box.setSmallWidth(5.0);
cout<<"Widthofbox:"<<box.getSmallWidth()<<endl;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Widthofbox:5
Constructor&Destructor
#include<iostream>
usingnamespacestd;
classLine
{
public:
voidsetLength(doublelen);
double getLength( void );
Line();//Thisistheconstructor
private:
doublelength;
};
//Memberfunctionsdefinitionsincludingconstructor
173
C++
Line::Line(void)
{
cout<<"Objectisbeingcreated"<<endl;
}
voidLine::setLength(doublelen)
{
length=len;
}
doubleLine::getLength(void)
{
returnlength;
}
//Mainfunctionfortheprogram int
main( )
{
Lineline;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Objectisbeingcreated
Length of line : 6
ParameterizedConstructor
A default constructor does not have any parameter, but if you need, a
constructor can have parameters. This helps you to assign initial value to an
object at the time of its creation as shown in the following example:
174
C++
#include<iostream>
usingnamespacestd;
classLine
{
public:
voidsetLength(doublelen);
double getLength( void );
Line(doublelen);//Thisistheconstructor
private:
doublelength;
};
//Memberfunctionsdefinitionsincludingconstructor
Line::Line( double len)
{
cout<<"Objectisbeingcreated,length="<<len<<endl; length =
len;
}
voidLine::setLength(doublelen)
{
length=len;
}
doubleLine::getLength(void)
{
returnlength;
}
//Mainfunctionfortheprogram
int main( )
{
175
C++
Lineline(10.0);
//getinitiallysetlength.
cout<<"Lengthofline:"<<line.getLength()<<endl;
//setlinelengthagain
line.setLength(6.0);
cout<<"Lengthofline:"<<line.getLength()<<endl;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Objectisbeingcreated,length=10
Length of line : 10
Lengthofline:6
UsingInitializationListstoInitializeFields
In case of parameterized constructor, you can use following syntax to
initializethe fields:
Line::Line(doublelen):length(len)
{
cout<<"Objectisbeingcreated,length="<<len<<endl;
}
Abovesyntaxisequaltothefollowingsyntax:
Line::Line(doublelen)
{
cout<<"Objectisbeingcreated,length="<<len<<endl;
length = len;
}
If for a class C, you have multiple fields X, Y, Z, etc., to be initialized, then use
can use same syntax and separate the fields by comma as follows:
C::C(doublea,doubleb,doublec):X(a),Y(b),Z(c)
{
176
C++
....
}
TheClassDestructor
#include<iostream>
usingnamespacestd;
classLine
{
public:
voidsetLength(doublelen);
double getLength( void );
Line(); //Thisistheconstructordeclaration
~Line();//Thisisthedestructor:declaration
private:
doublelength;
};
//Memberfunctionsdefinitionsincludingconstructor
Line::Line(void)
{
cout<<"Objectisbeingcreated"<< endl;
}
Line::~Line(void)
{
177
C++
cout<<"Objectisbeingdeleted"<<endl;
}
voidLine::setLength(doublelen)
{
length=len;
}
doubleLine::getLength(void)
{
returnlength;
}
//Mainfunctionfortheprogram int
main( )
{
Lineline;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Objectisbeingcreated
Length of line : 6
Objectisbeingdeleted
CopyConstructor
178
C++
classname(constclassname&obj){
//bodyofconstructor
}
#include<iostream>
usingnamespacestd;
classLine
{
public:
intgetLength(void);
Line( int len ); //simpleconstructor
Line( const Line &obj);// copy constructor
~Line(); //destructor
private:
int*ptr;
};
//Memberfunctionsdefinitionsincludingconstructor
Line::Line(int len)
{
179
C++
cout<<"Normalconstructorallocatingptr"<<endl;
//allocatememoryforthepointer; ptr
= new int;
*ptr=len;
}
Line::Line(constLine&obj)
{
cout<<"Copyconstructorallocatingptr."<<endl; ptr
= new int;
*ptr=*obj.ptr;//copythe value
}
Line::~Line(void)
{
cout<<"Freeingmemory!"<<endl;
delete ptr;
}
intLine::getLength(void)
{
return*ptr;
}
voiddisplay(Lineobj)
{
cout<<"Lengthofline:"<<obj.getLength()<<endl;
}
//Mainfunctionfortheprogram
int main( )
{
Lineline(10);
display(line);
180
C++
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Normalconstructorallocatingptr
Copy constructor allocating
ptr. Length of line : 10
Freeingmemory!
Freeingmemory!
Let us see the same example but with a small change to create another
objectusing existing object of the same type:
#include<iostream>
usingnamespacestd;
classLine
{
public:
intgetLength(void);
Line( int len ); //simpleconstructor
Line( const Line &obj);// copy constructor
~Line(); //destructor
private:
int*ptr;
};
//Memberfunctionsdefinitionsincludingconstructor
Line::Line(int len)
{
cout<<"Normalconstructorallocatingptr"<<endl;
//allocatememoryforthepointer;
ptr = new int;
181
C++
*ptr=len;
}
Line::Line(constLine&obj)
{
cout<<"Copyconstructorallocatingptr."<<endl; ptr
= new int;
*ptr=*obj.ptr;//copythe value
}
Line::~Line(void)
{
cout<<"Freeingmemory!"<<endl;
delete ptr;
}
intLine::getLength(void)
{
return*ptr;
}
voiddisplay(Lineobj)
{
cout<<"Lengthofline:"<<obj.getLength()<<endl;
}
//Mainfunctionfortheprogram
int main( )
{
Lineline1(10);
Lineline2=line1;//Thisalsocallscopyconstructor
display(line1);
display(line2);
182
C++
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Normalconstructorallocatingptr
Copy constructor allocating
ptr. Copy constructor
allocating ptr. Length of
line : 10
Freeingmemory!
Copyconstructorallocatingptr.
Length of line : 10
Freeingmemory
!
Freeingmemory
FriendFunctions
A friend function of a class is defined outside that class' scope but it has theright
to access all private and protected members of the class. Even though the
prototypes for friend functions appear in the class definition, friends are not
member functions.
A friend can be a function, function template, or member function, or a class or
class template, in which case the entire class and all of its members are friends.
Todeclare afunction asafriendof aclass, precede the function prototype in the
class definition with keyword friend as follows:
class Box
{
doublewidth;
public:
doublelength;
friendvoidprintWidth(Boxbox);
void setWidth( double wid );
};
183
C++
friendclassClassTwo;
Considerthefollowingprogram:
#include<iostream>
usingnamespacestd;
class Box
{
doublewidth;
public:
friendvoidprintWidth(Boxbox);
void setWidth( double wid );
};
//Note:printWidth()isnotamemberfunctionofanyclass. void
printWidth( Box box )
{
/*BecauseprintWidth()isafriendofBox,itcan directly
access any member of this class */
cout<<"Widthofbox:"<<box.width<<endl;
}
//Mainfunctionfortheprogram
int main( )
{
Boxbox;
184
C++
//setboxwidthwithoutmemberfunction
box.setWidth(10.0);
//Usefriendfunctiontoprintthewdith.
printWidth( box );
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Widthofbox:10
InlineFunctions
#include<iostream>
usingnamespacestd;
inlineintMax(intx,inty)
{
return(x>y)?x:y;
}
//Mainfunctionfortheprogram
185
C++
intmain()
{
cout<<"Max(20,10):"<<Max(20,10)<<endl;
cout<<"Max(0,200):"<<Max(0,200)<<endl;
cout<<"Max(100,1010):"<<Max(100,1010)<<endl;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Max(20,10):20
Max(0,200):200
Max(100,1010):1010
thisPointer
Every object in C++ has access to its own address through an important pointer
calledthispointer. Thethis pointer is an implicit parameter to all member
functions. Therefore, inside a member function, this may be used to refer to the
invoking object.
Friend functions do not have a this pointer, because friends are not members of
a class. Only member functions have a this pointer.
Letustrythefollowingexampletounderstandtheconceptofthispointer:
#include<iostream>
usingnamespacestd;
class Box
{
public:
//Constructordefinition
Box(doublel=2.0,doubleb=2.0,doubleh=2.0)
{
cout<<"Constructorcalled."<<endl;
length = l;
breadth= b;
186
C++
height=h;
}
doubleVolume()
{
returnlength*breadth*height;
}
intcompare(Boxbox)
{
returnthis->Volume()>box.Volume();
}
private:
double length; // Length of a
box double breadth;
//Breadthofabox
double height; // Height of a
box
};
intmain(void)
{
Box Box1(3.3, 1.2, 1.5); //Declarebox1
BoxBox2(8.5,6.0,2.0); //Declarebox2
if(Box1.compare(Box2))
{
cout<<"Box2issmallerthanBox1"<<endl;
}
else
{
cout<<"Box2isequaltoorlargerthanBox1"<<endl;
}
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
187
Constructorcalled.
C++
Constructorcalled.
Box2isequaltoorlargerthanBox1
PointertoC++Classes
A pointer to a C++ class is done exactly the same way as a pointer to astructure
and to access members of a pointer to a class you use the member access
operator->operator, just as you do with pointers to structures. Also as with all
pointers, you must initialize the pointer before using it.
Letustrythefollowingexampletounderstandtheconceptofpointertoaclass:
#include<iostream>
usingnamespacestd;
class Box
{
public:
//Constructordefinition
Box(doublel=2.0,doubleb=2.0,doubleh=2.0)
{
cout<<"Constructorcalled."<<endl; length = l;
breadth=b; height = h;
}
doubleVolume()
{
returnlength*breadth*height;
}
private:
doublelength; //Lengthofabox
doublebreadth; double
//Breadthofabox
height;
//Heightofabox
};
188
C++
intmain(void)
{
BoxBox1(3.3,1.2,1.5);
BoxBox2(8.5,6.0,2.0); //Declarebox1
Box*ptrBox; //Declarebox2
//Declarepointertoaclass.
//Savetheaddressoffirstobject
ptrBox=&Box1;
//Nowtrytoaccessamemberusingmemberaccessoperator
cout<<"VolumeofBox1:"<<ptrBox->Volume()<<endl;
//Savetheaddressoffirstobject
ptrBox=&Box2;
//Nowtrytoaccessamemberusingmemberaccessoperator
cout<<"VolumeofBox2:"<<ptrBox->Volume()<<endl;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Constructor called.
Constructor called.
VolumeofBox1:5.94
Volume of Box2: 102
StaticMembersofaClass
189
C++
Letustrythefollowingexampletounderstandtheconceptofstaticdata members:
#include<iostream>
usingnamespacestd;
classBox
{
public:
staticintobjectCount;
//Constructordefinition
Box(doublel=2.0,doubleb=2.0,doubleh=2.0)
{
cout<<"Constructorcalled."<<endl;
length = l;
breadth=b;
height = h;
//Increaseeverytimeobjectiscreated
objectCount++;
}
doubleVolume()
{
returnlength*breadth*height;
}
private:
double length; // Length of a
box double breadth;
//Breadthofabox
double height; // Height of a
box
};
//InitializestaticmemberofclassBox
int Box::objectCount = 0;
190
C++
int main(void)
191
C++
{
BoxBox1(3.3,1.2,1.5); //Declarebox1
BoxBox2(8.5,6.0,2.0); //Declarebox2
//Printtotalnumberofobjects.
cout<<"Totalobjects:"<<Box::objectCount<<endl;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Constructorcalled
.
Constructorcalled
. Total objects:
StaticFunctionMembers
By declaring a function member as static, you make it independent of any
particular object of the class. A static member function can be called even if no
objects of the class exist and thestaticfunctions are accessed using only the
class name and the scope resolution operator::.
A static member function can only access static data member, other static
member functions and any other functions from outside the class.
Staticmemberfunctionshaveaclassscopeandtheydonothaveaccessto
thethispointer of the class. You could use a static member function to determine
whether some objects of the class have been created or not.
Let us try the following example to understand the concept of static function
members:
#include<iostream>
usingnamespacestd;
classBox
{
public:
staticintobjectCount;
//Constructordefinition
192
C++
Box(doublel=2.0,doubleb=2.0,doubleh=2.0)
{
cout<<"Constructorcalled."<<endl;
length = l;
breadth=b;
height = h;
//Increaseeverytimeobjectiscreated
objectCount++;
}
doubleVolume()
{
returnlength*breadth*height;
}
staticintgetCount()
{
returnobjectCount;
}
private:
double length; // Length of a
box double breadth;
//Breadthofabox
double height; // Height of a
box
};
//InitializestaticmemberofclassBox
int Box::objectCount = 0;
int main(void)
{
193
C++
194
C++
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
InitalStageCount:0
Constructor called.
Constructor called.
FinalStageCount:2
195
C++
24. INHERITANCE
A class can be derived from more than one classes, which means it can inherit
data and functions from multiple base classes. To define a derived class, we use
a class derivation list to specify the base class(es). A class derivation list names
one or more base classes and has the form:
classderived-class:access-specifierbase-class
#include<iostream>
usingnamespacestd;
//Baseclass
class Shape
{
public:
voidsetWidth(intw)
{
width=w;
}
196
C++
voidsetHeight(inth)
{
height=h;
}
protected:
intwidth;
intheight;
};
//Derivedclass
classRectangle:publicShape
{
public:
intgetArea()
{
return(width*height);
}
};
int main(void)
{
RectangleRect;
Rect.setWidth(5);
Rect.setHeight(7)
;
//Printtheareaoftheobject.
cout<<"Totalarea:"<<Rect.getArea()<<endl;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
197
C++
Totalarea:35
AccessControlandInheritance
A derived class can access all the non-private members of its base class. Thus
base-class members that should not be accessible to the member functions of
derived classes should be declared private in the base class.
We can summarize the different access types according to - who can access
them, in the following way:
Outsideclasses yes no no
Aderivedclassinheritsallbaseclassmethodswiththefollowingexceptions:
Constructors,destructorsandcopyconstructorsofthebase class.
Overloadedoperatorsofthebaseclass.
Thefriendfunctionsofthebaseclass.
Type of Inheritance
When deriving a class from a base class, the base class may be
inheritedthroughpublic,protectedorprivateinheritance. The type of inheritance
is specified by the access-specifier as explained above.
Wehardlyuseprotectedorprivateinheritance,butpublicinheritanceis commonly
used. While using different type of inheritance, following rules are applied:
PublicInheritance:Whenderivingaclassfromapublicbase class,public
members of the base class becomepublicmembers of the
derivedclassandprotectedmembersofthebaseclass
becomeprotectedmembersofthederivedclass.Abase
class'sprivatemembers are never accessible directly from a derived
class,butcanbeaccessedthroughcallsto thepublicandprotectedmembers
of the base class.
ProtectedInheritance:Whenderivingfromaprotectedbase
class,publicandprotectedmembersofthebaseclass become protected
members of the derived class.
198
C++
PrivateInheritance:Whenderivingfromaprivatebase
class,publicandprotectedmembersofthebaseclass become private
members of the derived class.
MultipleInheritance
classderived-class:accessbaseA,accessbaseB....
#include<iostream>
usingnamespacestd;
//BaseclassShape
class Shape
{
public:
voidsetWidth(intw)
{
width=w;
}
voidsetHeight(inth)
{
height=h;
}
protected:
intwidth;
intheight;
};
//BaseclassPaintCost
class PaintCost
{
199
C++
public:
intgetCost(intarea)
{
returnarea*70;
}
};
//Derivedclass
classRectangle:publicShape,publicPaintCost
{
public:
intgetArea()
{
return(width*height);
}
};
int main(void)
{
RectangleRect;
int area;
Rect.setWidth(5);
Rect.setHeight(7)
;
area=Rect.getArea();
//Printtheareaoftheobject.
cout<<"Totalarea:"<<Rect.getArea()<<endl;
//Printthetotalcostofpainting
cout<<"Totalpaintcost:$"<<Rect.getCost(area)<<endl;
200
C++
return0;
201
C++
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Totalarea:35
Totalpaintcost:$2450
202
C++
25. OVERLOADING(O
PERATOR&FUNC
TION)
C++allowsyoutospecifymorethanonedefinitionforafunctionnameor
anoperatorinthesamescope,whichiscalledfunction overloading and operator
overloading respectively.
An overloaded declaration is a declaration that is declared with the same name
as a previously declared declaration in the same scope, except that both
declarations have different arguments and obviously different definition
(implementation).
Whenyou call an overloadedfunctionoroperator, the compiler determines the
most appropriate definition to use, by comparing the argument types you have
used to call the function or operator with the parameter types specified in the
definitions. The process of selecting the most appropriate overloaded function or
operator is called overload resolution.
FunctionOverloadinginC++
#include <iostream>
usingnamespacestd;
classprintData
{
public:
voidprint(inti){
cout<<"Printingint:"<<i<<endl;
}
voidprint(doublef){
cout<<"Printingfloat:"<<f<<endl;
}
203
C++
voidprint(char*c){
cout<<"Printingcharacter:"<<c<<endl;
}
};
int main(void)
{
printDatapd;
//Callprinttoprintinteger
pd.print(5);
//Callprinttoprintfloat
pd.print(500.263);
//Callprinttoprintcharacter
pd.print("Hello C++");
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Printingint:5
Printing float: 500.263
Printingcharacter:HelloC++
OperatorsOverloadinginC++
You can redefine or overload most of the built-in operators available in C++.
Thus, a programmer can use operators with user-defined types as well.
Overloaded operators are functions with special names the keyword operator
followed by the symbol for the operator being defined. Like any other function,
an overloaded operator has a return type and a parameter list.
Boxoperator+(constBox&);
Declares the addition operator that can be used toaddtwo Box objects and
returns final Box object. Most overloaded operators may be defined as ordinary
non-member functions or as class member functions. In case we define above
function as non-member function of a class then we would have to pass two
arguments for each operand as follows:
204
C++
Boxoperator+(constBox&,constBox&);
Following is the example to show the concept of operator over loading using a
memberfunction.Hereanobjectispassedasanargumentwhosepropertieswill be
accessed using this object, the object which will call this operator can be
accessed usingthis operator as explained below:
#include <iostream>
usingnamespacestd;
classBox
{
public:
doublegetVolume(void)
{
returnlength*breadth*height;
}
voidsetLength(doublelen)
{
length=len;
}
voidsetBreadth(doublebre)
{
breadth=bre;
}
voidsetHeight(doublehei)
{
height=hei;
}
//Overload+operatortoaddtwoBoxobjects. Box
operator+(const Box& b)
{
Boxbox;
205
C++
box.length = this->length +
b.length; box.breadth=this-
>breadth+b.breadth; box.height =
this->height + b.height; return box;
}
private:
double length; // Length of a
box double breadth; //Breadthofabox
double height; // Height of a
box
};
//Mainfunctionfortheprogram
int main( )
{
BoxBox1; //DeclareBox1oftype Box
BoxBox2; //DeclareBox2oftype Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0; //Storethevolumeofaboxhere
//box1specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
//box2specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
//volumeofbox1
volume=Box1.getVolume();
cout<<"VolumeofBox1:"<<volume<<endl;
//volumeofbox2
206
C++
volume=Box2.getVolume();
207
C++
cout<<"VolumeofBox2:"<<volume<<endl;
//Addtwoobjectasfollows:
Box3=Box1+Box2;
//volumeofbox3
volume=Box3.getVolume();
cout<<"VolumeofBox3:"<<volume<<endl;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Overloadable/Non-overloadableOperators
Followingisthelistofoperatorswhichcanbeoverloaded:
+ - * / % ^
& | ~ ! , =
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
Followingisthelistofoperators,whichcannotbeoverloaded:
208
C++
:: .* . ?:
OperatorOverloadingExamples
Here are various operator overloading examples to help you in understandingthe
concept.
S.N. OperatorsandExample
1 Unaryoperatorsoverloading
2 Binaryoperatorsoverloading
3 Relationaloperatorsoverloading
4 Input/Outputoperatorsoverloading
5 ++and--operators overloading
6 Assignmentoperatorsoverloading
7 Functioncall()operatoroverloading
8 Subscripting[]operatoroverloading
9 Classmemberaccessoperator->overloading
UnaryOperatorsOverloading
209
C++
#include <iostream>
usingnamespacestd;
classDistance
{
private:
intfeet; //0to infinite
int inches; //0to12
public:
//requiredconstructors
Distance(){
feet=0;
inches=0;
}
Distance(intf,inti)
{ feet = f;
inches=i;
}
//methodtodisplaydistance
void displayDistance()
{
cout<<"F:"<<feet<<"I:"<<inches<<endl;
}
//overloadedminus(-)operator
Distance operator- ()
{
feet = -feet;
inches=-inches;
returnDistance(feet,inches);
}
};
intmain()
{
DistanceD1(11,10),D2(-5,11);
210
C++
-D1; //applynegation
D1.displayDistance(); //displayD1
-D2; //applynegation
D2.displayDistance(); //displayD2
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
F:-11I:-10
F:5I:-11
Hopeaboveexamplemakesyourconceptclearandyoucanapplysimilar concept to
overload Logical Not Operators (!).
Increment(++)andDecrement(--) Operators
Theincrement(++)anddecrement(--)operatorsaretwoimportantunary operators
available in C++.
Following example explain how increment (++) operator can be overloaded for
prefix as well as postfix usage. Similar way, you can overload operator (--).
#include<iostream>
usingnamespacestd;
classTime
{
private:
int hours; intminutes;
public:
//0to23
//0to59
//requiredconstructors
Time(){
hours=0;
minutes= 0;
}
211
C++
Time(inth,intm)
{ hours = h;
minutes = m;
}
//methodtodisplaytime
void displayTime()
{
cout<<"H:"<<hours<<"M:"<<minutes<<endl;
}
//overloadedprefix++operator
Time operator++ ()
{
++minutes; //incrementthisobject
if(minutes >= 60)
{
++hours;
minutes-=60;
}
returnTime(hours,minutes);
}
//overloadedpostfix++operator
Time operator++( int )
{
//savetheorignalvalue
Time T(hours, minutes);
//incrementthisobject
++minutes;
if(minutes>=60)
{
++hours;
minutes-=60;
}
//returnoldoriginalvalue
return T;
212
C++
}
};
intmain()
{
TimeT1(11,59),T2(10,40);
++T1; // incrementT1
T1.displayTime(); // display T1
++T1; // incrementT1again
T1.displayTime(); // display T1
T2++; // increment T2
T2.displayTime(); // display T2
T2++; // incrementT2again
T2.displayTime(); // display T2
return 0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
H: 12 M:0
H: 12 M:1
H: 10 M:41
H: 10 M:42
BinaryOperatorsOverloading
The unary operators take two arguments and following are the examples of
Binary operators. You use binary operators very frequently like addition (+)
operator, subtraction (-) operator and division (/) operator.
Following example explains how addition (+) operator can be overloaded.Similar
way, you can overload subtraction (-) and division (/) operators.
#include <iostream>
usingnamespacestd;
213
C++
class Box
{
double length; // Length of a
box double breadth;
//Breadthofabox
double height; // Height of a
box
public:
doublegetVolume(void)
{
returnlength*breadth*height;
}
voidsetLength(doublelen)
{
length= len;
}
voidsetBreadth(doublebre)
{
breadth= bre;
}
voidsetHeight(doublehei)
{
height=hei;
}
//Overload+operatortoaddtwoBoxobjects. Box
operator+(const Box& b)
{
Boxbox;
box.length = this->length +
b.length; box.breadth=this-
>breadth+b.breadth; box.height =
214
C++
this->height + b.height; return box;
215
C++
}
};
//Mainfunctionfortheprogram
int main( )
{
BoxBox1; //DeclareBox1oftype Box
BoxBox2; //DeclareBox2oftype Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0; //Storethevolumeofaboxhere
//box1specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
//box2specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
//volumeofbox1
volume=Box1.getVolume();
cout<<"VolumeofBox1:"<<volume<<endl;
//volumeofbox2
volume=Box2.getVolume();
cout<<"VolumeofBox2:"<<volume<<endl;
//Addtwoobjectasfollows:
Box3 = Box1 + Box2;
//volumeofbox3
volume=Box3.getVolume();
cout<<"VolumeofBox3:"<<volume<<endl;
216
C++
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
RelationalOperatorsOverloading
TherearevariousrelationaloperatorssupportedbyC++languagelike(<,>,
<=,>=,==,etc.)whichcanbeusedtocompareC++built-indatatypes.
Youcanoverloadanyoftheseoperators,whichcanbeusedtocomparethe objects of a
class.
Following example explains how a < operator can be overloaded andsimilar way
you can overload other relational operators.
#include<iostream>
usingnamespacestd;
classDistance
{
private:
int feet; intinches;
public:
//0to infinite
//0to12
//requiredconstructors
Distance(){ feet=0;
inches=0;
}
Distance(intf,inti){ feet = f;
inches=i;
}
//methodtodisplaydistance
217
C++
voiddisplayDistance()
{
cout<<"F:"<<feet<<"I:"<<inches<<endl;
}
//overloadedminus(-)operator
Distance operator- ()
{
feet = -feet;
inches=-inches;
returnDistance(feet,inches);
}
//overloaded<operator
booloperator<(constDistance&d)
{
if(feet<d.feet)
{
returntrue;
}
if(feet==d.feet&&inches<d.inches)
{
returntrue;
}
returnfalse;
}
};
intmain()
{
DistanceD1(11,10),D2(5,11);
if(D1<D2)
{
cout<<"D1islessthanD2"<<endl;
}
else
218
C++
{
cout<<"D2islessthanD1"<<endl;
}
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
D2islessthanD1
Input/OutputOperatorsOverloading
C++ is able to input and output the built-in data types using the stream
extraction operator >> and the stream insertion operator <<. The stream
insertion and stream extraction operators also can be overloaded to perform
input and output for user-defined types like an object.
Here, it is important to make operator overloading function a friend of the class
because it would be called without creating an object.
Followingexampleexplainshowextractionoperator>>andinsertionoperator
<<.
#include<iostream>
usingnamespacestd;
classDistance
{
private:
int feet; intinches;
public:
//0to infinite
//0to12
//requiredconstructors
Distance(){ feet=0;
inches=0;
}
Distance(intf,inti){ feet = f;
inches=i;
219
C++
}
friendostream&operator<<(ostream&output,
constDistance&D)
{
output<<"F:"<<D.feet<<"I:"<<D.inches; return
output;
}
friendistream&operator>>(istream&input,Distance&D)
{
input>>D.feet>>D.inches;
return input;
}
};
intmain()
{
DistanceD1(11,10),D2(5,11),D3;
cout<<"Enterthevalueofobject:"<<endl; cin
>> D3;
cout<<"FirstDistance:"<<D1<<endl;
cout<<"SecondDistance:"<<D2<<endl;
cout <<"Third Distance :"<< D3 <<
endl;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
$./a.out
Enterthevalueofobject: 70
10
FirstDistance:F:11I:10
220
C++
SecondDistance:F:5I:11
ThirdDistance:F:70I:10
++and--Operators Overloading
Theincrement(++)anddecrement(--)operatorsaretwoimportantunary operators
available in C++.
Following example explain how increment (++) operator can be overloaded for
prefix as well as postfix usage. Similar way, you can overload operator (--).
#include<iostream>
usingnamespacestd;
classTime
{
private:
inthours; // 0 to 23
intminutes; // 0 to 59
public:
//requiredconstructors Time(){
hours=0;
minutes= 0;
}
Time(inth,intm){ hours = h; minutes = m;
}
//methodtodisplaytime void displayTime()
{
cout<<"H:"<<hours<<"M:"<<minutes<<endl;
}
//overloadedprefix++operator Time operator++ ()
{
221
C++
++minutes; //incrementthisobject
if(minutes >= 60)
{
++hours;
minutes-=60;
}
returnTime(hours,minutes);
}
//overloadedpostfix++operator
Time operator++( int )
{
//savetheorignalvalue
Time T(hours, minutes);
//incrementthisobject
++minutes;
if(minutes>=60)
{
++hours;
minutes-=60;
}
//returnoldoriginalvalue
return T;
}
};
intmain()
{
TimeT1(11,59),T2(10,40);
++T1; //incrementT1
T1.displayTime(); //displayT1
++T1; //incrementT1again
T1.displayTime(); //displayT1
T2++; //incrementT2
222
C++
T2.displayTime(); //displayT2
T2++; //incrementT2again
T2.displayTime(); return 0;
//displayT2
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
H: 12 M:0
H: 12 M:1
H: 10 M:41
H: 10 M:42
AssignmentOperatorsOverloading
You can overload the assignment operator (=) just as you can other
operatorsand it can be used to create an object just like the copy constructor.
Followingexampleexplainshowanassignmentoperatorcanbeoverloaded.
#include<iostream>
usingnamespacestd;
classDistance
{
private:
int feet; intinches;
public:
//0to infinite
//0to12
//requiredconstructors
Distance(){ feet=0;
inches=0;
}
Distance(intf,inti){ feet = f;
inches=i;
}
223
C++
voidoperator=(constDistance&D)
{
feet = D.feet;
inches=D.inches;
}
//methodtodisplaydistance
void displayDistance()
{
cout<<"F:"<<feet<<"I:"<<inches<<endl;
}
};
intmain()
{
DistanceD1(11,10),D2(5,11);
cout<<"FirstDistance:";
D1.displayDistance();
cout<<"SecondDistance:";
D2.displayDistance();
//useassignmentoperator
D1 = D2;
cout<<"FirstDistance:";
D1.displayDistance();
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
FirstDistance:F:11I:10
Second Distance :F: 5
I:11 First Distance :F: 5
I:11
FunctionCall()OperatorOverloading
224
C++
The function call operator () can be overloaded for objects of class type. When
you overload ( ), you are not creating a new way to call a function. Rather, you
are creating an operator function that can be passed an arbitrary number of
parameters.
Followingexampleexplainshowafunctioncalloperator()canbe overloaded.
#include
<iostream>
usingnamespacestd;
classDistance
{
private:
intfeet; //0to infinite
int inches; //0to12
public:
//requiredconstructors
Distance(){
feet=0;
inches=0;
}
Distance(intf,inti)
{ feet = f;
inches=i;
}
//overloadfunctioncall
Distanceoperator()(inta,intb,int c)
{
DistanceD;
//justputrandomcalculation
D.feet = a + c + 10;
D.inches=b+c+100; return
D;
}
//methodtodisplaydistance
void displayDistance()
{ 225
C++
cout<<"F:"<<feet<<"I:"<<inches<<endl;
}
};
intmain()
{
DistanceD1(11,10),D2;
cout<<"FirstDistance:";
D1.displayDistance();
D2=D1(10,10,10);//invokeoperator()
cout <<"Second Distance :";
D2.displayDistance();
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Subscripting[]OperatorOverloading
#include <iostream>
usingnamespacestd;
constintSIZE=10;
classsafearay
{
private:
226
C++
intarr[SIZE];
public:
safearay()
{
registerinti;
for(i=0;i<SIZE; i++)
{
arr[i]= i;
}
}
int&operator[](inti)
{
if(i>SIZE)
{
cout<<"Indexoutofbounds"<<endl;
//returnfirstelement.
return arr[0];
}
returnarr[i];
}
};
intmain()
{
safearayA;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
ValueofA[2]:2
227
C++
Value of A[5] : 5
Indexoutofbounds
Value of A[12] : 0
ClassMemberAccessOperator->Overloading
The class member accessoperator (->) can be overloaded but it is bit trickier. It
isdefinedtogive aclasstype a"pointer-like"behavior.Theoperator ->mustbe a
member function. If used, its return type must be a pointer or an object of a class
to which you can apply.
The operator-> is used often in conjunction with the pointer-dereference
operator * to implement "smart pointers." These pointers are objects that behave
like normal pointers except they perform other tasks when you accessan object
through them, such as automatic object deletion either when the pointer is
destroyed, or the pointer is used to point to another object.
The dereferencing operator-> can be defined as a unary postfix operator. Thatis,
given a class:
classPtr{
//...
X*operator->();
};
voidf(Ptrp)
{
p->m=10;//(p.operator->())->m= 10
}
#include <iostream>
#include <vector>
usingnamespacestd;
//Consideranactualclass.
class Obj {
228
C++
staticinti,j;
public:
voidf()const{cout<<i++<<endl;}
voidg()const{cout<<j++<<endl;}
};
//Staticmemberdefinitions:
int Obj::i = 10;
intObj::j=12;
//Implementacontainerfortheaboveclass
class ObjContainer {
vector<Obj*>a;
public:
voidadd(Obj*obj)
{
a.push_back(obj);//callvector'sstandardmethod.
}
friendclassSmartPointer;
};
//implementsmartpointertoaccessmemberofObjclass.
class SmartPointer {
ObjContaineroc;
int index;
public:
SmartPointer(ObjContainer&objc)
{
oc=objc;
index=0;
}
//Returnvalueindicatesendoflist:
bool operator++() // Prefix version
{
229
C++
if(index>=oc.a.size())returnfalse;
if(oc.a[++index] == 0) return false;
return true;
}
booloperator++(int)//Postfixversion
{
returnoperator++();
}
// overload operator-
> Obj*operator-
>()const
{
if(!oc.a[index])
{
cout<<"Zerovalue";
return (Obj*)0;
}
returnoc.a[index];
}
};
intmain(){
constintsz=10;
Obj o[sz];
ObjContainer oc;
for(inti=0;i<sz;i++)
{
oc.add(&o[i]);
}
SmartPointersp(oc);//Createaniterator
do {
sp->f();//smartpointercall
sp->g();
}while(sp++);
230
C++
return 0;
231
C++
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
10
12
11
13
12
14
13
15
14
16
15
17
16
18
17
19
18
20
19
21
232
C++
26.POLYMORPHISM
#include <iostream>
usingnamespacestd;
classShape{ pro
tected:
intwidth,height;
public:
Shape(inta=0,intb=0)
{
width = a;
height=b;
}
intarea()
{
cout<<"Parentclassarea:"<<endl;
return 0;
}
};
classRectangle:publicShape{ pub
lic:
Rectangle(inta=0,intb=0):Shape(a,b){} int
area ()
{
cout<<"Rectangleclassarea:"<<endl;
233
C++
return(width*height);
}
};
classTriangle:publicShape{ pu
blic:
Triangle(inta=0,intb=0):Shape(a,b){}
int area ()
{
cout<<"Triangleclassarea:"<<endl;
return (width * height / 2);
}
};
//Mainfunctionfortheprogram
int main( )
{
Shape *shape;
Rectanglerec(10,7);
Triangletri(10,5);
//storetheaddressofRectangle
shape = &rec;
//callrectanglearea.
shape->area();
//storetheaddressofTriangle
shape = &tri;
//calltrianglearea.
shape->area();
return0;
}
234
C++
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Parentclassarea
Parentclassarea
The reason for the incorrect output is that the call of the function area() is being
setoncebythecompilerastheversiondefinedinthebaseclass.Thisis calledstatic
resolutionof the function call, orstatic linkage- the function call is fixed before
the program is executed. This is also sometimes calledearly bindingbecause
the area() function is set during the compilation of the program.
But now, let's make a slight modification in our program and precede the
declaration of area() in the Shape class with the keywordvirtualso that it looks
like this:
classShape{ pro
tected:
intwidth,height;
public:
Shape(inta=0,intb=0)
{
width = a;
height=b;
}
virtualintarea()
{
cout<<"Parentclassarea:"<<endl;
return 0;
}
};
After this slight modification, when the previous example code is compiled
andexecuted, it produces the following result:
Rectangleclassarea
Triangle class area
This time, the compiler looks at the contents of the pointer instead of its type.
Hence, since addresses of objects of tri and rec classes are stored in *shape the
respective area() function is called.
235
C++
As you can see, each of the child classes has a separate implementation for the
functionarea().This is howpolymorphismis generallyused. Youhave different
classes with a function of the same name, and even the same parameters, but
with different implementations.
VirtualFunction
Avirtualfunctionisafunctioninabaseclassthatisdeclaredusingthe
keywordvirtual.Defining in a base class a virtual function, with another version
in a derived class, signals to the compiler that we don't want static linkage for
this function.
What we do want is the selection of the function to be called at any given point
in the program to be based on the kind of object for which it is called. This sort of
operation is referred to asdynamic linkage, orlate binding.
PureVirtualFunctions
It is possible that you want to include a virtual function in a base class so that it
may be redefined in a derived class to suit the objects of that class, but that
there is no meaningful definition you could give for the function in the baseclass.
Wecanchangethevirtualfunctionarea()inthebaseclasstothefollowing:
classShape{ pro
tected:
intwidth,height;
public:
Shape(inta=0,intb=0)
{
width = a;
height=b;
}
//purevirtualfunction
virtual int area() = 0;
};
236
C++
27. DATAABSTRACTION
#include <iostream>
usingnamespacestd;
intmain()
{
cout<<"HelloC++"<<endl;
return 0;
}
237
C++
Here, you don't need to understand howcoutdisplays the text on the user's
screen. You need to only know the public interface and the underlying
implementation of ‘cout’ is free to change.
AccessLabelsEnforceAbstraction
In C++, we use access labels to define the abstract interface to the class. Aclass
may contain zero or more access labels:
Members defined with a public label are accessible to all parts of the
program. The data-abstraction view of a type is defined by its public
members.
Members defined with a private label are not accessible to code that uses
the class. The private sections hide the implementation from code that
uses the type.
There are no restrictions on how often an access label may appear. Each access
label specifies the access level of the succeeding member definitions. The
specified access level remains in effect until the next access label is encountered
or the closing right brace of the class body is seen.
BenefitsofDataAbstraction
Dataabstractionprovidestwoimportantadvantages:
Any C++ program where you implement a class with public and privatemembers
is an example of data abstraction. Consider the following example:
#include <iostream>
usingnamespacestd;
classAdder{
public:
// constructor
Adder(inti=0)
238
C++
{
total=i;
}
//interfacetooutsideworld
void addNum(int number)
{
total+=number;
}
//interfacetooutsideworld
int getTotal()
{
returntotal;
};
private:
//hiddendatafromoutsideworld
int total;
};
intmain()
{
Addera;
a.addNum(10);
a.addNum(20);
a.addNum(30);
cout<<"Total"<<a.getTotal()<<endl;
return 0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Total60
Above class adds numbers together, and returns the sum. The public members -
addNum andgetTotalare the interfaces to the outside world and a user needs
to know them to use the class. The private membertotalis something that the
userdoesn'tneedtoknowabout,butisneededfortheclasstooperateproperly.
239
C++
DesigningStrategy
240
C++
28. DATAENCAPSULATION
AllC++programsarecomposedofthefollowingtwofundamentalelements:
Programstatements(code):Thisisthepartofaprogramthat performs
actions and they are called functions.
Programdata:Thedataistheinformationoftheprogramwhichgets affected
by the program functions.
Encapsulation is an Object Oriented Programming concept that binds together
the data and functions that manipulate the data, and that keeps both safe from
outside interference and misuse. Data encapsulation led to the important OOP
concept of data hiding.
Dataencapsulationis a mechanism of bundling the data, and the functions that
use them anddata abstractionis a mechanism of exposing only the interfaces
and hiding the implementation details from the user.
C++ supports the properties of encapsulation and data hiding through the
creation of user-defined types, calledclasses. We already have studied that a
class can containprivate,protectedandpublicmembers. By default, all items
defined in a class are private. For example:
classBox
{
public:
doublegetVolume(void)
{
returnlength*breadth*height;
}
private:
doublelength; //Lengthofabox
doublebreadth; double
//Breadthofabox
height;
//Heightofabox
};
The variables length, breadth, and height areprivate. This means that they can
be accessed only by other members of the Box class, and not by any other part
of your program. This is one way encapsulation is achieved.
To make parts of a classpublic(i.e., accessible to other parts of your program),
youmustdeclarethemafterthepublickeyword.Allvariablesorfunctions
241
C++
defined after the public specifier are accessible by all other functions in your
program.
Making one class a friend of another, exposes the implementation details and
reduces encapsulation. The ideal is to keep as many of the details of each class
hidden from all other classes as possible.
DataEncapsulationExample
Any C++ program where you implement a class with public and
privatemembersisanexampleofdataencapsulationanddataabstraction.Considerthe
following example:
#include <iostream>
usingnamespacestd;
classAdder{
public:
// constructor
Adder(inti=0)
{
total=i;
}
//interfacetooutsideworld
void addNum(int number)
{
total+=number;
}
//interfacetooutsideworld
int getTotal()
{
returntotal;
};
private:
//hiddendatafromoutsideworld
int total;
};
intmain()
{
242
C++
Addera;
a.addNum(10);
a.addNum(20);
a.addNum(30);
cout<<"Total"<<a.getTotal()<<endl;
return 0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Total60
Above class adds numbers together, and returns the sum. The public members -
addNum andgetTotalare the interfaces to the outside world and a user needs
to know them to use the class. The private membertotalis something that is
hidden from the outside world, but is needed for the class to operate properly.
DesigningStrategy
243
C++
29. INTERFACES
classBox
{
public:
// pure virtual function virtualdoublegetVolume()=0;
private:
doublelength; //Lengthofabox
doublebreadth; double
//Breadthofabox
height;
//Heightofabox
};
#include<iostream>
244
C++
usingnamespacestd;
//Baseclass
class Shape
{
public:
//purevirtualfunctionprovidinginterfaceframework.
virtual int getArea() = 0;
voidsetWidth(intw)
{
width=w;
}
voidsetHeight(inth)
{
height= h;
}
protected:
int width;
intheight;
};
//Derivedclasses
classRectangle:publicShape
{
public:
intgetArea()
{
return(width*height);
}
};
classTriangle:publicShape
{
public:
245
C++
intgetArea()
{
return(width*height)/2;
}
};
int main(void)
{
RectangleRect;
Triangle Tri;
Rect.setWidth(5);
Rect.setHeight(7);
//Printtheareaoftheobject.
cout<<"TotalRectanglearea:"<<Rect.getArea()<<endl;
Tri.setWidth(5);
Tri.setHeight(7);
//Printtheareaoftheobject.
cout<<"TotalTrianglearea:"<<Tri.getArea()<<endl;
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
TotalRectanglearea:35
Total Triangle area: 17
246
C++
The capabilities (i.e., the public functions) offered by the external applications
are provided as pure virtual functions in the abstract base class. The
implementations of these pure virtual functions are provided in the derived
classes that correspond to the specific types of the application.
This architecture also allows new applications to be added to a system easily,
even after the system has been defined.
247
C++
30. FILESANDSTREAMS
Sofar,wehavebeenusingtheiostreamstandardlibrary,which providescinandcout
methods for reading from standard input and writing to standard output
respectively.
This tutorial will teach you how to read and write from a file. This requires
another standard C++ library calledfstream, which defines three new data
types:
DataType Description
ifstream This data type represents the input file stream and is
used to read information from files.
ToperformfileprocessinginC++,headerfiles<iostream>and<fstream>must be
included in your C++ source file.
OpeningaFile
Afilemust beopened beforeyoucan read from it orwritetoit.Either
ofstreamorfstreamobject maybe used to open a file for writing.And ifstream
object is used to open a file for reading purpose only.
Following is the standard syntax for open() function, which is a member of
fstream, ifstream, and ofstream objects.
voidopen(constchar*filename,ios::openmodemode);
Here, the first argument specifies the name and location of the file to be opened
and the second argument of theopen()member function defines the mode in
which the file should be opened.
ModeFlag Description
248
C++
ios::ate Open a file for output and move the read/write control
to the end of the file.
You can combine two or more of these values byORing them together. For
example if you want to open a file in write mode and want to truncate it in case
that already exists, following will be the syntax:
ofstreamoutfile;
outfile.open("file.dat",ios::out|ios::trunc);
Similarway,youcanopenafileforreadingandwritingpurposeasfollows:
fstreamafile;
afile.open("file.dat",ios::out|ios::in);
ClosingaFile
voidclose();
Writingtoa File
While doing C++ programming, you write information to a file from your
program using the stream insertion operator (<<) just as you use that operator
tooutputinformationtothescreen.Theonlydifferenceisthatyouuse
anofstreamorfstreamobject instead of the coutobject.
ReadingfromaFile
249
C++
You read information from a file into your program using the stream extraction
operator (>>) just as you use that operator to input information from the
keyboard. The only difference is that you use anifstreamorfstreamobject
instead of the cin object.
Read&WriteExample
Following is the C++ program which opens a file in reading and writing mode.
After writing information entered by the user to a file named afile.dat, the
program reads information from the file and outputs it onto the screen:
#include <fstream>
#include <iostream>
usingnamespacestd;
intmain()
{
chardata[100];
//openafileinwritemode.
ofstream outfile;
outfile.open("afile.dat");
cout<<"Writingtothefile"<<endl; cout
<<"Enter your name: ";
cin.getline(data, 100);
//writeinputteddataintothefile.
outfile << data << endl;
cout<<"Enteryourage:";
cin >> data;
cin.ignore();
//againwriteinputteddataintothefile.
outfile << data << endl;
250
C++
//closetheopenedfile.
outfile.close();
//openafileinreadmode.
ifstream infile;
infile.open("afile.dat");
cout<<"Readingfromthefile"<<endl;
infile >> data;
//writethedataatthescreen. cout
<< data << endl;
//againreadthedatafromthefileanddisplayit. infile
>> data;
cout<<data<<endl;
//closetheopenedfile.
infile.close();
return0;
}
$./a.out
Writing to the file
Enteryourname:Zara
Enter your age: 9
Readingfromthefile
Zara
9
Above examples make use of additional functions from cin object, like getline()
function to read the line from outside, and ignore() function to ignore the extra
characters left by previous read statement.
251
C++
FilePositionPointers
//positiontothenthbyteoffileObject(assumesios::beg)
fileObject.seekg( n );
//positionnbytesforwardinfileObject
fileObject.seekg( n, ios::cur );
//positionnbytesbackfromendoffileObject
fileObject.seekg( n, ios::end );
//positionatendoffileObject
fileObject.seekg(0,ios::end);
252
C++
31. EXCEPTIONHANDLING
try
{
//protectedcode
}catch(ExceptionNamee1)
{
//catchblock
}catch(ExceptionNamee2)
{
//catchblock
}catch(ExceptionNameeN)
{
//catchblock
}
Youcanlistdownmultiplecatchstatementstocatchdifferenttypeofexceptions in
case yourtryblock raises more than one exception in different situations.
253
C++
ThrowingExceptions
doubledivision(inta,intb)
{
if(b==0)
{
throw"Divisionbyzerocondition!";
}
return(a/b);
}
CatchingExceptions
Thecatchblock following thetryblock catches any exception. You can specify
what type of exception you want to catch and this is determined by the
exception declaration that appears in parentheses following the keyword catch.
try
{
//protectedcode
}catch(ExceptionNamee)
{
//codetohandleExceptionNameexception
}
try
{
//protectedcode
}catch(...)
[Type text]
C++
{
//codetohandleanyexception
}
#include <iostream>
usingnamespacestd;
doubledivision(inta,intb)
{
if(b==0)
{
throw"Divisionbyzerocondition!";
}
return(a/b);
}
intmain()
{
int x = 50;
int y = 0;
doublez=0;
try{
z=division(x,y);
cout << z << endl;
}catch(constchar*msg)
{ cerr << msg << endl;
}
return0;
}
[Type text]
C++
Divisionbyzerocondition!
C++StandardExceptions
C++ provides a list of standard exceptions defined in<exception>which we can
use in our programs. These are arranged in a parent-child class hierarchy shown
below:
Exception Description
[Type text]
C++
std::bad_alloc Thiscanbethrownbynew.
std::bad_cast Thiscanbethrownbydynamic_cast.
std::bad_typeid Thiscanbethrownbytypeid.
std::logic_error Anexceptionthattheoreticallycanbedetectedbyreading
the code.
std::invalid_argument Thisisthrownduetoinvalidarguments.
std::overflow_error Thisisthrownifamathematicaloverflowoccurs.
DefineNewExceptions
Youcandefineyour ownexceptionsby inheritingandoverridingexceptionclass
functionality. Following is the example, which shows how you can use
std::exception class to implement your own exception in standard way:
#include <iostream>
#include<exception>
usingnamespacestd;
[Type text]
C++
structMyException:publicexception
{
constchar*what()constthrow()
{
return"C++Exception";
}
};
intmain()
{
try
{
throwMyException();
}
catch(MyException&e)
{
std::cout<<"MyExceptioncaught"<<std::endl;
std::cout << e.what() << std::endl;
}
catch(std::exception&e)
{
//Othererrors
}
}
Thiswouldproducethefollowingresult:
MyExceptioncaught
C++ Exception
[Type text]
C++
32. DYNAMICMEMORY
The stack:All variables declared inside the function will take up memory
from the stack.
Many times, you are not aware in advance how much memory you will need to
store particular information in a defined variable and the size of required
memory can be determined at run time.
You can allocate memory at run time within the heap for the variable of a given
type using a special operator in C++ which returns the address of the space
allocated. This operator is called new operator.
If you are not in need of dynamically allocated memory anymore, you can use
delete operator, which de-allocates memory previously allocated by new
operator.
ThenewanddeleteOperators
newdata-type;
Here,data-type could be any built-in data type including an array or any user
defined data types include class or structure. Let us start with built-in datatypes.
For example we can define a pointer to type double and then request that the
memory be allocated at execution time. We can do this using the new operator
with the following statements:
double*pvalue = NULL;
if( !(pvalue =newdouble))
{
cout<<"Error:outofmemory."<<endl; exit(1);
deletepvalue; //Releasememorypointedtobypvalue
#include<iostream>
usingnamespacestd;
intmain()
{
double* pvalue= NULL; // Pointer initialized with null pvalue= new double;//Re
*pvalue=29494.99; //Storevalueatallocatedaddress
cout<<"Valueofpvalue:"<<*pvalue<< endl;
deletepvalue; //freeupthememory.
return0;
}
Ifwecompileandrunabovecode,thiswouldproducethefollowingresult:
260
C++
Valueofpvalue: 29495
DynamicMemoryAllocationforArrays
Consider you want to allocate memory for an array of characters, i.e., string of
20 characters. Using the same syntax what we have used above we can allocate
memory dynamically as shown below.
delete[]pvalue; //Deletearraypointedtobypvalue
Followingisthesyntaxofnewoperatorforamulti-dimensionalarrayasfollows:
intROW=2;
intCOL=3;
double**pvalue =newdouble*[ROW];//Allocatememoryfor rows
//Nowallocatememoryforcolumns
for(int i = 0; i < COL; i++) {
pvalue[i]=newdouble[COL];
}
Thesyntaxtoreleasethememoryformulti-dimensionalwillbeasfollows:
for(inti=0;i<COL;i++){ delete[]
pvalue[i];
}
delete[]pvalue;
DynamicMemoryAllocationforObjects
Objects are no different from simple data types. For example, consider the
following code where we are going to use an array of objects to clarify the
concept:
#include <iostream>
usingnamespacestd;
261
C++
classBox
{
public:
Box(){
cout<<"Constructorcalled!"<<endl;
}
~Box(){
cout<<"Destructorcalled!"<<endl;
}
};
intmain()
{
Box*myBoxArray=newBox[4];
delete[]myBoxArray;//Deletearray
return0;
}
If you were to allocate an array of four Box objects, the Simple constructor would
be called four times and similarly while deleting these objects, destructor will
also be called same number of times.
Ifwecompileandrunabovecode,thiswouldproducethefollowingresult:
Constructorcalled!
Constructorcalled!
Constructorcalled!
Constructorcalled!
Destructor called!
Destructor called!
Destructor called!
Destructor called!
262
C++
33. NAMESPACES
Consider a situation, when we have two persons with the same name, Zara, in
the same class. Whenever we need to differentiate them definitely we would
have to use some additional information along with their name, like either the
area, if they live in different area or their mother’s or father’s name, etc.
Same situation can arise in your C++ applications. For example, you might be
writing some code that has a function called xyz() and there is another library
available which isalsohavingsame functionxyz().Nowthe compilerhasnoway of
knowing which version of xyz() function you are referring to within your code.
namespacenamespace_name{
//codedeclarations
}
name::code;//codecouldbevariableorfunction.
Letusseehownamespacescopetheentitiesincludingvariableandfunctions:
#include <iostream>
usingnamespacestd;
263
C++
//Callsfunctionfromfirstnamespace.
first_space::func();
//Callsfunctionfromsecondnamespace.
second_space::func();
return0;
}
Ifwecompileandrunabovecode,thiswouldproducethefollowingresult:
Inside first_space
Insidesecond_space
Theusingdirective
Youcanalsoavoidprependingofnamespaceswiththeusing namespacedirective.
This directive tells the compiler that the subsequent code is making use of
names in the specified namespace. The namespace is thus implied for the
following code:
#include <iostream>
usingnamespacestd;
264
C++
}
// second name space
namespacesecond_space
{
voidfunc(){
cout<<"Insidesecond_space"<<endl;
}
}
usingnamespacefirst_space;
int main ()
{
//Thiscallsfunctionfromfirstnamespace.
func();
return0;
}
Ifwecompileandrunabovecode,thiswouldproducethefollowingresult:
Insidefirst_space
The ‘using’ directive can also be used to refer to a particular item within a
namespace. For example, if the only part of the std namespace that you intend
to use is cout, you can refer to it as follows:
usingstd::cout;
#include<iostream>
using std::cout;
intmain()
{
cout<<"std::endlisusedwithstd!"<<std::endl;
265
C++
return0;
}
Ifwecompileandrunabovecode,thiswouldproducethefollowingresult:
std::endlisusedwithstd!
namespacenamespace_name{
//codedeclarations
}
NestedNamespaces
Namespaces can be nested where you can define one namespace inside another
namespace as follows:
namespacenamespace_name1{
// code declarations
namespacenamespace_name2{
//codedeclarations
}
}
//toaccessmembersofnamespace_name2
usingnamespacenamespace_name1::namespace_name2;
266
C++
//toaccessmembersofnamespace:name1
using namespace namespace_name1;
#include <iostream>
usingnamespacestd;
//Thiscallsfunctionfromsecondnamespace.
func();
return0;
}
Ifwecompileandrunabovecode,thiswouldproducethefollowingresult:
Insidesecond_space
267
C++
34. TEMPLATES
template<classtype>ret-typefunc-name(parameterlist)
{
//bodyoffunction
}
#include<iostream>
#include <string>
usingnamespacestd;
template<typenameT>
inlineTconst&Max(Tconst&a,Tconst&b)
{
returna<b?b:a;
}
intmain()
{
268
C++
inti=39;
intj= 20;
cout<<"Max(i,j):"<<Max(i,j)<< endl;
doublef1=13.5;
doublef2= 20.7;
cout<<"Max(f1,f2):"<<Max(f1,f2)<<endl;
strings1="Hello";
strings2="World";
cout<<"Max(s1,s2):"<<Max(s1,s2)<<endl;
return0;
}
Ifwecompileandrunabovecode,thiswouldproducethefollowingresult:
Max(i,j):39
Max(f1,f2):20.7
Max(s1,s2):World
ClassTemplate
Justaswecandefinefunctiontemplates,wecanalsodefineclasstemplates. The
general form of a generic class declaration is shown here:
template<classtype>classclass-name{
.
.
.
}
Here,typeis the placeholder type name, which will be specified when a class is
instantiated.Youcandefinemorethanonegenericdatatypebyusingacomma-
separated list.
Following is the example to define class Stack<> and implement generic
methods to push and pop the elements from the stack:
269
C++
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include<stdexcept>
usingnamespacestd;
template<classT>
class Stack {
private:
vector<T>elems; //elements
public:
void push(T const&);// push element
void pop(); //popelement
T top() const; // return top element
bool empty() const{ //returntrueifempty.
returnelems.empty();
}
};
template<classT>
voidStack<T>::push(Tconst&elem)
{
//appendcopyofpassedelement
elems.push_back(elem);
}
270
C++
}
//removelastelement
elems.pop_back();
}
template<classT>
TStack<T>::top()const
{
if(elems.empty()){
throwout_of_range("Stack<>::top():emptystack");
}
//returncopyoflastelement
return elems.back();
}
intmain()
{
try{
Stack<int> intStack;// stack of ints
Stack<string> stringStack; //stackofstrings
//manipulateintstack
intStack.push(7);
cout<<intStack.top()<<endl;
//manipulatestringstack
stringStack.push("hello");
cout<<stringStack.top()<<std::endl;
stringStack.pop();
stringStack.pop();
}
catch(exceptionconst&ex){
cerr<<"Exception:"<<ex.what()<<endl;
return -1;
271
C++
}
}
Ifwecompileandrunabovecode,thiswouldproducethefollowingresult:
7
hello
Exception:Stack<>::pop():emptystack
272
C++
35. PREPROCESSOR
The preprocessors are the directives, which give instructions to the compiler to
preprocess the information before actual compilation starts.
All preprocessor directives begin with #, and only white-space characters may
appear before a preprocessor directive on a line. Preprocessor directives are not
C++ statements, so they do not end in a semicolon (;).
You already have seen a#includedirective in all the examples. This macro is
used to include a header file into the source file.
There are number of preprocessor directives supported by C++ like #include,
#define, #if, #else, #line, etc. Let us see important directives:
The#definePreprocessor
#definemacro-namereplacement-text
When this line appears in a file, all subsequent occurrences of macro in that file
will be replaced by replacement-text before the program is compiled. For
example:
#include <iostream>
usingnamespacestd;
#definePI3.14159
intmain()
{
cout<<"ValueofPI:"<<PI<<endl;
return0;
}
Now,letusdothepreprocessingofthiscodetoseetheresultassumingwehave
thesourcecodefile.Soletuscompileitwith-Eoptionandredirecttheresultto
273
C++
$gcc-Etest.cpp> test.p
...
intmain()
{
cout<<"ValueofPI:"<<3.14159<< endl;
return0;
}
Function-LikeMacros
Youcanuse#definetodefineamacrowhichwilltakeargumentasfollows:
#include <iostream>
usingnamespacestd;
#defineMIN(a,b)(((a)<(b))?a:b)
intmain()
{
inti,j;
i= 100;
j= 30;
cout<<"Theminimumis"<<MIN(i,j)<<endl;
return0;
}
Ifwecompileandrunabovecode,thiswouldproducethefollowingresult:
Theminimumis 30
ConditionalCompilation
274
C++
There are several directives, which can be used to compile selective portions of
your program's source code. This process is called conditional compilation.
Theconditionalpreprocessorconstructismuchlikethe‘if’selectionstructure. Consider
the following preprocessor code:
#ifndef NULL
#defineNULL0
#endif
You can compile a program for debugging purpose. You can also turn on or offthe
debugging using a single macro as follows:
#ifdefDEBUG
cerr<<"Variablex="<<x<<endl; #endif
#if0
codepreventedfromcompiling
#endif
Letustrythefollowingexample:
#include <iostream>
usingnamespacestd;
#define DEBUG
#defineMIN(a,b)(((a)<(b))?a:b)
intmain()
{
inti,j;
i= 100;
j= 30;
#ifdefDEBUG
cerr<<"Trace:Insidemainfunction"<<endl;
#endif
275
C++
#if0
/*Thisiscommentedpart */
cout<<MKSTR(HELLOC++)<<endl;
#endif
cout<<"Theminimumis"<<MIN(i,j)<<endl;
#ifdefDEBUG
cerr<<"Trace:Comingoutofmainfunction"<<endl; #endif
return0;
}
Ifwecompileandrunabovecode,thiswouldproducethefollowingresult:
Trace:Insidemainfunction
The minimum is 30
Trace:Comingoutofmain function
The#and## Operators
#include <iostream>
usingnamespacestd;
#defineMKSTR(x)#x
intmain()
{
cout<<MKSTR(HELLOC++)<< endl;
return0;
276
C++
Ifwecompileandrunabovecode,thiswouldproducethefollowingresult:
HELLO C++
Let us see how it worked. It is simple to understand that the C++ preprocessor
turns the line:
cout<<MKSTR(HELLOC++)<<endl;
Abovelinewillbeturnedintothefollowingline:
cout<<"HELLOC++"<<endl;
The##operatorisusedtoconcatenatetwotokens.Hereisanexample:
#defineCONCAT(x,y)x##y
When CONCAT appears in the program, its arguments are concatenated and
used to replace the macro. For example, CONCAT(HELLO, C++) is replaced by
"HELLO C++" in the program as follows.
#include <iostream>
usingnamespacestd;
#defineconcat(a,b)a##b
int main()
{
intxy=100;
cout<<concat(x,y);
return 0;
}
Ifwecompileandrunabovecode,thiswouldproducethefollowingresult:
100
Let us see how it worked. It is simple to understand that the C++ preprocessor
transforms:
cout<<concat(x,y);
277
C++
Abovelinewillbetransformedintothefollowingline:
cout<<xy;
PredefinedC++Macros
C++providesanumberofpredefinedmacrosmentionedbelow:
Macro Description
DATE Thiscontainsastringoftheformmonth/day/yearthat is
the date of the translation of the source file into object
code.
Letusseeanexampleforalltheabovemacros:
#include <iostream>
usingnamespacestd;
intmain()
{
cout <<"ValueofLINE:"<<LINE<<endl; cout
<<"ValueofFILE:"<<FILE<<endl; cout
<<"ValueofDATE:"<<DATE<<endl; cout
<<"ValueofTIME:"<<TIME<<endl;
return0;
}
Ifwecompileandrunabovecode,thiswouldproducethefollowingresult:
278
C++
ValueofLINE:6
Value of FILE: test.cpp
Value of DATE: Feb 28 2011
Value of TIME: 18:52:48
279
C++
36. SIGNALHANDLING
Signals are the interrupts delivered to a process by the operating system which
can terminate a program prematurely. You can generate interrupts by pressing
Ctrl+C on a UNIX, LINUX, Mac OS X or Windows system.
There are signals which cannot be caught by the program but there is afollowing
list of signals which you can catch in your program and can take appropriate
actions based on the signal. These signals are defined in C++header file
<csignal>.
Signal Description
SIGABRT Abnormalterminationoftheprogram,suchasacalltoabort.
SIGILL Detectionofanillegalinstruction.
SIGINT Receiptofaninteractiveattentionsignal.
Thesignal()Function
C++ signal-handling library provides functionsignalto trap unexpected events.
Following is the syntax of the signal() function:
void(*signal(intsig,void(*func)(int)))(int);
#include<iostream>
280
C++
#include<csignal>
usingnamespacestd;
voidsignalHandler(intsignum)
{
cout<<"Interruptsignal("<<signum<<")received.\n";
//cleanupandcloseupstuff here
//terminateprogram
exit(signum);
intmain()
{
//registersignalSIGINTandsignalhandler
signal(SIGINT, signalHandler);
while(1){
cout<<"Goingtosleep...."<<endl;
sleep(1);
}
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Goingtosleep....
Goingtosleep....
Goingtosleep....
Now, press Ctrl+C to interrupt the program and you will see that your program
will catch the signal and would come out by printing something as follows:
281
C++
Goingtosleep....
Goingtosleep....
Goingtosleep....
Interruptsignal(2)received.
Theraise()Function
Youcangeneratesignalsbyfunctionraise(),whichtakesanintegersignal number as
an argument and has the following syntax.
intraise(signal sig);
Here,sigis the signal number to send any of the signals: SIGINT, SIGABRT,
SIGFPE, SIGILL, SIGSEGV, SIGTERM, SIGHUP. Following is the example where we
raise a signal internally using raise() function as follows:
#include<iostream>
#include <csignal>
usingnamespacestd;
voidsignalHandler(intsignum)
{
cout<<"Interruptsignal("<<signum<<")received.\n";
//cleanupandcloseupstuff here
//terminateprogram
exit(signum);
intmain()
{
inti= 0;
//registersignalSIGINTandsignalhandler
signal(SIGINT, signalHandler);
282
C++
while(++i){
cout<<"Goingtosleep...."<<endl;
if( i == 3 ){
raise(SIGINT);
}
sleep(1);
}
return0;
}
When the above code is compiled and executed, it produces the following result
and would come out automatically:
Goingtosleep....
Goingtosleep....
Goingtosleep....
Interruptsignal(2)received.
283
C++
37. MULTITHREADING
#include<pthread.h>
pthread_create(thread,attr,start_routine,arg)
Parameter Description
284
C++
#include <pthread.h>
pthread_exit(status)
Example:
This simple example code creates 5 threads with the pthread_create() routine.
Each thread prints a "Hello World!" message, and then terminates with a call to
pthread_exit().
#include<iostream>
#include <cstdlib> #include<pthread.h>
usingnamespacestd;
#defineNUM_THREADS 5
void*PrintHello(void*threadid)
{
long tid;
tid= (long)threadid;
cout<<"HelloWorld!ThreadID,"<<tid<< endl;
285
C++
pthread_exit(NULL);
}
intmain()
{
pthread_tthreads[NUM_THREADS
]; int rc;
int i;
for(i=0;i<NUM_THREADS;i++){
cout<<"main():creatingthread,"<<i<<endl; rc =
pthread_create(&threads[i], NULL,
PrintHello,(void*)i);
if(rc){
cout<<"Error:unabletocreatethread,"<<rc<<endl;
exit(-1);
}
}
pthread_exit(NULL);
}
Compilethefollowingprogramusing-lpthreadlibraryasfollows:
$gcctest.cpp-lpthread
Now,executeyourprogramwhichgivesthefollowingoutput:
286
C++
PassingArgumentstoThreads
This example shows how to pass multiple arguments via a structure. You can
pass any data type in a thread callback because it points to void as explained in
the following example:
#include <iostream>
#include <cstdlib>
#include<pthread.h>
usingnamespacestd;
#defineNUM_THREADS 5
structthread_data{
intthread_id;
char *message;
};
void*PrintHello(void*threadarg)
{
structthread_data*my_data;
my_data=(structthread_data*)threadarg;
pthread_exit(NULL);
}
intmain()
{
pthread_t threads[NUM_THREADS];
structthread_datatd[NUM_THREADS]
; int rc;
287
C++
int i;
for(i=0;i<NUM_THREADS;i++){
cout<<"main():creatingthread,"<<i<<endl;
td[i].thread_id = i;
td[i].message="Thisismessage";
rc=pthread_create(&threads[i],NULL,
PrintHello,(void*)&td[i]);
if(rc){
cout<<"Error:unabletocreatethread,"<<rc<<endl;
exit(-1);
}
}
pthread_exit(NULL);
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
main():creatingthread,0
main():creatingthread,1
main():creatingthread,2
main():creatingthread,3
main():creatingthread,4
ThreadID:3Message:Thisismessage
ThreadID:2Message:Thisismessage
ThreadID:0Message:Thisismessage
ThreadID:1Message:Thisismessage
ThreadID:4Message:Thisis message
JoiningandDetachingThreads
Therearefollowingtworoutineswhichwecanusetojoinordetachthreads:
pthread_join(threadid,status)
pthread_detach (threadid)
288
C++
The pthread_join() subroutine blocks the calling thread until the specified
‘threadid’ thread terminates. When a thread is created, one of its attributes
defines whether it is joinable or detached. Only threads that are created as
joinable canbe joined.Ifathread iscreatedasdetached, itcan neverbe joined.
This example demonstrates how to wait for thread completions by using the
Pthread join routine.
#include<iostream>
#include<cstdlib>
#include<pthread.h> #include <unistd.h>
usingnamespacestd;
#defineNUM_THREADS 5
void*wait(void*t)
{
int i; longtid;
tid= (long)t;
sleep(1);
cout<<"Sleepinginthread"<<endl;
cout<<"Threadwithid:"<<tid<<"...exiting"<<endl; pthread_exit(NULL);
intmain()
{
intrc; int i;
pthread_tthreads[NUM_THREADS]; pthread_attr_t attr;
void*status;
289
C++
//Initializeandsetthreadjoinable
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);
for(i=0;i<NUM_THREADS;i++){
cout<<"main():creatingthread,"<<i<<endl;
rc=pthread_create(&threads[i],NULL,wait,(void*)i);
if (rc){
cout<<"Error:unabletocreatethread,"<<rc<<endl;
exit(-1);
}
}
//freeattributeandwaitforthe otherthreads
pthread_attr_destroy(&attr);
for(i=0;i<NUM_THREADS;i++){
rc=pthread_join(threads[i],&status);
if (rc){
cout<<"Error:unabletojoin,"<<rc<<endl;
exit(-1);
}
cout<<"Main:completedthreadid:"<<i;
cout<<"exitingwithstatus:"<<status<< endl;
}
cout<<"Main:programexiting."<<endl;
pthread_exit(NULL);
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
main():creatingthread,0
main():creatingthread,1
main():creatingthread,2
290
C++
main():creatingthread,3
main():creatingthread,4
Sleeping in thread
Threadwithid:0exiting
Sleepinginthread
Threadwithid:1.......exiting
Sleepinginthread
Threadwithid:2.......exiting
Sleepinginthread
Threadwithid:3.......exiting
Sleepinginthread
Threadwithid:4.......exiting
Main:completedthreadid:0exitingwithstatus0
Main:completedthreadid:1exitingwithstatus0
Main:completedthreadid:2exitingwithstatus0
Main:completedthreadid:3exitingwithstatus0
Main:completedthreadid:4exitingwithstatus0
Main:programexiting.
291
C++
38.WEBPROGRAMMING
WhatisCGI?
TheCommonGatewayInterface,orCGI,isasetofstandardsthatdefinehow information
is exchanged between the web server and a custom script.
TheCGIspecsarecurrentlymaintainedby theNCSAandNCSAdefinesCGIisas follows:
TheCommonGatewayInterface,orCGI,isastandardforexternalgateway programs to
interface with information servers such as HTTP servers.
ThecurrentversionisCGI/1.1andCGI/1.2isunderprogress. Web
Browsing
TounderstandtheconceptofCGI,let'sseewhathappenswhenweclicka hyperlink to
browse a particular web page or URL.
Your browser contacts the HTTP web server and demand for the URL i.e.
filename.
WebServerwillparse the URLand willlook forthe filename. If it finds the
requested file then web server sends that file back to the browser
otherwise sends an error message indicating that you have requested a
wrong file.
Web browser takes response from web server and displays either the
received file or error message based on the received response.
However, it is possible to set up the HTTP server in such a way that whenever a
file in a certain directory is requested, that file is not sent back; instead it is
executed as a program, and produced output from the program is sent back to
your browser to display.
The Common Gateway Interface (CGI) is a standard protocol for enabling
applications (called CGI programs or CGI scripts) to interact with Web servers
and with clients. These CGI programs can be a written in Python, PERL, Shell, C
or C++ etc.
CGIArchitectureDiagram
ThefollowingsimpleprogramshowsasimplearchitectureofCGI:
292
C++
WebServerConfiguration
Before you proceed with CGI Programming, make sure that your Web Server
supports CGI and it is configured to handle CGI Programs. All the CGI Programs to
be executed by the HTTP server are kept in a pre-configured directory. This
directory is called CGI directory and by convention it is named as /var/www/cgi-
bin. By convention CGI files will have extension as.cgi, though they are C++
executable.
Bydefault,ApacheWebServerisconfiguredtorunCGIprogramsin
/var/www/cgi-bin. If you want to specify any other directory to run your CGI
scripts, you can modify the following section in the httpd.conf file:
<Directory"/var/www/cgi-bin">
AllowOverride None
Options ExecCGI
Orderallow,deny
Allow from all
</Directory>
293
C++
<Directory"/var/www/cgi-bin">
Options All
</Directory>
Here, I assume that you have Web Server up and running successfully and you
are able to run any other CGI program like Perl or Shell etc.
FirstCGIProgram
ConsiderthefollowingC++Programcontent:
#include<iostream>
usingnamespacestd;
intmain()
{
return0;
}
Compile above code and name the executable as cplusplus.cgi. This file is being
kept in /var/www/cgi-bin directory and it has following content. Before running
your CGI program make sure you have change mode of file usingchmod 755
cplusplus.cgiUNIXcommandtomakefileexecutable.Nowifyou
clickcplusplus.cgithen this produces the following output:
MyFirstCGI program
The above C++ program is a simple program which is writing its output on
STDOUTfile i.e.screen.Thereisoneimportantandextrafeatureavailablewhich is first
lineprintingContent-type:text/html\r\n\r\n.This lineis sentback to
thebrowserandspecifythecontenttypetobedisplayedonthebrowserscreen.
294
C++
Now you must have understood the basic concept of CGI and you can writemany
complicated CGI programs using Python. A C++ CGI program can interact with
any other external system, such as RDBMS, to exchange information.
HTTPHeader
HTTPFieldName:Field Content
ForExample
Content-type:text/html\r\n\r\n
Header Description
Set-Cookie:String Setthecookiepassedthroughthestring.
CGIEnvironmentVariables
AlltheCGIprogramwillhaveaccesstothefollowingenvironmentvariables. These
variables play an important role while writing any CGI program.
295
C++
VariableName Description
CONTENT_TYPE The data type of the content, used when the client is
sending attached content to the server. For example
file upload etc.
PATH_INFO ThepathfortheCGIscript.
SCRIPT_FILENAME ThefullpathtotheCGIscript.
SCRIPT_NAME ThenameoftheCGIscript.
SERVER_NAME Theserver'shostnameorIPAddress.
296
C++
HereissmallCGIprogramto listoutalltheCGIvariables.
#include
<iostream>
#include
<stdlib.h>
usingnamespacestd;
conststringENV[24]={
"COMSPEC", "DOCUMENT_ROOT", "GATEWAY_INTERFACE",
"HTTP_ACCEPT", "HTTP_ACCEPT_ENCODING",
"HTTP_ACCEPT_LANGUAGE", "HTTP_CONNECTION",
"HTTP_HOST", "HTTP_USER_AGENT", "PATH",
"QUERY_STRING", "REMOTE_ADDR", "REMOTE_PORT",
"REQUEST_METHOD","REQUEST_URI","SCRIPT_FILENAME",
"SCRIPT_NAME", "SERVER_ADDR", "SERVER_ADMIN",
"SERVER_NAME","SERVER_PORT","SERVER_PROTOCOL",
"SERVER_SIGNATURE","SERVER_SOFTWARE" };
intmain()
{
for(inti=0;i<24;i++)
{
cout<<"<tr><td>"<<ENV[i]<<"</td><td>";
297
C++
//attempttoretrievevalueofenvironmentvariable
char *value = getenv( ENV[ i ].c_str() );
298
C++
if(value!=0){ cout
<< value;
}else{
cout<<"Environmentvariabledoesnotexist.";
}
cout<<"</td></tr>\n";
}
cout<<"</table><\n";
cout <<"</body>\n";
cout <<"</html>\n";
return0;
}
Theoutputisas follows:
COMSPEC Environmentvariabledoesnotexist.
/var/www/tutorialspoint
DOCUMENT_ROOT GATEWAY_INTERFACE CGI/1.1
HTTP_ACCEPT HTTP_ACCEPT_ENCODING HTTP_ACCEPT_LAN
text/html,application/xhtml+xml,*/* gzip, deflate
en-US
PATH QUERY_STRING REMOTE_ADDR REMOTE_PORT REQUEST_METHOD REQUEST_URI SCRIPT_FILE
SERVER_ADDR Keep-Alive
Mozilla/5.0(WindowsNT6.3;WOW64;Trident/7.0; rv:11.0) like
/sbin:/usr/sbin:/bin:/usr/bin
183.82.104.71
50902
GET
/cgi-bin/cpp_env.cgi
/var/www/cgi-bin/cpp_env.cgi
/cgi-bin/cpp_env.cgi 66.135.33.172
299
C++
SERVER_ADMIN
80 SERVER_PROTOCOL SERVER_SIGNATURE SERVER_SOFTWARE
SERVER_NAME SERVER_PORT
< HTTP/1.1
Apache
C++CGILibrary
For realexamples, you would need to do manyoperations by your CGI program.
There is a CGI library written for C++ program which you can download from
ftp://ftp.gnu.org/gnu/cgicc/ and follow the steps to install the library:
$tarxzfcgicc-X.X.X.tar.gz
$cdcgicc-X.X.X/
$./configure--prefix=/usr
$make
$makeinstall
The GET method sends the encoded user information appended to the page
request. The page and the encoded information are separated by the ‘?’
character as follows:
http://www.test.com/cgi-bin/cpp.cgi?key1=value1&key2=value2
The GET method is the default method to pass information from browser to web
serveranditproducesa longstringthatappearsinyour browser'sLocation:box. Never
use the GET method if you have password or other sensitive information to pass
to the server. The GET method has size limitation and you can pass upto 1024
characters in a request string.
When using GET method, information is passed using QUERY_STRING http
header and will be accessible in your CGI Program through QUERY_STRING
environment variable.
300
C++
You can pass information by simply concatenating key and value pairs alongwith
any URL or you can use HTML <FORM> tags to pass information using GET
method.
SimpleURLExample:GetMethod
Here is a simple URL which will pass two values to hello_get.py program using
GET method.
/cgi-bin/cpp_get.cgi?first_name=ZARA&last_name=ALI
#include<iostream>
#include <vector> #include <string> #include<stdio.h>
#include<stdlib.h>
#include<cgicc/CgiDefs.h>
#include<cgicc/Cgicc.h> #include<cgicc/HTTPHTMLHeader.h>
#include<cgicc/HTMLClasses.h>
usingnamespacestd;
usingnamespacecgicc;
intmain()
{
CgiccformData;
301
C++
form_iteratorfi=formData.getElement("first_name");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout<<"Firstname:"<<**fi<<endl;
}else{
cout<<"Notextenteredforfirstname"<<endl;
}
cout<<"<br/>\n";
fi=formData.getElement("last_name");
if(!fi->isEmpty()&&fi!=(*formData).end())
{ cout <<"Last name: "<< **fi << endl;
}else{
cout<<"Notextenteredforlastname"<<endl;
}
cout<<"<br/>\n";
cout<<"</body>\n";
cout<<"</html>\n";
return0;
}
Now,compiletheaboveprogramasfollows:
$g++-ocpp_get.cgicpp_get.cpp-lcgicc
Generatecpp_get.cgiandputitinyourCGIdirectoryandtrytoaccessusing following
link:
/cgi-bin/cpp_get.cgi?first_name=ZARA&last_name=ALI
This would generate following result:
Firstname:ZARA
Last name: ALI
SimpleFORMExample:GETMethod
Here is a simple example which passes two values usingHTML FORM andsubmit
button. We are going to use same CGI script cpp_get.cgi to handle this input.
<formaction="/cgi-bin/cpp_get.cgi"method="get">
302
C++
FirstName:<inputtype="text"name="first_name"><br/>
LastName:<inputtype="text"name="last_name" />
<inputtype="submit"value="Submit"/>
</form>
Here is the actual output of the above form. You enter First and Last Name and
then click submit button to see the result.
FirstName:
Submit
Last Name:
PassingInformationUsingPOSTMethod
The same cpp_get.cgi program will handle POST method as well. Let us take
same example as above, which passes two values using HTML FORM and submit
button but this time with POST method as follows:
<inputtype="submit"value="Submit"/>
</form>
Here is the actual output of the above form. You enter First and Last Name and
then click submit button to see the result.
FirstName:
Submit
Last Name:
PassingCheckboxDatatoCGIProgram
Checkboxesareusedwhenmorethanoneoptionisrequiredtobe selected.
303
C++
HereisexampleHTMLcodeforaformwithtwocheckboxes:
<formaction="/cgi-bin/
cpp_checkbox.cgi"method="POST"
target="_blank">
<inputtype="checkbox"name="maths"value="on"/>Maths
<inputtype="checkbox"name="physics"value="on"/>Physics
<inputtype="submit"value="SelectSubject"/>
</form>
Theresultofthiscodeisthefollowing form:
SelectSubject
Maths Physics
BelowisC++program,whichwillgeneratecpp_checkbox.cgiscripttohandle input
given by web browser through checkbox button.
#include<iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include<stdlib.h>
#include <cgicc/CgiDefs.h>
#include<cgicc/Cgicc.h>#includ
e<cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
intmain()
{
CgiccformData;
boolmaths_flag,physics_flag;
cout<<"Content-type:text/html\r\n\r\n";
cout <<"<html>\n";
304
C++
maths_flag=formData.queryCheckbox("maths");
if(maths_flag){
cout<<"MathsFlag:ON"<<endl;
}else{
cout<<"MathsFlag:OFF"<<endl;
}
cout<<"<br/>\n";
physics_flag=formData.queryCheckbox("physics");
if(physics_flag){
cout<<"PhysicsFlag:ON"<<endl;
}else{
cout<<"PhysicsFlag:OFF"<<endl;
}
cout <<"<br/>\n"; cout<<"</body>\n"; cout<<"</html>\n";
return0;
}
PassingRadioButtonDatatoCGIProgram
RadioButtonsareusedwhenonlyoneoptionisrequiredtobeselected. Here is
example HTML code for a form with two radio button:
<formaction="/cgi-bin/
cpp_radiobutton.cgi"method="post"
target="_blank">
<inputtype="radio"name="subject"value="maths"
checked="checked"/>Maths
305
C++
<inputtype="radio"name="subject"value="physics"/>Physics
<inputtype="submit"value="SelectSubject"/>
</form>
Theresultofthiscodeisthefollowing form:
SelectSubject
Maths Physics
#include<iostream>
#include <vector> #include <string> #include <stdio.h> #include<stdlib.h>
#include<cgicc/CgiDefs.h>
#include<cgicc/Cgicc.h> #include<cgicc/HTTPHTMLHeader.h> #include <cgicc/HTMLC
usingnamespacestd;
usingnamespacecgicc;
intmain()
{
CgiccformData;
form_iteratorfi=formData.getElement("subject");
306
C++
cout <<"<br/>\n";
cout<<"</body>\n";
cout<<"</html>\n";
return0;
}
PassingTextAreaDatatoCGI Program
TEXTAREAelementisusedwhenmultilinetexthastobepassedtotheCGI Program.
HereisexampleHTMLcodeforaformwithaTEXTAREAbox:
<formaction="/cgi-bin/
cpp_textarea.cgi"method="post"
target="_blank">
<textareaname="textcontent"cols="40"rows="4"
> Type your text here...
</textarea>
<inputtype="submit"value="Submit"/>
</form>
Theresultofthiscodeisthefollowing form:
Submit
BelowisC++program,whichwillgeneratecpp_textarea.cgiscripttohandle input
given by web browser through text area.
#include<iostream>
#include <vector>
#include <string>
#include <stdio.h>
307
C++
#include<stdlib.h>
#include<cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include<cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
intmain()
{
CgiccformData;
form_iteratorfi=formData.getElement("textcontent");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout<<"TextContent:"<<**fi<<endl;
}else{
cout<<"Notextentered"<<endl;
}
cout <<"<br/>\n";
cout<<"</body>\n";
cout<<"</html>\n";
return0;
}
308
C++
PassingDropdownBoxDatatoCGIProgram
DropdownBoxisusedwhenwehavemanyoptionsavailablebutonlyoneortwo will be
selected.
HereisexampleHTMLcodeforaformwithonedropdownbox:
<formaction="/cgi-bin/cpp_dropdown.cgi"
method="post"target="_blank">
<selectname="dropdown">
<optionvalue="Maths"selected>Maths</option>
<optionvalue="Physics">Physics</option>
</select>
<inputtype="submit"value="Submit"/>
</form>
Theresultofthiscodeisthefollowing form:
Maths Submit
#include<iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include<stdlib.h>
#include<cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include<cgicc/
HTTPHTMLHeader.h> #include
<cgicc/HTMLClasses.h>
intmain()
{
CgiccformData; 309
C++
form_iteratorfi=formData.getElement("dropdown");
if(!fi->isEmpty()&&fi!=(*formData).end()){ cout <<"Value Selected: "<< **fi
}
cout<<"<br/>\n";
cout<<"</body>\n"; cout<<"</html>\n";
return0;
}
UsingCookiesin CGI
310
C++
Domain:Thisisthedomainnameofyoursite.
Path: This is the path to the directory or web page that sets the cookie.
This may be blank if you want to retrieve the cookie from any directory or
page.
Secure:If this field contains the word "secure" then the cookie may only
be retrieved with a secure server. If this field is blank, no such restriction
exists.
Name=Value:Cookies are set and retrieved in the form of key and value
pairs.
SettingupCookies
It is very easy to send cookies to browser. These cookies will be sent along with
HTTP Header before the Content-type filed. Assuming you want to set UserID and
Password as cookies. So cookies setting will be done as follows:
#include<iostream>
usingnamespacestd;
intmain()
{
cout <<"Set-Cookie:UserID=XYZ;\r\n";
cout <<"Set-Cookie:Password=XYZ123;\r\n";
cout <<"Set-Cookie:Domain=www.tutorialspoint.com;\r\
n";
cout <<"Set-Cookie:Path=/perl;\n";
cout <<"Content-type:text/html\r\n\r\n";
cout <<"<html>\n";
cout <<"<head>\n";
cout <<"<title>CookiesinCGI</title>\n";
cout <<"</head>\n";
cout <<"<body>\n";
cout <<"Settingcookies"<<endl;
cout <<"<br/>\n";
cout <<"</body>\n";
311
C++
cout<<"</html>\n";
return0;
}
From this example, you must have understood how to set cookies. We useSet-
Cookie HTTP header to set cookies.
Here, it is optional to set cookies attributes like Expires, Domain, and Path. It is
notable that cookies are set before sending magic line"Content-
type:text/html\r\n\r\n.
Compile above program to produce setcookies.cgi, and try to set cookies
usingfollowing link. It will set four cookies at your computer:
/cgi-bin/setcookies.cgi
Retrieving Cookies
It is easy to retrieve all the set cookies. Cookies are stored in CGI environment
variable HTTP_COOKIE and they will have following form.
key1=value1;key2=value2;key3=value3....
Hereisanexampleofhowtoretrievecookies.
#include<iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include<stdlib.h>
#include <cgicc/CgiDefs.h>
#include<cgicc/Cgicc.h>#includ
e<cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
intmain()
{
312
C++
Cgicc cgi;
const_cookie_iteratorcci;
//getenvironmentvariables
constCgiEnvironment&env=cgi.getEnvironment();
for(cci=env.getCookieList().begin();
cci !=
env.getCookieList().end();
++cci)
{
cout<<"<tr><td>"<<cci->getName()<<"</td><td>";
cout << cci->getValue();
cout<<"</td></tr>\n";
}
cout<<"</table><\n";
cout <<"<br/>\n";
cout<<"</body>\n";
cout<<"</html>\n";
return0;
}
Now, compile above program to produce getcookies.cgi, and try to get a list ofall
the cookies available at your computer:
/cgi-bin/getcookies.cgi
313
C++
UserID XYZ
PasswordXYZ123
Domainwww.tutorialspoint.com
Path /perl
FileUploadExample
TouploadafiletheHTMLformmusthavetheenctypeattributeset tomultipart/form-
data. The input tag with the file type will create a "Browse"button.
<html>
<body>
<form enctype="multipart/form-
data"action="/cgi-bin/cpp_uploadf
ile.cgi" method="post">
<p>File:<inputtype="file"name="userfile"/></p>
<p><inputtype="submit"value="Upload"/></p>
</form>
</body>
</html>
Theresultofthiscodeisthefollowingform: File:
Upload
#include<iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include<stdlib.h>
314
C++
#include <cgicc/CgiDefs.h>
#include<cgicc/Cgicc.h>#includ
e<cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
intmain()
{
Cgicccgi;
return0;
}
315
C++
The above example is for writing content atcoutstream but you can open your
file stream and save the content of uploaded file in a file at desired location.
Hopeyouhaveenjoyedthistutorial.Ifyes,pleasesendusyourfeedback.
316
C++
39. STLTUTORIAL
Hope you have already understood the concept of C++ Template which we have
discussed earlier. The C++ STL (Standard Template Library) is a powerful set of
C++ template classes to provide general-purpose classes and functions with
templates that implement many popular and commonly used algorithms and
data structures like vectors, lists, queues, and stacks.
At the core of the C++ Standard Template Library are following three well-
structured components:
Component Description
We will discuss about all the three C++ STL components in next chapter while
discussing C++ Standard Library. For now, keep in mind that all the three
components have a rich set of pre-defined functions which help us in doing
complicated tasks in very easy fashion.
Let us take the following program that demonstrates the vector container (a C+
+ Standard Template) which is similar to an array with an exception that it
automatically handles its own storage requirements in case it grows:
#include <iostream>
#include <vector>
usingnamespacestd;
intmain()
{
317
C++
//createavectortostoreint
vector<int> vec;
int i;
//displaytheoriginalsizeofvec
cout<<"vectorsize="<<vec.size()<<endl;
//push5valuesintothevector for(i
= 0; i < 5; i++){
vec.push_back(i);
}
//displayextendedsizeof vec
cout<<"extendedvectorsize="<<vec.size()<<endl;
//access5valuesfromthevector
for(i = 0; i < 5; i++){
cout<<"valueofvec["<<i<<"]="<<vec[i]<<endl;
}
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
vectorsize=0
extendedvectorsize=5
value of vec [0] = 0
318
C++
Here are following points to be noted related to various functions we used in the
above example:
The push_back( ) member function inserts value at the end of the vector,
expanding its size as needed.
Thesize()functiondisplaysthesizeofthevector.
Thefunctionbegin()returnsaniteratortothestartofthe vector.
Thefunctionend()returnsaniteratortotheendofthevector.
319
C++
40. STANDARDLIBRARY
TheC++StandardLibrarycanbecategorizedintotwoparts:
320
C++
TheLocalization library
ExceptionHandlingClasses
MiscellaneousSupportLibrary
321