Bilal Ahmed Shaik CPP
Bilal Ahmed Shaik CPP
Bilal Ahmed Shaik CPP
1. OVERVIEW
C++
Object-Oriented Programming
C++ fully supports object-oriented programming, including the four pillars of
object-oriented development:
Encapsulation
Data hiding
Inheritance
Polymorphism
Standard Libraries
Standard C++ consists of three important parts:
The core language giving all the building blocks including variables, data
types and literals, etc.
The C++ Standard Library giving a rich set of functions manipulating files,
strings, etc.
C++
The ANSI standard has been stable for a while, and all the major C++ compiler
manufacturers support the ANSI standard.
Learning C++
The most important thing while learning C++ is to focus on concepts.
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.
Use of C++
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++.
2. ENVIORNMENT SETUP
C++
int main()
{
cout << "Hello World";
return 0;
}
For most of the examples given in this tutorial, you will find Try it option 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.
Text Editor:
This will be used to type your program. Examples of few editors include Windows
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.
3
C++
C++ Compiler:
This is an actual C++ compiler, which will be used to compile your source code
into final executable program.
Most C++ compilers don't care what extension you give to your source code, 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.
Mac OS X Installation:
If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode
development environment from Apple's website and follow the simple installation
instructions.
Xcode is currently available at developer.apple.com/technologies/tools/.
Windows Installation:
To install GCC at Windows you need to install MinGW. To install MinGW, go to
the 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.
4
C++
3. BASIC SYNTAX
C++
Object - Objects have states and behaviors. Example: A dog has states color, name, breed as well as behaviors - wagging, barking, and eating.
An object is an instance of a class.
Instant Variables - Each object has its unique set of instant variables.
An object's state is created by the values assigned to these instant
variables.
int main()
{
cout << "Hello World"; // prints Hello World
return 0;
}
Let us look at the various parts of the above program:
1. The C++ language defines several headers, which contain information
that is either necessary or useful to your program. For this program, the
header <iostream> is needed.
2. The line using namespace std; tells the compiler to use the std
namespace. Namespaces are a relatively recent addition to C++.
6
C++
C++
y = y+1;
add(x, y);
A block is a set of logically connected statements that are surrounded by
opening and closing braces. For example:
{
cout << "Hello World"; // prints Hello World
return 0;
}
C++ does not recognize the end of the line as 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);
is the same as
x = y; y = y+1; add(x, y);
C++ Identifiers
A C++ identifier is a name used to identify a variable, function, class, module, or
any other user-defined item. An identifier starts with a letter A to Z or a to z or
an underscore (_) followed by zero or more letters, underscores, and digits (0 to
9).
C++ does not allow punctuation characters such as @, $, and % within
identifiers.
C++
is
a
case-sensitive
programming
language.
Thus, Manpower and manpower are two different identifiers in C++.
Here are some examples of acceptable identifiers:
mohd
zara
abc
move_name
a_123
myname50
_temp
a23b9
retVal
C++ Keywords
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.
asm
else
new
this
8
C++
auto
enum
operator
throw
bool
explicit
private
true
break
export
protected
try
case
extern
public
typedef
catch
false
register
typeid
char
float
reinterpret_cast
typename
class
for
return
union
const
friend
short
unsigned
const_cast
goto
signed
using
continue
if
sizeof
virtual
default
inline
static
void
delete
int
static_cast
volatile
do
long
struct
wchar_t
double
mutable
switch
while
dynamic_cast
namespace
template
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.
Following are most frequently used trigraph sequences:
9
C++
Trigraph
Replacement
??=
??/
??'
??(
??)
??!
??<
??>
??-
All the compilers do not support trigraphs and they are not advised to be used
because of their confusing nature.
Whitespace in C++
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:
int age;
In the above statement there must be at least one whitespace character (usually
a space) between int and age for the compiler to be able to distinguish them.
Statement 2:
fruit = apples + oranges;
10
C++
11
4. COMMENTS IN C++
C++
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 available
inside any comment are ignored by C++ compiler.
C++ comments start with /* and end with */. For example:
/* This is a comment */
main()
{
cout << "Hello World"; // prints Hello World
return 0;
}
When the above code is compiled, it will ignore // prints Hello World and final
executable will produce the following result:
Hello World
Within a /* and */ comment, // characters have no special meaning. Within a //
comment, /* and */ have no special meaning. Thus, you can "nest" one kind of
comment within the other kind. For example:
/* Comment out printing of Hello World:
12
C++
*/
13
5. DATA TYPES
C++
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.
Keyword
Boolean
bool
Character
char
Integer
int
Floating point
float
double
Valueless
void
Wide character
wchar_t
Several of the basic types can be modified using one or more of these type
modifiers:
signed
unsigned
short
14
C++
long
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.
Type
Typical Range
char
1byte
unsigned char
1byte
0 to 255
signed char
1byte
-127 to 127
int
4bytes
-2147483648 to 2147483647
unsigned int
4bytes
0 to 4294967295
signed int
4bytes
-2147483648 to 2147483647
short int
2bytes
-32768 to 32767
Range
0 to 65,535
Range
-32768 to 32767
long int
4bytes
-2,147,483,647 to 2,147,483,647
4bytes
4bytes
0 to 4,294,967,295
float
4bytes
double
8bytes
long double
8bytes
wchar_t
2 or 4 bytes
1 wide character
15
C++
The size of variables might be different from those shown in the above table,
depending on the compiler and the computer you are using.
Following is the example, which will produce correct size of various data types
on your computer.
#include <iostream>
using namespace std;
int main()
{
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << 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 << "Size of wchar_t : " << sizeof(wchar_t) << endl;
return 0;
}
This example uses endl, which inserts a new-line character after every line and
<< operator is being used to pass multiple values out to the screen. We are also
using sizeof() 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:
Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 4
Size of float : 4
Size of double : 8
Size of wchar_t : 4
typedef Declarations
You can create a new name for an existing type using typedef. Following is the
simple syntax to define a new type using typedef:
16
C++
Enumerated Types
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 keyword enum. The general
form of an enumeration type is:
enum enum-name { list of names } var-list;
Here, the enum-name is the enumeration's type name. The list of names is
comma separated.
For example, the following code defines an enumeration of colors called colors
and the variable c of type color. Finally, c is assigned the value "blue".
enum color { 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
value
by
adding
an
initializer.
For
example,
in
the
following
enumeration, green will have the value 5.
enum color { red, green=5, blue };
Here, blue will have a value of 6 because each name will be one greater than
the one that precedes it.
17
6. VARIABLE TYPES
C++
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 layout
of 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:
There are following basic types of variable in C++ as explained in last chapter:
Type
Description
bool
char
int
float
double
void
wchar_t
C++ also allows to define various other types of variables, which we will cover in
subsequent chapters like Enumeration, Pointer, Array, Reference, Data
structures, and Classes.
Following section will cover how to define, declare and use various types of
variables.
18
C++
i, j, k;
char
c, ch;
float
f, salary;
double d;
The line int i, j, k; both declares and defines the variables i, j and k; which
instructs the compiler to create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The
initializer consists of an equal sign followed by a constant expression as follows:
type variable_name = value;
Some examples are:
extern int d = 3, f = 5;
// declaration of d and f.
int d = 3, f = 5;
byte z = 22;
char x = '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.
C++
the program. You will use extern keyword 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:
Try the following example where a variable has been declared at the top, but it
has been defined inside the main function:
#include <iostream>
using namespace std;
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main ()
{
// Variable definition:
int a, b;
int c;
float f;
// actual initialization
a = 10;
b = 20;
c = a + b;
f = 70.0/3.0;
cout << f << endl ;
return 0;
}
20
C++
When the above code is compiled and executed, it produces the following result:
30
23.3333
Same concept applies on function declaration where you provide a function
name at the time of its declaration and its actual definition can be given
anywhere else. For example:
// function declaration
int func();
int main()
{
// function call
int i = func();
}
// function definition
int func()
{
return 0;
}
rvalue : The term rvalue refers to a data value that is stored at some
address in memory. An rvalue is an expression that cannot have a value
assigned to it which means an rvalue may appear on the right- but not
left-hand side of an assignment.
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:
int g = 20;
21
C++
But the following is not a valid statement and would generate compile-time
error:
10 = 20;
22
7. VARIABLE SCOPE
C++
A scope is a region of the program and broadly speaking there are three places,
where variables can be declared:
We will learn what a function is, and it's parameter in subsequent chapters. Here
let us explain what local and global variables are.
Local Variables
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>
using namespace std;
int main ()
{
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
23
C++
Global Variables
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>
using namespace std;
int main ()
{
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
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>
using namespace std;
C++
int main ()
{
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
When the above code is compiled and executed, it produces the following result:
10
Initializer
int
char
'\0'
float
double
pointer
NULL
25
8. CONSTANTS/LITERALS
C++
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.
Integer Literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix
specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for
decimal.
An integer literal can also have a suffix that is a combination of U and L, for
unsigned and long, respectively. The suffix can be uppercase or lowercase and
can be in any order.
Here are some examples of integer literals:
212
// Legal
215u
// Legal
0xFeeL
// Legal
078
032UU
// decimal
0213
// octal
0x4b
// hexadecimal
30
// int
30u
// unsigned int
30l
// long
30ul
// unsigned long
26
C++
Floating-point Literals
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.
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.
Here are some examples of floating-point literals:
3.14159
// Legal
314159E-5L
// Legal
510E
210f
.e55
Boolean Literals
There are two Boolean literals and they are part of standard C++ keywords:
You should not consider the value of true equal to 1 and value of false equal to
0.
Character Literals
Character literals are enclosed in single quotes. If the literal begins with L
(uppercase only), it is a wide character literal (e.g., L'x') and should be stored
in wchar_t type of variable. Otherwise, it is a narrow character literal (e.g., 'x')
and can be stored in a simple variable of char type.
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 backslash
they 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:
Escape sequence
Meaning
\\
\ character
27
C++
\'
' character
\"
" character
\?
? character
\a
Alert or bell
\b
Backspace
\f
Form feed
\n
Newline
\r
Carriage return
\t
Horizontal tab
\v
Vertical tab
\ooo
\xhh . . .
int main()
{
cout << "Hello\tWorld\n\n";
return 0;
}
When the above code is compiled and executed, it produces the following result:
28
C++
Hello
World
String Literals
String literals are enclosed in double quotes. A string contains characters that
are similar to character literals: plain characters, escape sequences, and
universal characters.
You can break a long line into multiple lines using string literals and separate
them using whitespaces.
Here are some examples of string literals. All the three forms are identical
strings.
"hello, dear"
"hello, \
dear"
Defining Constants
There are two simple ways in C++ to define constants:
#define LENGTH 10
#define WIDTH
C++
int main()
{
int area;
int main()
{
const int
LENGTH = 10;
const int
WIDTH
= 5;
C++
}
When the above code is compiled and executed, it produces the following result:
50
Note that it is a good programming practice to define constants in CAPITALS.
31
C++
9. MODIFIER TYPES
C++ allows the char, int, and double data types to have modifiers preceding
them. A modifier is used to alter the meaning of the base type so that it more
precisely fits the needs of various situations.
The data type modifiers are listed here:
signed
unsigned
long
short
The modifiers signed, unsigned, long, and short can be applied to integer base
types. In addition, signed and unsigned can be applied to char, and long can
be applied to double.
The
modifiers signed and unsigned can
also
be
used
to long or short modifiers. For example, unsigned long int.
as
prefix
C++
allows
a
shorthand
notation
for
declaring unsigned,
short, or long integers. You can simply use the word unsigned, short, or long,
without int. It automatically implies int. For example, the following two
statements both declare unsigned integer variables.
unsigned x;
unsigned int y;
To understand the difference between the way signed and unsigned integer
modifiers are interpreted by C++, you should run the following short program:
#include <iostream>
using namespace std;
C++
j = 50000;
i = j;
cout << i << " " << j;
return 0;
}
When this program is run, following is the output:
-15536 50000
The above result is because the bit pattern that represents 50,000 as a short
unsigned integer is interpreted as -15,536 by a short.
Meaning
const
volatile
The modifier volatile tells the compiler that a variable's value may
be changed in ways not explicitly specified by the program.
restrict
33
C++
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
miles;
}
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.
34
C++
// Function declaration
void func(void);
main()
{
while(count--)
{
func();
}
return 0;
}
// Function definition
void func( void )
{
static int i = 5; // local static variable
i++;
std::cout << "i is " << i ;
std::cout << " and count is " << count << std::endl;
}
When the above code is compiled and executed, it produces the following result:
35
C++
i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
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
int count ;
extern void write_extern();
main()
{
count = 5;
write_extern();
}
36
C++
void write_extern(void)
{
std::cout << "Count is " << count << std::endl;
}
Here, extern keyword is being used to declare count in another file. Now compile
these two files as follows:
$g++ main.cpp support.cpp -o write
This will produce write executable program, try to execute write and check the
result as follows:
$./write
5
37
11. OPERATORS
C++
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
This chapter will examine the arithmetic, relational, logical, bitwise, assignment
and other operators one by one.
Arithmetic Operators
There are following arithmetic operators supported by C++ language:
Assume variable A holds 10 and variable B holds 20, then:
Operator
Description
Example
A + B will give 30
Divides
numerator
numerator
Modulus
Operator
and
remainder of after an integer
division
by
de-
B / A will give 2
B % A will give 0
38
C++
++
--
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>
using namespace std;
main()
{
int a = 21;
int b = 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 = a * b;
cout << "Line 3 - Value of c is :" << c << endl ;
c = a / b;
cout << "Line 4 - Value of c is
c = a % b;
cout << "Line 5 - Value of c is
c = a++;
cout << "Line 6 - Value of c is :" << c << endl ;
c = a--;
cout << "Line 7 - Value of c is
return 0;
39
C++
}
When the above code is compiled and executed, it produces the following result:
Line 1 - Value of c is :31
Line 2 - Value of c is
:11
:2
Line 5 - Value of c is
:1
:22
Relational Operators
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then:
Operator
Description
Example
==
(A == B) is not true.
!=
(A != B) is true.
>
<
(A < B) is true.
40
C++
>=
<=
Checks if
operand is
the value
yes then
true.
(A <= B) is 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>
using namespace std;
main()
{
int a = 21;
int b = 10;
int c ;
if( a == b )
{
cout << "Line 1 - a is equal to b" << endl ;
}
else
{
cout << "Line 1 - a is not equal to b" << endl ;
}
if ( a < b )
{
41
C++
}
if ( b >= a )
{
cout << "Line 5 - b is either greater than \
or equal to b" << endl ;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
42
C++
Logical Operators
There are following logical operators supported by C++ language.
Assume variable A holds 1 and variable B holds 0, then:
Operator
Description
Example
&&
(A && B) is false.
||
(A || B) is true.
Try the following example to understand all the logical operators available in
C++.
Copy and paste the following C++ program in test.cpp file and compile and run
this program.
#include <iostream>
using namespace std;
main()
{
int a = 5;
int b = 20;
int c ;
43
C++
if ( a && b )
{
cout << "Line 1 - Condition is true"<< endl ;
}
if ( a || b )
{
cout << "Line 2 - Condition is true"<< endl ;
}
/* Let's change the values of
a and b */
a = 0;
b = 10;
if ( a && b )
{
cout << "Line 3 - Condition is true"<< endl ;
}
else
{
cout << "Line 4 - Condition is not true"<< endl ;
}
if ( !(a && b) )
{
cout << "Line 5 - Condition is true"<< endl ;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Line 1 - Condition is true
Line 2 - Condition is true
Line 4 - Condition is not true
Line 5 - Condition is true
44
C++
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables
for &, |, and ^ are as follows:
p
p&q
p|q
p^q
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
----------------A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the following
table. Assume variable A holds 60 and variable B holds 13, then:
Operator
Description
Example
&
C++
not both.
~
Binary
Ones
Complement
Operator is unary and has the
effect of 'flipping' bits.
<<
>>
Try the following example to understand all the bitwise operators available in
C++.
Copy and paste the following C++ program in test.cpp file and compile and run
this program.
#include <iostream>
using namespace std;
main()
{
unsigned int a = 60;
// 60 = 0011 1100
// 13 = 0000 1101
int c = 0;
c = a & b;
// 12 = 0000 1100
c = a | b;
// 61 = 0011 1101
46
C++
c = a ^ b;
// 49 = 0011 0001
c = ~a;
c = a << 2;
c = a >> 2;
// 15 = 0000 1111
return 0;
}
When the above code is compiled and executed, it produces the following result:
Line 1 - Value of c is : 12
Line 2 - Value of c is: 61
Line 3 - Value of c is: 49
Line 4 - Value of c is: -61
Line 5 - Value of c is: 240
Line 6 - Value of c is: 15
Assignment Operators
There are following assignment operators supported by C++ language:
Operator
Description
Example
+=
C += A is equivalent to C = C +
A
47
C++
left operand.
-=
Subtract
AND
assignment
operator, It subtracts right
operand from the left operand
and assign the result to left
operand.
C -= A is equivalent to C = C A
*=
Multiply
AND
assignment
operator, It multiplies right
operand with the left operand
and assign the result to left
operand.
C *= A is equivalent to C = C *
A
/=
Divide
AND
assignment
operator, It divides left operand
with the right operand and
assign
the
result
to
left
operand.
C /= A is equivalent to C = C /
A
%=
Modulus
AND
assignment
operator, It takes modulus
using two operands and assign
the result to left operand.
C %= A is equivalent to C = C
%A
<<=
Left shift
operator.
AND
assignment
>>=
Right shift
operator.
AND
assignment
&=
Bitwise
operator.
assignment
^=
Bitwise
exclusive
OR
assignment operator.
and
C ^= 2 is same as C = C ^ 2
|=
Bitwise
inclusive
OR
assignment operator.
and
C |= 2 is same as C = C | 2
AND
48
C++
Try the following example to understand all the assignment operators available
in C++.
Copy and paste the following C++ program in test.cpp file and compile and run
this program.
#include <iostream>
using namespace std;
main()
{
int a = 21;
int c ;
c =
a;
c +=
a;
c -=
a;
c *=
a;
c /=
a;
= 200;
c %=
a;
c <<=
2;
49
C++
c >>=
2;
c &=
2;
c ^=
2;
c |=
2;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Line 1 - =
Operator, Value of c = : 21
Misc Operators
The following table lists some other operators that C++ supports.
Operator
Description
50
C++
sizeof
Condition ? X : Y
Cast
&
Operator
Associativity
51
C++
Postfix
() [] -> . ++ - -
Left to right
Unary
Right to left
Multiplicative
*/%
Left to right
Additive
+-
Left to right
Shift
<< >>
Left to right
Relational
Left to right
Equality
== !=
Left to right
Bitwise AND
&
Left to right
Bitwise XOR
Left to right
Bitwise OR
Left to right
Logical AND
&&
Left to right
Logical OR
||
Left to right
Conditional
?:
Right to left
Assignment
Right to left
Comma
Left to right
C++
main()
{
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d;
// ( 30 * 15 ) / 5
e = ((a + b) * c) / d;
// (30 * 15 ) / 5
e = (a + b) * (c / d);
// (30) * (15/5)
e = a + (b * c) / d;
//
20 + (150/5)
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of (a + b) * c / d is :90
Value of ((a + b) * c) / d is
:90
Value of (a + b) * (c / d) is
:90
Value of a + (b * c) / d is
:50
53
C++
54
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:
Description
while loop
for loop
55
C++
do...while loop
nested loops
While Loop
A while loop statement repeatedly executes a target statement as long as a
given condition is true.
Syntax
The syntax of a while loop in C++ is:
while(condition)
{
statement(s);
}
Here, statement(s) may be a single statement or a block of statements.
The condition may 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
56
C++
Here, key point of the while loop 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>
using namespace std;
int main ()
{
// Local variable declaration:
int a = 10;
57
C++
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
for Loop
A for loop is a repetition control structure that allows you to efficiently write a
loop that needs to execute a specific number of times.
Syntax
The syntax of a for loop in C++ is:
for ( init; condition; increment )
{
statement(s);
}
Here is the flow of control in a for loop:
1. The init step 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, the condition is 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
to the increment statement. This statement allows you to update any
58
C++
Flow Diagram
Example
#include <iostream>
using namespace std;
int main ()
{
// for loop execution
59
C++
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
dowhile Loop
Unlike for and while loops, which test the loop condition at the top of the loop,
the do...while loop checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is
guaranteed to execute at least one time.
Syntax
The syntax of a do...while loop in C++ is:
do
{
statement(s);
}while( condition );
Notice that the conditional expression appears at the end of the loop, so the
statement(s) in the loop execute once before the condition is tested.
60
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>
using namespace std;
int main ()
{
// Local variable declaration:
int a = 10;
// do loop execution
do
{
cout << "value of a: " << a << endl;
a = a + 1;
}while( a < 20 );
61
C++
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
nested Loops
A loop can be nested inside of another loop. C++ allows at least 256 levels of
nesting.
Syntax
The syntax for a nested for loop statement in C++ is as follows:
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s); // you can put more statements.
}
The syntax for a nested while loop statement in C++ is as follows:
while(condition)
{
while(condition)
62
C++
{
statement(s);
}
statement(s); // you can put more statements.
}
The syntax for a nested do...while loop statement in C++ is as follows:
do
{
statement(s); // you can put more statements.
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>
using namespace std;
int main ()
{
int i, j;
C++
}
This would produce the following result:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
C++
Control Statement
Description
break statement
Terminates
the loop or switch statement
and
transfers execution to the statement immediately
following the loop or switch.
continue statement
goto statement
Break Statement
The break statement has the following two usages in C++:
If you are using nested loops (i.e., one loop inside another loop), the break
statement will stop the execution of the innermost loop and start executing the
next line of code after the block.
Syntax
The syntax of a break statement in C++ is:
break;
Flow Diagram
65
C++
Example
#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration:
int a = 10;
// do loop execution
do
{
cout << "value of a: " << a << endl;
a = a + 1;
if( a > 15)
{
// terminate the loop
break;
}
}while( a < 20 );
66
C++
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: prettyprint notranslate10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
continue Statement
The continue statement works somewhat like the break statement. Instead of
forcing termination, however, continue forces the next iteration of the loop to
take place, skipping any code in between.
For the for loop, continue causes the conditional test and increment portions of
the loop to execute. For the while and do...while loops, program control passes
to the conditional tests.
Syntax
The syntax of a continue statement in C++ is:
continue;
Flow Diagram
67
C++
Example
#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration:
int a = 10;
// do loop execution
do
{
if( a == 15)
{
// skip the iteration.
a = a + 1;
continue;
}
cout << "value of a: " << a << endl;
a = a + 1;
68
C++
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
goto Statement
A goto statement provides an unconditional jump from the goto to a labeled
statement in the same function.
NOTE: Use of goto statement is highly discouraged because it makes difficult to
trace the control flow of a program, making the program hard to understand and
hard to modify. Any program that uses a goto can be rewritten so that it doesn't
need the goto.
Syntax
The syntax of a goto statement in C++ is:
goto label;
..
.
label: statement;
Where label is an identifier that identifies a labeled statement. A labeled
statement is any statement that is preceded by an identifier followed by a colon
(:).
Flow Diagram
69
C++
Example
#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration:
int a = 10;
// do loop execution
LOOP:do
{
if( a == 15)
{
// skip the iteration.
a = a + 1;
goto LOOP;
}
cout << "value of a: " << a << endl;
a = a + 1;
}while( a < 20 );
70
C++
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
One good use of goto is to exit from a deeply nested routine. For example,
consider the following code fragment:
for(...) {
for(...) {
while(...) {
if(...) goto stop;
.
.
.
}
}
}
stop:
cout << "Error in program.\n";
Eliminating the goto would force a number of additional tests to be performed. A
simplebreak statement would not work here, because it would only cause the
program to exit from the innermost loop.
71
C++
int main ()
{
for( ; ; )
{
printf("This loop will run forever.\n");
}
return 0;
}
When the conditional expression is absent, it is assumed to be true. You may
have an initialization and increment expression, but C++ programmers more
commonly use the for (;;) construct to signify an infinite loop.
NOTE: You can terminate an infinite loop by pressing Ctrl + C keys.
72
C++
Description
if statement
if...else statement
switch statement
73
C++
If Statement
An if statement consists of a boolean expression followed by one or more
statements.
Syntax
The syntax of an if statement in C++ is:
if(boolean_expression)
{
// statement(s) will execute if the boolean expression is true
}
If the boolean expression evaluates to true, then the block of code inside the if
statement will be executed. If boolean expression evaluates to false, then the
first set of code after the end of the if statement (after the closing curly brace)
will be executed.
Flow Diagram
74
C++
Example
#include <iostream>
using namespace std;
int main ()
{
// local variable declaration:
int a = 10;
return 0;
}
75
C++
When the above code is compiled and executed, it produces the following result:
a is less than 20;
value of a is : 10
ifelse Statement
An if statement can be followed by an optional else statement, which executes
when the boolean expression is false.
Syntax
The syntax of an if...else statement in C++ is:
if(boolean_expression)
{
// statement(s) will execute if the boolean expression is true
}
else
{
// statement(s) will execute if the boolean expression is false
}
If the boolean expression evaluates to true, then the if block of code will be
executed, otherwise else block of code will be executed.
Flow Diagram
76
C++
Example
#include <iostream>
using namespace std;
int main ()
{
// local variable declaration:
int a = 100;
return 0;
}
When the above code is compiled and executed, it produces the following result:
a is not less than 20;
value of a is : 100
An if can have zero or one else's and it must come after any else if's.
77
C++
An if can have zero to many else if's and they must come before the else.
Syntax
The syntax of an if...else if...else statement in C++ is:
if(boolean_expression 1)
{
// Executes when the boolean expression 1 is true
}
else if( boolean_expression 2)
{
// Executes when the boolean expression 2 is true
}
else if( boolean_expression 3)
{
// Executes when the boolean expression 3 is true
}
else
{
// executes when the none of the above condition is true.
}
Example
#include <iostream>
using namespace std;
int main ()
{
// local variable declaration:
int a = 100;
C++
{
// if condition is true then print the following
cout << "Value of a is 10" << endl;
}
else if( a == 20 )
{
// if else if condition is true
cout << "Value of a is 20" << endl;
}
else if( a == 30 )
{
// if else if condition is true
cout << "Value of a is 30" << endl;
}
else
{
// if none of the conditions is true
cout << "Value of a is not matching" << endl;
}
cout << "Exact value of a is : " << a << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of a is not matching
Exact value of a is : 100
Switch Statement
A switch statement allows a variable to be tested for equality against a list of
values. Each value is called a case, and the variable being switched on is
checked for each case.
Syntax
The syntax for a switch statement in C++ is as follows:
79
C++
switch(expression){
case constant-expression
statement(s);
break; //optional
case constant-expression
statement(s);
break; //optional
You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.
The constant-expression for a case must be the same data type as the
variable in the switch, and it must be a constant or a literal.
When a break statement is reached, the switch terminates, and the flow
of control jumps to the next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of
control will fall through to subsequent cases until a break is reached.
Flow Diagram
80
C++
Example
#include <iostream>
using namespace std;
int main ()
{
// local variable declaration:
char grade = 'D';
switch(grade)
{
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
81
C++
case 'D' :
cout << "You passed" << endl;
break;
case 'F' :
cout << "Better try again" << endl;
break;
default :
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;
return 0;
}
This would produce the following result:
You passed
Your grade is D
Nested if Statement
It is always legal to nest if-else statements, which means you can use one if or
else if statement inside another if or else if statement(s).
Syntax
The syntax for a nested if statement is as follows:
if( boolean_expression 1)
{
// Executes when the boolean expression 1 is true
if(boolean_expression 2)
{
// Executes when the boolean expression 2 is true
}
}
You can nest else if...else in the similar way as you have nested if statement.
82
C++
Example
#include <iostream>
using namespace std;
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
C++
C++ specifies that at least 256 levels of nesting be allowed for switch
statements.
Syntax
The syntax for a nested switch statement is as follows:
switch(ch1) {
case 'A':
cout << "This A is part of outer switch";
switch(ch2) {
case 'A':
cout << "This A is part of inner switch";
break;
case 'B': // ...
}
break;
case 'B': // ...
}
Example
#include <iostream>
using namespace std;
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
switch(a) {
case 100:
cout << "This is part of outer switch" << endl;
switch(b) {
case 200:
cout << "This is part of inner switch" << endl;
84
C++
}
}
cout << "Exact value of a is : " << a << endl;
cout << "Exact value of b is : " << b << endl;
return 0;
}
This would produce the following result:
This is part of outer switch
This is part of inner switch
Exact value of a is : 100
Exact value of b is : 200
The ? : Operator
We have covered conditional operator ? : in previous chapter which can be
used to replace if...else statements. 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.
85
14. FUNCTIONS
C++
Defining a Function
The general form of a C++ function definition is as follows:
return_type function_name( parameter list )
{
body of the function
}
A C++ function definition consists of a function header and a function body.
Here are all the parts of a function:
Function Name: This is the actual name of the function. The function
name and the parameter list together constitute the function signature.
C++
Example:
Following is the source code for a function called max(). This function takes two
parameters num1 and num2 and returns the maximum between the two:
// function returning the max between two numbers
return result;
}
Function Declarations
A function declaration tells the compiler about a function name and how to call
the function. The actual body of the function can be defined separately.
A function declaration has the following parts:
return_type function_name( parameter list );
For the above defined function max(), following is the function declaration:
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is
required, so following is also valid declaration:
int max(int, int);
87
C++
Function declaration is required when you define a function in one source file
and you call that function in another file. In such case, you should declare the
function at the top of the file calling the function.
Calling a Function
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 its 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>
using namespace std;
// function declaration
int max(int num1, int num2);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int ret;
return 0;
}
C++
return result;
}
I kept max() function along with main() function and compiled the source code.
While running final executable, it would produce the following result:
Max value is : 200
Function Arguments
If a function is to use arguments, it must declare variables that accept the
values of the arguments. These variables are called the formal parameters of
the function.
The formal parameters behave like other local variables inside the function and
are created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a
function:
Call Type
Description
Call by value
Call by pointer
C++
Call by Value
The call 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.
// function definition to swap the values.
void swap(int x, int y)
{
int temp;
/* put y into x */
return;
}
Now, let us call the function swap() by passing actual values as in the following
example:
#include <iostream>
using namespace std;
// function declaration
void swap(int x, int y);
90
C++
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
return 0;
}
When the above code is put together in a file, compiled and executed, it
produces the following result:
Before swap, value of a :100
Before swap, value of b :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.
Call by Pointer
The call by pointer method of passing arguments to a function copies the
address of an argument into the formal parameter. Inside the function, the
address is used to access the actual argument used in the call. This means that
changes made to the parameter affect the passed argument.
To pass the value by pointer, argument pointers are passed to the functions just
like any other value. So accordingly you need to declare the function parameters
91
C++
return;
}
To check the
Pointers chapter.
more
detail
about
C++
pointers,
kindly
check C++
For now, let us call the function swap() by passing values by pointer as in the
following example:
#include <iostream>
using namespace std;
// function declaration
void swap(int *x, int *y);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
C++
return 0;
}
When the above code is put together in a file, compiled and executed, it
produces the following result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
Call by Reference
The call by reference method of passing arguments to a function copies the
reference of an argument into the formal parameter. Inside the function, the
reference is used to access the actual argument used in the call. This means that
changes made to the parameter affect the passed argument.
To pass the value by reference, argument reference is passed to the functions
just like any other value. So accordingly you need to declare the function
parameters as reference types as in the following function swap(), which
exchanges the values of the two integer variables pointed to by its arguments.
// function definition to swap the values.
void swap(int &x, int &y)
{
int temp;
temp = x; /* save the value at address x */
x = y;
/* put y into x */
return;
93
C++
}
For now, let us call the function swap() by passing values by reference as in the
following example:
#include <iostream>
using namespace std;
// function declaration
void swap(int &x, int &y);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
return 0;
}
When the above code is put together in a file, compiled and executed, it
produces the following result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
94
C++
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
and above mentioned example while calling max() function used the same
method.
result = a + b;
return (result);
}
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int result;
C++
return 0;
}
When the above code is compiled and executed, it produces the following result:
Total value is :300
Total value is :120
96
15. NUMBERS
C++
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.
int main ()
{
// number definition:
short
s;
int
i;
long
l;
float
f;
double d;
// number assignments;
s = 10;
i = 1000;
l = 1000000;
f = 230.47;
d = 30949.374;
// number printing;
cout << "short
C++
return 0;
}
When the above code is compiled and executed, it produces the following result:
short
s :10
int
i :1000
long
l :1000000
float
f :230.47
double d :30949.4
double cos(double);
This function takes an angle (as a double) and returns the cosine.
double sin(double);
This function takes an angle (as a double) and returns the sine.
double tan(double);
This function takes an angle (as a double) and returns the tangent.
double log(double);
This function takes a number and returns the natural log of that
number.
98
C++
double sqrt(double);
You pass this function a number and it gives you the square root.
int abs(int);
This function returns the absolute value of an integer that is passed to
it.
double fabs(double);
This function returns the absolute value of any decimal number passed
to it.
10
double floor(double);
Finds the integer which is less than or equal to the argument passed to
it.
int main ()
{
// number definition:
short
s = 10;
int
i = -1000;
long
l = 100000;
float
f = 230.47;
99
C++
double d = 200.374;
// mathematical operations;
cout << "sin(d) :" << sin(d) << endl;
cout << "abs(i)
return 0;
}
When the above code is compiled and executed, it produces the following result:
sign(d) :-0.634939
abs(i)
:1000
floor(d) :200
sqrt(f) :15.1812
pow( d, 2 ) :40149.7
int main ()
{
100
C++
int i,j;
/* generate 10
random numbers. */
return 0;
}
When the above code is compiled and executed, it produces the following result:
Random Number : 1748144778
Random Number : 630873888
Random Number : 2134540646
Random Number : 219404170
Random Number : 902129458
Random Number : 920445370
Random Number : 1319072661
Random Number : 257938873
Random Number : 1256201101
Random Number : 580322989
101
16. ARRAYS
C++
C++ provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type. An array is used to store a collection of
data, but it is often more useful to think of an array as a collection of variables
of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and
number99, you declare one array variable such as numbers and use
numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.
A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address
corresponds to the first element and the highest address to the last element.
Declaring 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:
type arrayName [ arraySize ];
This is called a single-dimension array. The arraySize must be an integer
constant greater than zero and type can be any valid C++ data type. For
example, to declare a 10-element array called balance of type double, use this
statement:
double balance[10];
Initializing Arrays
You can initialize C++ array elements either one by one or using a single
statement as follows:
double balance[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:
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
102
C++
You will create exactly the same array as you did in the previous example.
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:
#include <iomanip>
using std::setw;
int main ()
{
int n[ 10 ]; // n is an array of 10 integers
C++
return 0;
}
This program makes use of setw() function to format the output. When the
above code is compiled and executed, it produces the following result:
Element
Value
100
101
102
103
104
105
106
107
108
109
Arrays in C++
Arrays are important to C++ and should need lots of more detail. There are
following few important concepts, which should be clear to a C++ programmer:
Concept
Description
Multi-dimensional arrays
Pointer to an array
C++
Multi-dimensional Arrays
C++ allows multidimensional arrays.
multidimensional array declaration:
Here
is
the
general
form
of
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional 5 . 10 . 4
integer array:
int threedim[5][10][4];
Two-Dimensional Arrays
The simplest form of the multidimensional array is the two-dimensional array. A
two-dimensional array is, in essence, a list of one-dimensional arrays. To declare
a two-dimensional integer array of size x,y, you would write something as
follows:
type arrayName [ x ][ y ];
Where type can be any valid C++ data type and arrayName will be a valid C++
identifier.
A two-dimensional array can be think as a table, which will have x number of
rows and y number of columns. A 2-dimensional array a, which contains three
rows and four columns can be shown as below:
105
C++
/*
{4, 5, 6, 7} ,
/*
/*
};
The nested braces, which indicate the intended row, are optional. The following
initialization is equivalent to previous example:
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
int main ()
{
// an array with 5 rows and 2 columns.
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
C++
return 0;
}
When the above code is compiled and executed, it produces the following result:
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.
Pointer to an 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:
double balance[50];
balance is a pointer to &balance[0], which is the address of the first element of
the array balance. Thus, the following program fragment assigns p the address
of the first element ofbalance:
double *p;
double balance[10];
p = balance;
It is legal to use array names as constant pointers, and vice versa. Therefore,
*(balance + 4) is a legitimate way of accessing the data at balance[4].
107
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>
using namespace std;
int main ()
{
// an array with 5 elements.
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
p = balance;
cout << "Array values using balance as address " << endl;
for ( int i = 0; i < 5; i++ )
{
cout << "*(balance + " << i << ") : ";
cout << *(balance + i) << endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Array values using pointer
*(p + 0) : 1000
108
C++
*(p + 1) : 2
*(p + 2) : 3.4
*(p + 3) : 17
*(p + 4) : 50
Array values using balance as address
*(balance + 0) : 1000
*(balance + 1) : 2
*(balance + 2) : 3.4
*(balance + 3) : 17
*(balance + 4) : 50
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 *p will give us
value available at the address stored in p, as we have shown in the above
example.
Way-1
Formal parameters as a pointer as follows:
void myFunction(int *param)
{
.
.
.
}
Way-2
Formal parameters as a sized array as follows:
void myFunction(int param[10])
109
C++
{
.
.
.
}
Way-3
Formal parameters as an unsized array as follows:
void myFunction(int param[])
{
.
.
.
}
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:
double getAverage(int arr[], int size)
{
int
i, sum = 0;
double avg;
return avg;
}
Now, let us call the above function as follows:
#include <iostream>
110
C++
// function declaration:
double getAverage(int arr[], int size);
int main ()
{
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
return 0;
}
When the above code is compiled together and executed, it produces the
following result:
Average value is: 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 formal
parameters.
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 the
local 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>
r[10];
return r;
}
C++
int *p;
p = getRandom();
for ( int i = 0; i < 10; i++ )
{
cout << "*(p + " << i << ") : ";
cout << *(p + i) << endl;
}
return 0;
}
When the above code is compiled together and executed, it produces result
something as follows:
624723190
1468735695
807113585
976495677
613357504
1377296355
1530315259
1778906708
1820354158
667126415
*(p + 0) : 624723190
*(p + 1) : 1468735695
*(p + 2) : 807113585
*(p + 3) : 976495677
*(p + 4) : 613357504
*(p + 5) : 1377296355
*(p + 6) : 1530315259
*(p + 7) : 1778906708
*(p + 8) : 1820354158
*(p + 9) : 667126415
113
C++
114
17. STRINGS
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>
115
C++
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
return 0;
}
When the above code is compiled and executed, it produces the following result:
Greeting message: Hello
C++ supports a wide range of functions that manipulate null-terminated strings:
S.N.
strcpy(s1, s2);
Copies string s2 into string s1.
strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
strlen(s1);
Returns the length of string s1.
strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than
0 if s1>s2.
strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
strstr(s1, s2);
116
C++
int main ()
{
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
int
len ;
return 0;
}
When the above code is compiled and executed, it produces result something as
follows:
strcpy( str3, str1) : Hello
117
C++
int main ()
{
string str1 = "Hello";
string str2 = "World";
string str3;
int
len ;
return 0;
}
118
C++
When the above code is compiled and executed, it produces result something as
follows:
str3 : Hello
str1 + str2 : HelloWorld
str3.size() :
10
119
18. POINTERS
C++
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 location
has 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>
int main ()
{
int
var1;
char var2[10];
return 0;
}
When the above code is compiled and executed, it produces the following result:
Address of var1 variable: 0xbfebd5c0
Address of var2 variable: 0xbfebd5b6
120
C++
*ip;
// pointer to an integer
double *dp;
// pointer to a double
float
*fp;
// pointer to a float
char
*ch
// pointer to character
The actual data type of the value of all pointers, whether integer, float,
character, or otherwise, is the same, a long hexadecimal number that represents
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.
int main ()
{
int
var = 20;
int
*ip;
// pointer variable
ip = &var;
C++
return 0;
}
When the above code is compiled and executed, it produces result something as
follows:
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
Pointers in C++
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
122
C++
and arrays.
C++ array of pointers
Null Pointers
It is always a good practice to assign the pointer NULL to a pointer variable in
case you do not have exact address to be assigned. This is done at the time of
variable declaration. A pointer that is assigned NULL is called a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard
libraries, including iostream. Consider the following program:
#include <iostream>
int main ()
{
int
*ptr = NULL;
return 0;
}
123
C++
When the above code is compiled and executed, it produces the following result:
The value of ptr is 0
On most of the operating systems, programs are not permitted to access
memory at address 0 because that memory is reserved by the operating system.
However, the memory address 0 has special significance; it signals that the
pointer is not intended to point to an accessible memory location. But by
convention, if a pointer contains the null (zero) value, it is assumed to point to
nothing.
To check for a null pointer you can use an if statement as follows:
if(ptr)
if(!ptr)
// succeeds if p is null
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 becomes
difficult to debug the program.
Pointer Arithmetic
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. There are four arithmetic operators that can be used on pointers: ++, --,
+, and To understand pointer arithmetic, let us consider that ptr is an integer pointer
which points to the address 1000. Assuming 32-bit integers, let us perform the
following arithmatic operation on the pointer:
ptr++
the ptr will 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.
Incrementing a Pointer
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>
124
C++
int main ()
{
int
int
*ptr;
125
C++
Decrementing a Pointer
The same considerations apply to decrementing a pointer, which decreases its
value by the number of bytes of its data type as shown below:
#include <iostream>
int main ()
{
int
int
*ptr;
C++
Pointer Comparisons
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.
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>
int main ()
{
int
int
*ptr;
C++
}
return 0;
}
When the above code is compiled and executed, it produces result something as
follows:
Address of var[0] = 0xbfce42d0
Value of var[0] = 10
Address of var[1] = 0xbfce42d4
Value of var[1] = 100
Address of var[2] = 0xbfce42d8
Value of var[2] = 200
Pointers vs Arrays
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>
int main ()
{
int
int
*ptr;
C++
int main ()
{
int
var++;
// This is incorrect.
}
return 0;
129
C++
}
It is perfectly acceptable to apply the pointer operator * to var but it is illegal to
modify var value. The reason for this is that var is a constant that points to the
beginning of an array and can not be used as l-value.
Because an array name generates a pointer constant, it can still be used in
pointer-style expressions, as long as it is not modified. For example, the
following is a valid statement that assigns var[2] the value 500:
*(var + 2) = 500;
Above statement is valid and will compile successfully because var is not
changed.
Array of Pointers
Before we understand the concept of array of pointers, let us consider the
following example, which makes use of an array of 3 integers:
#include <iostream>
int main ()
{
int
C++
int main ()
{
int
int *ptr[MAX];
C++
int main ()
{
char *names[MAX] = {
"Zara Ali",
"Hina Ali",
"Nuha Ali",
"Sara Ali",
};
132
C++
Pointer to a Pointer
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 main ()
{
int
var;
int
*ptr;
int
**pptr;
var = 3000;
C++
cout << "Value available at *ptr :" << *ptr << endl;
cout << "Value available at **pptr :" << **pptr << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of var :3000
Value available at *ptr :3000
Value available at **pptr :3000
int main ()
{
unsigned long sec;
getSeconds( &sec );
134
C++
return 0;
}
// function declaration:
double getAverage(int *arr, int size);
int main ()
{
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
return 0;
}
135
C++
i, sum = 0;
double avg;
return avg;
}
When the above code is compiled together and executed, it produces the
following result:
Average value is: 214.4
C++
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>
r[10];
return r;
}
p = getRandom();
for ( int i = 0; i < 10; i++ )
{
cout << "*(p + " << i << ") : ";
137
C++
return 0;
}
When the above code is compiled together and executed, it produces result
something as follows:
624723190
1468735695
807113585
976495677
613357504
1377296355
1530315259
1778906708
1820354158
667126415
*(p + 0) : 624723190
*(p + 1) : 1468735695
*(p + 2) : 807113585
*(p + 3) : 976495677
*(p + 4) : 613357504
*(p + 5) : 1377296355
*(p + 6) : 1530315259
*(p + 7) : 1778906708
*(p + 8) : 1820354158
*(p + 9) : 667126415
138
19. REFERENCES
C++
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.
References vs Pointers
References are often confused with pointers but three major differences between
references and pointers are:
You cannot have NULL references. You must always be able to assume
that a reference is connected to a legitimate piece of storage.
i = 17;
r = i;
Read the & in these declarations as reference. Thus, read the first declaration
as "r is an integer reference initialized to i" and read the second declaration as "s
is a double reference initialized to d." Following example makes use of
references on int and double:
#include <iostream>
int main ()
139
C++
{
// declare simple variables
int
i;
double d;
r = i;
double& s = d;
i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r
<< endl;
d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s
<< endl;
return 0;
}
When the above code is compiled together and executed, it produces the
following result:
Value of i : 5
Value of i reference : 5
Value of d : 11.7
Value of d reference : 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
References as parameters
140
C++
References as Parameters
We have discussed how we implement call by reference concept using
pointers. Here is another example of call by reference which makes use of C++
reference:
#include <iostream>
using namespace std;
// function declaration
void swap(int& x, int& y);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
return 0;
}
C++
{
int temp;
temp = x; /* save the value at address x */
x = y;
/* put y into x */
return;
}
When the above code is compiled and executed, it produces the following result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
C++
int main ()
{
C++
vals[3] = 70.8
vals[4] = 50
When returning a reference, be careful that the object being referred to does not
go out of scope. So it is not legal to return a reference to local var. But you can
always return a reference on a static variable.
int& func() {
int q;
//! return q; // Compile time error
static int x;
return x;
144
C++
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.
There are four time-related types: clock_t, time_t, size_t, and tm. The types clock_t, size_t and time_t are capable of representing the system time and date
as some sort of integer.
The structure type tm holds the date and time in the form of a C structure
having the following elements:
struct tm {
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
C++
hours:minutes:seconds year\n\0.
3
clock_t clock(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.
size_t strftime();
This function can be used to format date and time in a specific format.
C++
#include <ctime>
int main( )
{
// current date/time based on current system
time_t now = time(0);
cout << "The local date and time is: " << dt << endl;
8 20:07:41 2011
9 03:07:41 2011
147
C++
#include <iostream>
#include <ctime>
int main( )
{
// current date/time based on current system
time_t now = time(0);
cout << "Number of sec since January 1,1970:" << now << endl;
tm *ltm = localtime(&now);
148
C++
<iostream>
This file defines the cin, cout, cerr and clog objects, which
correspond to the standard input stream, the standard output
stream, the un-buffered standard error stream and the
buffered standard error stream, respectively.
<iomanip>
<fstream>
149
C++
#include <iostream>
int main( )
{
char str[] = "Hello C++";
int main( )
{
char name[50];
C++
cout << "Your name is: " << name << endl;
}
When the above code is compiled and executed, it will prompt you to enter a
name. You enter a value and then hit enter to see the following result:
Please enter your name: cplusplus
Your name is: cplusplus
The C++ compiler also determines the data type of the entered value and
selects the appropriate stream extraction operator to extract the value and store
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;
This will be equivalent to the following two statements:
cin >> name;
cin >> age;
int main( )
{
char str[] = "Unable to read....";
C++
}
When the above code is compiled and executed, it produces the following result:
Error message : Unable to read....
int main( )
{
char str[] = "Unable to read....";
152
C++
C/C++ arrays allow you to define variables that combine several data items of
the same kind, but structure is another user defined data type 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
Defining a Structure
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 [structure tag]
{
member definition;
member definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition. At the
end of the structure's definition, before the final semicolon, you can specify one
or more structure variables but it is optional. Here is the way you would declare
the Book structure:
struct Books
{
char
title[50];
char
author[50];
char
subject[100];
153
C++
int
book_id;
}book;
struct Books
{
char
title[50];
char
author[50];
char
subject[100];
int
book_id;
};
int main( )
{
struct Books Book1;
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
// book 2 specification
strcpy( Book2.title, "Telecom Billing");
154
C++
return 0;
}
When the above code is compiled and executed, it produces the following result:
Book 1 title : Learn C++ Programming
Book 1 author : Chand Miyan
Book 1 subject : C++ Programming
Book 1 id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Yakit Singha
Book 2 subject : Telecom
Book 2 id : 6495700
C++
#include <cstring>
struct Books
{
char
title[50];
char
author[50];
char
subject[100];
int
book_id;
};
int main( )
{
struct Books Book1;
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
C++
printBook( Book2 );
return 0;
}
void printBook( struct Books book )
{
cout << "Book title : " << book.title <<endl;
cout << "Book author : " << book.author <<endl;
cout << "Book subject : " << book.subject <<endl;
cout << "Book id : " << book.book_id <<endl;
}
When the above code is compiled and executed, it produces the following result:
Book title : Learn C++ Programming
Book author : Chand Miyan
Book subject : C++ Programming
Book id : 6495407
Book title : Telecom Billing
Book author : Yakit Singha
Book subject : Telecom
Book id : 6495700
Pointers to Structures
You can define pointers to structures in very similar way as you define pointer to
any other variable as follows:
struct Books *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;
To access the members of a structure using a pointer to that structure, you must
use the -> operator as follows:
struct_pointer->title;
157
C++
Let us re-write above example using structure pointer, hope this will be easy for
you to understand the concept:
#include <iostream>
#include <cstring>
struct Books
{
char
title[50];
char
author[50];
char
subject[100];
int
book_id;
};
int main( )
{
struct Books Book1;
// Book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
// Book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
C++
printBook( &Book1 );
return 0;
}
// This function accept pointer to structure as parameter.
void printBook( struct Books *book )
{
cout << "Book title : " << book->title <<endl;
cout << "Book author : " << book->author <<endl;
cout << "Book subject : " << book->subject <<endl;
cout << "Book id : " << book->book_id <<endl;
}
When the above code is compiled and executed, it produces the following result:
Book title : Learn C++ Programming
Book author : Chand Miyan
Book subject : C++ Programming
Book id : 6495407
Book title : Telecom Billing
Book author : Yakit Singha
Book subject : Telecom
Book id : 6495700
title[50];
char
author[50];
char
subject[100];
159
C++
int
book_id;
}Books;
Now, you can use Books directly to define variables of Books type without using
struct keyword. Following is the example:
Books Book1, Book2;
You can use typedef keyword for non-structs as well as follows:
typedef long int *pint32;
pint32 x, y, z;
x, y and z are all pointers to long ints.
160
C++
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
};
The keyword public determines the access attributes of the members of the
class that follows it. A public member can be accessed from outside the class
anywhere within the scope of the class object. You can also specify the members
of a class as private or protected which we will discuss in a sub-section.
C++
Box Box2;
Both of the objects Box1 and Box2 will have their own copy of data members.
class Box
{
public:
double length;
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
};
int main( )
{
Box Box1;
Box Box2;
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
162
C++
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560
It is important to note that private and protected members cannot be accessed
directly using direct member access operator (.). We will learn how private and
protected members can be accessed.
Description
163
C++
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
C++
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
double getVolume(void)
{
return length * breadth * height;
}
};
If you like, you can define the same function outside the class using the scope
resolution operator (::) as follows:
double Box::getVolume(void)
{
return length * breadth * height;
}
Here, only important point is that you would have to use class name just before
:: operator. A member function will be called using a dot operator (.) on a object
where it will manipulate data related to that object only as follows:
Box myBox;
// Create an object
myBox.getVolume();
Let us put above concepts to set and get the value of different class members in
a class:
#include <iostream>
C++
class Box
{
public:
double length;
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
C++
Box Box2;
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560
167
C++
public:
protected:
private:
};
class Line
168
C++
{
public:
double length;
void setLength( double len );
double getLength( void );
};
C++
Length of line : 6
Length of line : 10
class Box
{
public:
double length;
void setWidth( double wid );
double getWidth( void );
private:
170
C++
double width;
};
return 0;
}
When the above code is compiled and executed, it produces the following result:
Length of box : 10
Width of box : 10
171
C++
class Box
{
protected:
double width;
};
172
C++
return 0;
}
When the above code is compiled and executed, it produces the following result:
Width of box : 5
class Line
{
public:
void setLength( double len );
double getLength( void );
Line();
173
C++
private:
double length;
};
return 0;
}
When the above code is compiled and executed, it produces the following result:
Object is being created
174
C++
Length of line : 6
Parameterized Constructor
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:
#include <iostream>
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(double len);
private:
double length;
};
C++
{
return length;
}
// Main function for the program
int main( )
{
Line line(10.0);
return 0;
}
When the above code is compiled and executed, it produces the following result:
Object is being created, length = 10
Length of line : 10
Length of line : 6
C++
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( double a, double b, double c): X(a), Y(b), Z(c)
{
....
}
class Line
{
public:
void setLength( double len );
double getLength( void );
Line();
~Line();
private:
double length;
};
177
C++
return 0;
}
178
C++
When the above code is compiled and executed, it produces the following result:
Object is being created
Length of line : 6
Object is being deleted
Copy Constructor
The copy constructor is a constructor which creates an object by initializing it
with an object of the same class, which has been created previously. The copy
constructor is used to:
If a copy constructor is not defined in a class, the compiler itself defines one.If
the class has pointer variables and has some dynamic memory allocations, then
it is a must to have a copy constructor. The most common form of copy
constructor is shown here:
classname (const classname &obj) {
// body of constructor
}
Here, obj is a reference to an object that is being used to initialize another
object.
#include <iostream>
class Line
{
public:
int getLength( void );
Line( int len );
Line( const Line &obj);
~Line();
// simple constructor
// copy constructor
// destructor
private:
179
C++
int *ptr;
};
Line::~Line(void)
{
cout << "Freeing memory!" << endl;
delete ptr;
}
int Line::getLength( void )
{
return *ptr;
}
180
C++
display(line);
return 0;
}
When the above code is compiled and executed, it produces the following result:
Normal constructor allocating ptr
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!
Let us see the same example but with a small change to create another object
using existing object of the same type:
#include <iostream>
class Line
{
public:
int getLength( void );
Line( int len );
Line( const Line &obj);
~Line();
// simple constructor
// copy constructor
// destructor
private:
int *ptr;
};
181
C++
Line::~Line(void)
{
cout << "Freeing memory!" << endl;
delete ptr;
}
int Line::getLength( void )
{
return *ptr;
}
C++
Line line1(10);
display(line1);
display(line2);
return 0;
}
When the above code is compiled and executed, it produces the following result:
Normal constructor allocating ptr
Copy constructor allocating ptr.
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!
Freeing memory!
Friend Functions
A friend function of a class is defined outside that class' scope but it has the
right 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.
To declare a function as a friend of a class, precede the function prototype in the
class definition with keyword friend as follows:
class Box
{
double width;
public:
183
C++
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};
To declare all member functions of class ClassTwo as friends of class ClassOne,
place a following declaration in the definition of class ClassOne:
friend class ClassTwo;
Consider the following program:
#include <iostream>
class Box
{
double width;
public:
friend void printWidth( Box box );
void setWidth( double wid );
};
C++
return 0;
}
When the above code is compiled and executed, it produces the following result:
Width of box : 10
Inline Functions
C++ inline function is powerful concept that is commonly used with classes. If a
function is inline, the compiler places a copy of the code of that function at each
point where the function is called at compile time.
Any change to an inline function could require all clients of the function to be
recompiled because compiler would need to replace all the code once again
otherwise it will continue with old functionality.
To inline a function, place the keyword inline before the function name and
define the function before any calls are made to the function. The compiler can
ignore the inline qualifier in case defined function is more than a line.
A function definition in a class definition is an inline function definition, even
without the use of the inline specifier.
Following is an example, which makes use of inline function to return max of two
numbers:
#include <iostream>
C++
this Pointer
Every object in C++ has access to its own address through an important pointer
called thispointer. The this 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.
Let us try the following example to understand the concept of this pointer:
#include <iostream>
class Box
{
186
C++
public:
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume()
{
return length * breadth * height;
}
int compare(Box box)
{
return this->Volume() > box.Volume();
}
private:
double length;
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
};
int main(void)
{
Box Box1(3.3, 1.2, 1.5);
// Declare box1
// Declare box2
if(Box1.compare(Box2))
{
cout << "Box2 is smaller than Box1" <<endl;
}
else
{
187
C++
class Box
{
public:
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume()
{
188
C++
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
};
int main(void)
{
Box Box1(3.3, 1.2, 1.5);
// Declare box1
// Declare box2
Box *ptrBox;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Constructor called.
Constructor called.
Volume of Box1: 5.94
Volume of Box2: 102
189
C++
class Box
{
public:
static int objectCount;
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
// Increase every time object is created
objectCount++;
}
double Volume()
{
return length * breadth * height;
}
private:
double length;
// Length of a box
190
C++
double breadth;
// Breadth of a box
double height;
// Height of a box
};
int main(void)
{
Box Box1(3.3, 1.2, 1.5);
// Declare box1
// Declare box2
return 0;
}
When the above code is compiled and executed, it produces the following result:
Constructor called.
Constructor called.
Total objects: 2
C++
#include <iostream>
class Box
{
public:
static int objectCount;
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
// Increase every time object is created
objectCount++;
}
double Volume()
{
return length * breadth * height;
}
static int getCount()
{
return objectCount;
}
private:
double length;
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
};
C++
int main(void)
{
// Declare box1
// Declare box2
return 0;
}
When the above code is compiled and executed, it produces the following result:
Inital Stage Count: 0
Constructor called.
Constructor called.
Final Stage Count: 2
193
24. INHERITANCE
C++
// Base class
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
194
C++
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
return 0;
}
When the above code is compiled and executed, it produces the following result:
195
C++
Total area: 35
public
protected
private
Same class
yes
yes
yes
Derived classes
yes
yes
no
Outside classes
yes
no
no
A derived class inherits all base class methods with the following exceptions:
Type of Inheritance
When deriving a class from a base class, the base class may be inherited
through public, protected or private inheritance. The type of inheritance is
specified by the access-specifier as explained above.
We hardly use protected or private inheritance, but public inheritance is
commonly used. While using different type of inheritance, following rules are
applied:
196
C++
Protected
Inheritance: When
deriving
from
a protected base
class, public and
protected members
of
the
base
class
become protected members of the derived class.
Private
Inheritance: When
deriving
from
class, public and
protected members
of
the
become private members of the derived class.
a private base
base
class
Multiple Inheritance
A C++ class can inherit members from more than one class and here is the
extended syntax:
class derived-class: access baseA, access baseB....
Where access is one of public, protected, or private and would be given for
every base class and they will be separated by comma as shown above. Let us
try the following example:
#include <iostream>
197
C++
// Derived class
class Rectangle: public Shape, public PaintCost
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
C++
cout << "Total paint cost: $" << Rect.getCost(area) << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Total area: 35
Total paint cost: $2450
199
C++
class printData
{
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double
f) {
C++
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};
int main(void)
{
printData pd;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Printing int: 5
Printing float: 500.263
Printing character: Hello C++
C++
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
void setLength( double len )
{
length = len;
}
C++
{
Box box;
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;
// Breadth of a box
double height;
// Height of a box
};
// Main function for the program
int main( )
{
Box Box1;
Box Box2;
Box Box3;
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
203
C++
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
Overloadable/Non-overloadable Operators
Following is the list of operators which can be overloaded:
+
&
<
>
<=
>=
++
--
<<
>>
==
!=
&&
||
+=
-=
/=
%=
^=
&=
|=
*=
<<=
>>=
[]
()
->
->*
new
new []
delete
delete []
204
C++
.*
?:
205
C++
The unary operators operate on the object for which they were called and
normally, this operator appears on the left side of the object, as in !obj, -obj,
and ++obj but sometime they can be used as postfix as well like obj++ or obj--.
Following example explain how minus (-) operator can be overloaded for prefix
as well as postfix usage.
#include <iostream>
using namespace std;
class Distance
{
private:
int feet;
// 0 to infinite
int inches;
// 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
// method to display distance
void displayDistance()
{
cout << "F: " << feet << " I:" << inches <<endl;
}
// overloaded minus (-) operator
Distance operator- ()
{
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
206
C++
};
int main()
{
Distance D1(11, 10), D2(-5, 11);
-D1;
// apply negation
D1.displayDistance();
// display D1
-D2;
// apply negation
D2.displayDistance();
// display D2
return 0;
}
When the above code is compiled and executed, it produces the following result:
F: -11 I:-10
F: 5 I:-11
Hope above example makes your concept clear and you can apply similar
concept to overload Logical Not Operators (!).
class Time
{
private:
int hours;
// 0 to 23
int minutes;
// 0 to 59
public:
207
C++
// required constructors
Time(){
hours = 0;
minutes = 0;
}
Time(int h, int m){
hours = h;
minutes = m;
}
// method to display time
void displayTime()
{
cout << "H: " << hours << " M:" << minutes <<endl;
}
// overloaded prefix ++ operator
Time operator++ ()
{
++minutes;
C++
++hours;
minutes -= 60;
}
// return old original value
return T;
}
};
int main()
{
Time T1(11, 59), T2(10,40);
++T1;
// increment T1
T1.displayTime();
// display T1
++T1;
// increment T1 again
T1.displayTime();
// display T1
T2++;
// increment T2
T2.displayTime();
// display T2
T2++;
// increment T2 again
T2.displayTime();
// display T2
return 0;
}
When the above code is compiled and executed, it produces the following result:
H: 12 M:0
H: 12 M:1
H: 10 M:41
H: 10 M:42
209
C++
class Box
{
double length;
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
public:
double getVolume(void)
{
return length * breadth * height;
}
void setLength( double len )
{
length = len;
}
C++
Box Box2;
Box Box3;
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
211
C++
// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
class Distance
{
private:
int feet;
// 0 to infinite
int inches;
// 0 to 12
public:
// required constructors
212
C++
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
// method to display distance
void displayDistance()
{
cout << "F: " << feet << " I:" << inches <<endl;
}
// overloaded minus (-) operator
Distance operator- ()
{
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
// overloaded < operator
bool operator <(const Distance& d)
{
if(feet < d.feet)
{
return true;
}
if(feet == d.feet && inches < d.inches)
{
return true;
}
return false;
}
};
213
C++
int main()
{
Distance D1(11, 10), D2(5, 11);
if( D1 < D2 )
{
cout << "D1 is less than D2 " << endl;
}
else
{
cout << "D2 is less than D1 " << endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
D2 is less than D1
class Distance
{
private:
int feet;
// 0 to infinite
int inches;
// 0 to 12
214
C++
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
friend ostream &operator<<( ostream &output,
const Distance &D )
{
output << "F : " << D.feet << " I : " << D.inches;
return output;
}
{
input >> D.feet >> D.inches;
return input;
}
};
int main()
{
Distance D1(11, 10), D2(5, 11), D3;
215
C++
return 0;
}
When the above code is compiled and executed, it produces the following result:
$./a.out
Enter the value of object :
70
10
First Distance : F : 11 I : 10
Second Distance :F : 5 I : 11
Third Distance :F : 70 I : 10
class Time
{
private:
int hours;
// 0 to 23
int minutes;
// 0 to 59
public:
// required constructors
Time(){
hours = 0;
minutes = 0;
}
Time(int h, int m){
hours = h;
minutes = m;
216
C++
}
// method to display time
void displayTime()
{
cout << "H: " << hours << " M:" << minutes <<endl;
}
// overloaded prefix ++ operator
Time operator++ ()
{
++minutes;
C++
{
Time T1(11, 59), T2(10,40);
++T1;
// increment T1
T1.displayTime();
// display T1
++T1;
// increment T1 again
T1.displayTime();
// display T1
T2++;
// increment T2
T2.displayTime();
// display T2
T2++;
// increment T2 again
T2.displayTime();
// display T2
return 0;
}
When the above code is compiled and executed, it produces the following result:
H: 12 M:0
H: 12 M:1
H: 10 M:41
H: 10 M:42
class Distance
{
private:
int feet;
// 0 to infinite
int inches;
// 0 to 12
public:
218
C++
// required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
void operator=(const Distance &D )
{
feet = D.feet;
inches = D.inches;
}
// method to display distance
void displayDistance()
{
cout << "F: " << feet <<
};
int main()
{
Distance D1(11, 10), D2(5, 11);
C++
return 0;
}
When the above code is compiled and executed, it produces the following result:
First Distance : F: 11 I:10
Second Distance :F: 5 I:11
First Distance :F: 5 I:11
class Distance
{
private:
int feet;
// 0 to infinite
int inches;
// 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
// overload function call
220
C++
};
int main()
{
Distance D1(11, 10), D2;
return 0;
}
When the above code is compiled and executed, it produces the following result:
First Distance : F: 11 I:10
Second Distance :F: 30 I:120
221
C++
class safearay
{
private:
int arr[SIZE];
public:
safearay()
{
register int i;
for(i = 0; i < SIZE; i++)
{
arr[i] = i;
}
}
int &operator[](int i)
{
if( i > SIZE )
{
cout << "Index out of bounds" <<endl;
// return first element.
return arr[0];
}
return arr[i];
}
};
int main()
{
222
C++
safearay A;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of A[2] : 2
Value of A[5] : 5
Index out of bounds
Value of A[12] : 0
C++
p->m = 10 ; // (p.operator->())->m = 10
}
The statement p->m is interpreted as (p.operator->())->m. Using the same
concept, following example explains how a class access operator -> can be
overloaded.
#include <iostream>
#include <vector>
using namespace std;
}
friend class SmartPointer;
};
C++
ObjContainer oc;
int index;
public:
SmartPointer(ObjContainer& objc)
{
oc = objc;
index = 0;
}
// Return value indicates end of list:
bool operator++() // Prefix version
{
if(index >= oc.a.size()) return false;
if(oc.a[++index] == 0) return false;
return true;
}
bool operator++(int) // Postfix version
{
return operator++();
}
// overload operator->
Obj* operator->() const
{
if(!oc.a[index])
{
cout << "Zero value";
return (Obj*)0;
}
return oc.a[index];
}
};
int main() {
const int sz = 10;
Obj o[sz];
225
C++
ObjContainer oc;
for(int i = 0; i < sz; i++)
{
oc.add(&o[i]);
}
SmartPointer sp(oc); // Create an iterator
do {
sp->f(); // smart pointer call
sp->g();
} while(sp++);
return 0;
}
When the above code is compiled and executed, it produces the following result:
10
12
11
13
12
14
13
15
14
16
15
17
16
18
17
19
18
20
19
21
226
C++
227
26. POLYMORPHISM
C++
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
int area()
{
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape{
public:
Rectangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << "Rectangle class area :" <<endl;
228
C++
tri(10,5);
return 0;
}
229
C++
When the above code is compiled and executed, it produces the following result:
Parent class area
Parent class area
The reason for the incorrect output is that the call of the function area() is being
set once by the compiler as the version defined in the base class. This is
called static resolution of the function call, or static linkage - the function call
is fixed before the program is executed. This is also sometimes called early
binding because 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 keyword virtual so that it looks
like this:
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
virtual int area()
{
cout << "Parent class area :" <<endl;
return 0;
}
};
After this slight modification, when the previous example code is compiled and
executed, it produces the following result:
Rectangle class area
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.
230
C++
As you can see, each of the child classes has a separate implementation for the
function area(). This is how polymorphism is generally used. You have different
classes with a function of the same name, and even the same parameters, but
with different implementations.
Virtual Function
A virtual function is a function in a base class that is declared using the
keyword virtual. 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 as dynamic linkage, or late binding.
231
C++
int main( )
{
cout << "Hello C++" <<endl;
return 0;
}
232
C++
Here, you don't need to understand how cout displays 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.
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.
By defining data members only in the private section of the class, the class
author is free to make changes in the data. If the implementation changes, only
the class code needs to be examined to see what affect the change may have. If
data is public, then any function that directly access the data members of the
old representation might be broken.
class Adder{
public:
233
C++
// constructor
Adder(int i = 0)
{
total = i;
}
// interface to outside world
void addNum(int number)
{
total += number;
}
// interface to outside world
int getTotal()
{
return total;
};
private:
// hidden data from outside world
int total;
};
int main( )
{
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
234
C++
Above class adds numbers together, and returns the sum. The public members addNum and getTotal are the interfaces to the outside world and a user needs
to know them to use the class. The private member total is something that the
user doesn't need to know about, but is needed for the class to operate properly.
Designing Strategy
Abstraction separates code into interface and implementation. So while
designing your component, you must keep interface independent of the
implementation so that if you change underlying implementation then interface
would remain intact.
In this case whatever programs are using these interfaces, they would not be
impacted and would just need a recompilation with the latest implementation.
235
C++
All C++ programs are composed of the following two fundamental elements:
Program data: The data is the information of the program which gets
affected by the program functions.
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
};
The variables length, breadth, and height are private. 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 class public (i.e., accessible to other parts of your program),
you must declare them after the public keyword. All variables or functions
236
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.
class Adder{
public:
// constructor
Adder(int i = 0)
{
total = i;
}
// interface to outside world
void addNum(int number)
{
total += number;
}
// interface to outside world
int getTotal()
{
return total;
};
private:
// hidden data from outside world
int total;
};
int main( )
237
C++
{
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
Designing Strategy
Most of us have learnt to make class members private by default unless we
really need to expose them. That's just good encapsulation.
This is applied most frequently to data members, but it applies equally to all
members, including virtual functions.
238
29. INTERFACES
C++
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
};
The purpose of an abstract class (often referred to as an ABC) is to provide an
appropriate base class from which other classes can inherit. Abstract classes
cannot be used to instantiate objects and serves only as an interface.
Attempting to instantiate an object of an abstract class causes a compilation
error.
Thus, if a subclass of an ABC needs to be instantiated, it has to implement each
of the virtual functions, which means that it supports the interface declared by
the ABC. Failure to override a pure virtual function in a derived class, then
attempting to instantiate objects of that class, is a compilation error.
Classes that can be used to instantiate objects are called concrete classes.
C++
// Base class
class Shape
{
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// Derived classes
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
class Triangle: public Shape
{
public:
240
C++
int getArea()
{
return (width * height)/2;
}
};
int main(void)
{
Rectangle Rect;
Triangle
Tri;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total Rectangle area: " << Rect.getArea() << endl;
Tri.setWidth(5);
Tri.setHeight(7);
// Print the area of the object.
cout << "Total Triangle area: " << Tri.getArea() << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Total Rectangle area: 35
Total Triangle area: 17
You can see how an abstract class defined an interface in terms of getArea() and
two other classes implemented same function but with different algorithm to
calculate the area specific to the shape.
Designing Strategy
An object-oriented system might use an abstract base class to provide a
common and standardized interface appropriate for all the external applications.
241
C++
Then, through inheritance from that abstract base class, derived classes are
formed that operate similarly.
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.
242
C++
Description
ofstream
ifstream
fstream
To perform file processing in C++, header files <iostream> and <fstream> must
be included in your C++ source file.
Opening a File
A file must be opened before you can read from it or write to it. Either
ofstream or fstream object may be 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.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened
and the second argument of the open() member function defines the mode in
which the file should be opened.
243
C++
Mode Flag
Description
ios::app
ios::ate
ios::in
ios::out
ios::trunc
You can combine two or more of these values by ORing 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:
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows:
fstream
afile;
Closing a File
When a C++ program terminates it automatically flushes all the streams,
release all the allocated memory and close all the opened files. But it is always a
good practice that a programmer should close all the opened files before
program termination.
Following is the standard syntax for close() function, which is a member of
fstream, ifstream, and ofstream objects.
void close();
244
C++
Writing to a 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
to output information to the screen. The only difference is that you use
an ofstream or fstream object instead of the cout object.
int main ()
{
char data[100];
245
C++
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
return 0;
}
When the above code is compiled and executed, it produces the following
sample input and output:
$./a.out
Writing to the file
246
C++
247
C++
try: A try block identifies a block of code for which particular exceptions
will be activated. It is followed by one or more catch blocks.
C++
Throwing Exceptions
Exceptions can be thrown anywhere within a code block using throw statement.
The operand of the throw statement determines a type for the exception and can
be any expression and the type of the result of the expression determines the
type of exception thrown.
Following is an example of throwing an exception when dividing by zero
condition occurs:
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
Catching Exceptions
The catch block following the try block 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
{
// protected code
}catch( ExceptionName e )
{
// code to handle ExceptionName exception
}
Above code will catch an exception of ExceptionName type. If you want to
specify that a catch block should handle any type of exception that is thrown in a
try block, you must put an ellipsis, ..., between the parentheses enclosing the
exception declaration as follows:
try
{
// protected code
249
C++
}catch(...)
{
// code to handle any exception
}
The following is an example, which throws a division by zero exception and we
catch it in catch block.
#include <iostream>
using namespace std;
int main ()
{
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
}catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}
250
C++
Because we are raising an exception of type const char*, so while catching this
exception, we have to use const char* in catch block. If we compile and run
above code, this would produce the following result:
Division by zero condition!
Description
std::exception
251
C++
std::bad_alloc
std::bad_cast
std::bad_exception
std::bad_typeid
std::logic_error
std::domain_error
std::invalid_argument
std::length_error
std::out_of_range
std::runtime_error
std::overflow_error
std::range_error
std::underflow_error
C++
int main()
{
try
{
throw MyException();
}
catch(MyException& e)
{
std::cout << "MyException caught" << std::endl;
std::cout << e.what() << std::endl;
}
catch(std::exception& e)
{
//Other errors
}
}
This would produce the following result:
MyException caught
C++ Exception
Here, what() is a public method provided by exception class and it has been
overridden by all the child exception classes. This returns the cause of an
exception.
253
C++
The stack: All variables declared inside the function will take up memory
from the stack.
The heap: This is unused memory of the program and can be used to
allocate the memory dynamically when program runs.
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.
= new double;
The memory may not have been allocated successfully, if the free store had
been used up. So it is good practice to check if new operator is returning NULL
pointer and take appropriate action as below:
254
C++
double* pvalue
if( !(pvalue
= NULL;
= new double ))
{
cout << "Error: out of memory." <<endl;
exit(1);
}
The malloc() function from C, still exists in C++, but it is recommended to
avoid using malloc() function. The main advantage of new over malloc() is that
new doesn't just allocate memory, it constructs objects which is prime purpose
of C++.
At any point, when you feel a variable that has been dynamically allocated is not
anymore required, you can free up the memory that it occupies in the free store
with the delete operator as follows:
delete pvalue;
Let us put above concepts and form the following example to show how new and
delete work:
#include <iostream>
using namespace std;
int main ()
{
double* pvalue
pvalue
= new double;
*pvalue = 29494.99;
delete pvalue;
return 0;
}
If we compile and run above code, this would produce the following result:
255
C++
= NULL;
To remove the array that we have just created the statement would look like
this:
delete [] pvalue;
C++
class Box
{
public:
Box() {
cout << "Constructor called!" <<endl;
}
~Box() {
cout << "Destructor called!" <<endl;
}
};
int main( )
{
Box* myBoxArray = new Box[4];
return 0;
}
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.
If we compile and run above code, this would produce the following result:
Constructor called!
Constructor called!
Constructor called!
Constructor called!
Destructor called!
Destructor called!
Destructor called!
Destructor called!
257
33. NAMESPACES
C++
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 mothers or fathers 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 is also having same function xyz(). Now the compiler has no way
of knowing which version of xyz() function you are referring to within your code.
A namespace is designed to overcome this difficulty and is used as additional
information to differentiate similar functions, classes, variables etc. with the
same name available in different libraries. Using namespace, you can define the
context in which names are defined. In essence, a namespace defines a scope.
Defining a Namespace
A namespace definition begins with the keyword namespace followed by the
namespace name as follows:
namespace namespace_name {
// code declarations
}
To call the namespace-enabled version of either function or variable, prepend
(::) the namespace name as follows:
name::code;
Let us see how namespace scope the entities including variable and functions:
#include <iostream>
using namespace std;
C++
return 0;
}
If we compile and run above code, this would produce the following result:
Inside first_space
Inside second_space
C++
}
}
// second name space
namespace second_space{
void func(){
cout << "Inside second_space" << endl;
}
}
using namespace first_space;
int main ()
{
return 0;
}
If we compile and run above code, this would produce the following result:
Inside first_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:
using std::cout;
Subsequent code can refer to cout without prepending the namespace, but other
items in the std namespace will still need to be explicit as follows:
#include <iostream>
using std::cout;
int main ()
{
C++
return 0;
}
If we compile and run above code, this would produce the following result:
std::endl is used with std!
Names introduced in a using directive obey normal scope rules. The name is
visible from the point of the using directive to the end of the scope in which the
directive is found. Entities with the same name defined in an outer scope are
hidden.
Discontiguous Namespaces
A namespace can be defined in several parts and so a namespace is made up of
the sum of its separately defined parts. The separate parts of a namespace can
be spread over multiple files.
So, if one part of the namespace requires a name defined in another file, that
name must still be declared. Writing a following namespace definition either
defines a new namespace or adds new elements to an existing one:
namespace namespace_name {
// code declarations
}
Nested Namespaces
Namespaces can be nested where you can define one namespace inside another
namespace as follows:
namespace namespace_name1 {
// code declarations
namespace namespace_name2 {
// code declarations
}
}
C++
return 0;
}
If we compile and run above code, this would produce the following result:
262
C++
Inside second_space
263
34. TEMPLATES
C++
Function Template
The general form of a template function definition is shown here:
template <class type> ret-type func-name(parameter list)
{
// body of function
}
Here, type is a placeholder name for a data type used by the function. This
name can be used within the function definition.
The following is the example of a function template that returns the maximum of
two values:
#include <iostream>
#include <string>
C++
int i = 39;
int j = 20;
cout << "Max(i, j): " << Max(i, j) << endl;
double f1 = 13.5;
double f2 = 20.7;
cout << "Max(f1, f2): " << Max(f1, f2) << endl;
string s1 = "Hello";
string s2 = "World";
cout << "Max(s1, s2): " << Max(s1, s2) << endl;
return 0;
}
If we compile and run above code, this would produce the following result:
Max(i, j): 39
Max(f1, f2): 20.7
Max(s1, s2): World
Class Template
Just as we can define function templates, we can also define class templates.
The general form of a generic class declaration is shown here:
template <class type> class class-name {
.
.
.
}
Here, type is the placeholder type name, which will be specified when a class is
instantiated. You can define more than one generic data type by using a commaseparated list.
265
C++
// elements
public:
void push(T const&);
// push element
void pop();
// pop element
T top() const;
return elems.empty();
}
};
C++
if (elems.empty()) {
throw out_of_range("Stack<>::pop(): empty stack");
}
// remove last element
elems.pop_back();
}
int main()
{
try {
Stack<int>
intStack;
Stack<string> stringStack;
// stack of ints
// stack of strings
C++
268
35. PREPROCESSOR
C++
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 #include directive 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:
#define PI 3.14159
int main ()
{
return 0;
}
Now, let us do the preprocessing of this code to see the result assuming we have
the source code file. So let us compile it with -E option and redirect the result to
269
C++
test.p. Now, if you check test.p, it will have lots of information and at the
bottom, you will find the value replaced as follows:
$gcc -E test.cpp > test.p
...
int main ()
{
return 0;
}
Function-Like Macros
You can use #define to define a macro which will take argument as follows:
#include <iostream>
using namespace std;
int main ()
{
int i, j;
i = 100;
j = 30;
cout <<"The minimum is " << MIN(i, j) << endl;
return 0;
}
If we compile and run above code, this would produce the following result:
The minimum is 30
270
C++
Conditional Compilation
There are several directives, which can be used to compile selective portions of
your program's source code. This process is called conditional compilation.
The conditional preprocessor construct is much like the if selection structure.
Consider the following preprocessor code:
#ifndef NULL
#define NULL 0
#endif
You can compile a program for debugging purpose. You can also turn on or off
the debugging using a single macro as follows:
#ifdef DEBUG
cerr <<"Variable x = " << x << endl;
#endif
This causes the cerr statement to be compiled in the program if the symbolic
constant DEBUG has been defined before directive #ifdef DEBUG. You can use
#if 0 statement to comment out a portion of the program as follows:
#if 0
code prevented from compiling
#endif
Let us try the following example:
#include <iostream>
using namespace std;
#define DEBUG
int main ()
{
int i, j;
i = 100;
j = 30;
#ifdef DEBUG
271
C++
#if 0
/* This is commented part */
cout << MKSTR(HELLO C++) << endl;
#endif
#ifdef DEBUG
cerr <<"Trace: Coming out of main function" << endl;
#endif
return 0;
}
If we compile and run above code, this would produce the following result:
Trace: Inside main function
The minimum is 30
Trace: Coming out of main function
#define MKSTR( x ) #x
int main ()
{
cout << MKSTR(HELLO C++) << endl;
272
C++
return 0;
}
If we compile and run above code, this would produce the following result:
HELLO C++
Let us see how it worked. It is simple to understand that the C++ preprocessor
turns the line:
cout << MKSTR(HELLO C++) << endl;
Above line will be turned into the following line:
cout << "HELLO C++" << endl;
The ## operator is used to concatenate two tokens. Here is an example:
#define CONCAT( 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>
using namespace std;
#define concat(a, b) a ## b
int main()
{
int xy = 100;
C++
Description
__LINE__
__FILE__
__DATE__
__TIME__
int main ()
{
cout << "Value of __LINE__ : " << __LINE__ << endl;
cout << "Value of __FILE__ : " << __FILE__ << endl;
cout << "Value of __DATE__ : " << __DATE__ << endl;
cout << "Value of __TIME__ : " << __TIME__ << endl;
return 0;
}
274
C++
If we compile and run above code, this would produce the following result:
Value of __LINE__ : 6
Value of __FILE__ : test.cpp
Value of __DATE__ : Feb 28 2011
Value of __TIME__ : 18:52:48
275
C++
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 a
following 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
SIGFPE
SIGILL
SIGINT
SIGSEGV
SIGTERM
C++
#include <iostream>
#include <csignal>
exit(signum);
int main ()
{
// register signal SIGINT and signal handler
signal(SIGINT, signalHandler);
while(1){
cout << "Going to sleep...." << endl;
sleep(1);
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Going to sleep....
Going to sleep....
Going to sleep....
277
C++
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:
Going to sleep....
Going to sleep....
Going to sleep....
Interrupt signal (2) received.
exit(signum);
int main ()
{
int i = 0;
// register signal SIGINT and signal handler
278
C++
signal(SIGINT, signalHandler);
while(++i){
cout << "Going to sleep...." << endl;
if( i == 3 ){
raise( SIGINT);
}
sleep(1);
}
return 0;
}
When the above code is compiled and executed, it produces the following result
and would come out automatically:
Going to sleep....
Going to sleep....
Going to sleep....
Interrupt signal (2) received.
279
37. MULTITHREADING
C++
Creating Threads
The following routine is used to create a POSIX thread:
#include <pthread.h>
pthread_create (thread, attr, start_routine, arg)
Here, pthread_create creates a new thread and makes it executable. This
routine can be called any number of times from anywhere within your code.
Here is the description of the parameters:
Parameter
Description
thread
attr
start_routine
280
C++
created.
arg
Terminating Threads
There is following routine which we use to terminate a POSIX thread:
#include <pthread.h>
pthread_exit (status)
Here pthread_exit is used to explicitly exit a thread. Typically, the
pthread_exit() routine is called after a thread has completed its work and is no
longer required to exist.
If main() finishes before the threads it has created, and exits with
pthread_exit(), the other threads will continue to execute. Otherwise, they will
be automatically terminated when main() finishes.
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>
#define NUM_THREADS
C++
tid = (long)threadid;
cout << "Hello World! Thread ID, " << tid << endl;
pthread_exit(NULL);
}
int main ()
{
pthread_t threads[NUM_THREADS];
int rc;
int i;
for( i=0; i < NUM_THREADS; i++ ){
cout << "main() : creating thread, " << i << endl;
rc = pthread_create(&threads[i], NULL,
PrintHello, (void *)i);
if (rc){
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
pthread_exit(NULL);
}
Compile the following program using -lpthread library as follows:
$gcc test.cpp -lpthread
Now, execute your program which gives the following output:
main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
main() : creating thread, 3
main() : creating thread, 4
Hello World! Thread ID, 0
Hello World! Thread ID, 1
Hello World! Thread ID, 2
282
C++
#define NUM_THREADS
struct thread_data{
int
thread_id;
char *message;
};
pthread_exit(NULL);
}
int main ()
{
283
C++
pthread_t threads[NUM_THREADS];
struct thread_data td[NUM_THREADS];
int rc;
int i;
C++
#define NUM_THREADS
tid = (long)t;
sleep(1);
cout << "Sleeping in thread " << endl;
cout << "Thread with id : " << tid << "
pthread_exit(NULL);
}
int main ()
{
int rc;
int i;
285
C++
pthread_t threads[NUM_THREADS];
pthread_attr_t attr;
void *status;
C++
287
C++
What is CGI?
The Common Gateway Interface, or CGI, is a set of standards that define how
information is exchanged between the web server and a custom script.
The CGI specs are currently maintained by the NCSA and NCSA defines CGI is as
follows:
The Common Gateway Interface, or CGI, is a standard for external gateway
programs to interface with information servers such as HTTP servers.
The current version is CGI/1.1 and CGI/1.2 is under progress.
Web Browsing
To understand the concept of CGI, let's see what happens when we click a
hyperlink to browse a particular web page or URL.
Your browser contacts the HTTP web server and demand for the URL i.e.
filename.
Web Server will parse the URL and will look for the 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.
288
C++
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.
int main ()
{
return 0;
}
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 using chmod 755
cplusplus.cgi UNIX command to make file executable. Now if you
click cplusplus.cgi then this produces the following output:
290
C++
HTTP Header
The line Content-type:text/html\r\n\r\n is a part of HTTP header, which is
sent to the browser to understand the content. All the HTTP header will be in the
following form:
HTTP Field Name: Field Content
For Example
Content-type: text/html\r\n\r\n
There are few other important HTTP headers, which you will use frequently in
your CGI Programming.
Header
Description
Content-type:
Expires: Date
Location: URL
Last-modified: Date
Content-length: N
C++
Set-Cookie: String
Description
CONTENT_TYPE
CONTENT_LENGTH
HTTP_COOKIE
HTTP_USER_AGENT
The
User-Agent
request-header
field
contains
information about the user agent originating the
request. It is a name of the web browser.
PATH_INFO
QUERY_STRING
REMOTE_ADDR
REMOTE_HOST
REQUEST_METHOD
SCRIPT_FILENAME
C++
SCRIPT_NAME
SERVER_NAME
SERVER_SOFTWARE
Here is small CGI program to list out all the CGI variables.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main ()
{
C++
return 0;
}
The output is as follows:
COMSPEC
DOCUMENT_ROOT
/var/www/tutorialspoint
GATEWAY_INTERFACE
CGI/1.1
HTTP_ACCEPT
HTTP_ACCEPT_ENCODING
gzip, deflate
HTTP_ACCEPT_LANGUAGE
en-US
HTTP_CONNECTION
Keep-Alive
HTTP_HOST
www.tutorialspoint.com
HTTP_USER_AGENT
PATH
/sbin:/usr/sbin:/bin:/usr/bin
QUERY_STRING
REMOTE_ADDR
183.82.104.71
294
C++
REMOTE_PORT
50902
REQUEST_METHOD
GET
REQUEST_URI
/cgi-bin/cpp_env.cgi
SCRIPT_FILENAME
/var/www/cgi-bin/cpp_env.cgi
SCRIPT_NAME
/cgi-bin/cpp_env.cgi
SERVER_ADDR
66.135.33.172
SERVER_ADMIN
SERVER_NAME
www.tutorialspoint.com
SERVER_PORT
80
SERVER_PROTOCOL
HTTP/1.1
SERVER_SIGNATURE
SERVER_SOFTWARE
Apache
<
C++
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
server and it produces a long string that appears in your browser's Location: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 up
to 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.
You can pass information by simply concatenating key and value pairs along
with any URL or you can use HTML <FORM> tags to pass information using GET
method.
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
int main ()
{
296
C++
Cgicc formData;
form_iterator fi = formData.getElement("first_name");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "First name: " << **fi << endl;
}else{
cout << "No text entered for first name" << endl;
}
cout << "<br/>\n";
fi = formData.getElement("last_name");
if( !fi->isEmpty() &&fi != (*formData).end()) {
cout << "Last name: " << **fi << endl;
}else{
cout << "No text entered for last name" << endl;
}
cout << "<br/>\n";
return 0;
}
Now, compile the above program as follows:
$g++ -o cpp_get.cgi cpp_get.cpp -lcgicc
Generate cpp_get.cgi and put it in your CGI directory and try to access using
following link:
297
C++
/cgi-bin/cpp_get.cgi?first_name=ZARA&last_name=ALI
This would generate following result:
First name: ZARA
Last name: ALI
<br />
First Name:
Last Name:
Submit
298
C++
First Name:
Submit
Last Name:
Physics
Select Subject
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
299
C++
#include <cgicc/HTMLClasses.h>
int main ()
{
Cgicc formData;
bool maths_flag, physics_flag;
maths_flag = formData.queryCheckbox("maths");
if( maths_flag ) {
cout << "Maths Flag: ON " << endl;
}else{
cout << "Maths Flag: OFF " << endl;
}
cout << "<br/>\n";
physics_flag = formData.queryCheckbox("physics");
if( physics_flag ) {
cout << "Physics Flag: ON " << endl;
}else{
cout << "Physics Flag: OFF " << endl;
}
cout << "<br/>\n";
cout << "</body>\n";
cout << "</html>\n";
300
C++
return 0;
}
Physics
Select Subject
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
C++
int main ()
{
Cgicc formData;
form_iterator fi = formData.getElement("subject");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "Radio box selected: " << **fi << endl;
}
return 0;
}
C++
Submit
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
int main ()
{
Cgicc formData;
C++
form_iterator fi = formData.getElement("textcontent");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "Text Content: " << **fi << endl;
}else{
cout << "No text entered" << endl;
}
return 0;
}
Submit
C++
#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>
int main ()
{
Cgicc formData;
form_iterator fi = formData.getElement("dropdown");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "Value Selected: " << **fi << endl;
}
return 0;
305
C++
How It Works
Your server sends some data to the visitor's browser in
browser may accept the cookie. If it does, it is stored
the visitor's hard drive. Now, when the visitor arrives
site, the cookie is available for retrieval. Once
knows/remembers what was stored.
Expires: This showsthe date the cookie will expire. If this is blank, the
cookie will expire when the visitor quits the browser.
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.
Setting up Cookies
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>
using namespace std;
int main ()
306
C++
return 0;
}
From this example, you must have understood how to set cookies. We use SetCookie 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 "Contenttype:text/html\r\n\r\n.
Compile above program to produce setcookies.cgi, and try to set cookies using
following 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.
307
C++
key1=value1;key2=value2;key3=value3....
Here is an example of how to retrieve cookies.
#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>
int main ()
{
Cgicc cgi;
const_cookie_iterator cci;
C++
cci != env.getCookieList().end();
++cci )
{
cout << "<tr><td>" << cci->getName() << "</td><td>";
cout << cci->getValue();
cout << "</td></tr>\n";
}
cout << "</table><\n";
return 0;
}
Now, compile above program to produce getcookies.cgi, and try to get a list of
all the cookies available at your computer:
/cgi-bin/getcookies.cgi
This will produce a list of all the four cookies set in previous section and all other
cookies set in your computer:
UserID XYZ
Password XYZ123
Domain www.tutorialspoint.com
Path /perl
309
C++
Note: Above example has been disabled intentionally to stop people uploading
files on our server. But you can try above code with your server.
Here is the script cpp_uploadfile.cpp to handle file upload:
#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>
int main ()
{
Cgicc cgi;
C++
return 0;
}
The above example is for writing content at cout stream but you can open your
file stream and save the content of uploaded file in a file at desired location.
Hope you have enjoyed this tutorial. If yes, please send us your feedback.
311
C++
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 wellstructured components:
Component
Description
Containers
Algorithms
Iterators
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>
using namespace std;
int main()
{
312
C++
return 0;
}
When the above code is compiled and executed, it produces the following result:
vector size = 0
extended vector size = 5
value of vec [0] = 0
313
C++
The push_back( ) member function inserts value at the end of the vector,
expanding its size as needed.
314
C++
The Standard Function Library: This library consists of generalpurpose, stand-alone functions that are not part of any class. The function
library is inherited from C.
Standard C++ Library incorporates all the Standard C libraries also, with small
additions and changes to support type safety.
I/O,
Mathematical,
Dynamic allocation,
Miscellaneous,
Wide-character functions
C++
316