C++ Language
C++ Language
C++ Language
ts
ee
Va
C++ program.
rd
Pa
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.
The Standard Template Library (STL) giving a rich set of methods manipulating
data structures, etc.
Va
ts
rd
Learning C++
ee
The ANSI standard has been stable for a while, and all the major C++
compiler manufacturers support the ANSI standard.
Pa
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 softwares that
rely on direct manipulation of hardware under realtime 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++.
Va
ts
rd
ee
instance of a class.
Pa
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;
}
The C++ language defines several headers, which contain information that is
either
necessary
or
useful
to
your
program.
For
this
program,
the
ts
Va
ee
The line int main() is the main function where program execution begins.
The next line cout << "This is my first C++ program."; causes the message
rd
Pa
Open a command prompt and go to the directory where you saved the file.
Type 'g++ hello.cpp ' and press enter to compile your code. If there are no
errors in your code the command prompt will take you to the next line and
would generate a.out executable file.
You will be able to see ' Hello World ' printed on the window.
$ g++ hello.cpp
$ ./a.out
Hello World
ts
Make sure that g++ is in your path and that you are running it in the
directory containing file hello.cpp.
You can compile C/C++ programs using makefile. For more details, you can
Va
ee
rd
x = y;
Pa
y = y+1;
add(x, y);
C++ does not recognize the end of the line as a terminator. For this reason,
it does not matter where on a line you put a statement. For example:
x = y;
y = y+1;
add(x, y);
is the same as
x = y; y = y+1; add(x, y);
C++ Identifiers:
Va
ts
ee
zara
abc
myname50
_temp
move_name
a_123
a23b9
retVal
Pa
mohd
rd
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
auto
enum
operator
throw
bool
explicit
private
true
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
continue
if
sizeof
default
inline
delete
int
do
using
virtual
void
static_cast
volatile
long
struct
wchar_t
double
mutable
switch
while
dynamic_cast
namespace
template
rd
static
Pa
ee
Va
ts
break
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.
Replacement
??=
??/
??'
??(
??)
??!
Va
ts
Trigraph
ee
??>
??-
rd
Pa
??<
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.
ts
Va
purpose.
Comments in C++
ee
Program comments are explanatory statements that you can include in the
Pa
rd
C++ code that you write and helps anyone reading it's 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 */
also
A comment can also start with //, extending to the end of the line. For
example:
#include <iostream>
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:
ts
Hello World
ee
Va
a // comment, /* and */ have no special meaning. Thus, you can "nest" one
kind of comment within the other kind. For example:
*/
Pa
rd
Keyword
Boolean
bool
Character
char
Integer
int
Floating point
float
double
ee
Va
Type
ts
Pa
Wide character
void
rd
Valueless
wchar_t
Several of the basic types can be modified using one or more of these type
modifiers:
signed
unsigned
short
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.
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
Range
long int
4bytes
-2,147,483,648 to 2,147,483,647
4bytes
4bytes
0 to 4,294,967,295
float
4bytes
double
8bytes
ee
Va
ts
Type
Pa
rd
0 to 65,535
-32768 to 32767
long double
8bytes
wchar_t
2 or 4 bytes
1 wide character
The sizes 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>
ts
int main()
Va
ee
cout << "Size of short int : " << sizeof(short int) << endl;
rd
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
Pa
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() operator 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
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:
typedef type newname;
ts
For example, the following tells the compiler that feet is another name for
int:
Va
ee
feet distance;
rd
Enumerated Types:
Pa
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, 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.
ts
Va
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.
ee
Pa
rd
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,
Reference, Data structures, and Classes.
Pointer,
Array,
Va
ts
Following section will cover how to define, declare and use various types of
variables.
ee
A variable definition means to tell the compiler where and how much to
create the storage for the variable. A variable definition specifies a data
Pa
type variable_list;
rd
type, and contains a list of one or more variables of that type as follows:
Here, type must be a valid C++ data type including char, w_char, int, float,
double, bool or any user-defined object, etc., and variable_list may
consist of one or more identifier names separated by commas. Some valid
declarations are shown here:
int
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.
// declaration of d and f.
int d = 3, f = 5;
byte z = 22;
char x = 'x';
Va
ts
ee
Pa
rd
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>
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main ()
{
// Variable definition:
int a, b;
int c;
Va
ts
float f;
// actual initialization
a = 10;
ee
b = 20;
f = 70.0/3.0;
Pa
rd
c = a + b;
return 0;
}
When the above code is compiled and executed, it produces the following
result:
30
23.3333
int main()
{
// function call
int i = func();
ts
Va
// function definition
int func()
{
return 0;
ee
rd
Pa
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.
Va
ts
ee
Local Variables:
Pa
rd
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;
}
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 lifetime of your program.
ts
A global variable can be accessed by any function. That is, a global variable
Va
is available for use throughout your entire program after its declaration.
Following is the example using global and local variables:
ee
#include <iostream>
int g;
Pa
int main ()
{
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
rd
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;
ts
int main ()
Va
{
// Local variable declaration:
ee
int g = 10;
Pa
return 0;
rd
cout << g;
When the above code is compiled and executed, it produces the following
result:
10
Initializer
int
char
'\0'
float
double
pointer
NULL
ts
Va
C++ Constants/Literals
ee
Constants refer to fixed values that the program may not alter and they are
called literals.
Pa
rd
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
Va
85
ts
Floating-point literals:
ee
rd
Pa
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 inwchar_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.
Va
ts
\\
rd
Meaning
Pa
Escape sequence
ee
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:
\ character
\'
' character
\"
" character
\?
? character
\a
Alert or bell
Backspace
\f
Form feed
\n
Newline
\r
Carriage return
\t
Horizontal tab
\v
Vertical tab
\ooo
\xhh . . .
ee
Va
ts
\b
rd
Pa
#include <iostream>
int main()
{
cout << "Hello\tWorld\n\n";
return 0;
}
When the above code is compiled and executed, it produces the following
result:
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"
Va
ts
"hello, \
dear"
ee
rd
Defining Constants:
Pa
#define LENGTH 10
#define WIDTH
int main()
{
int area;
ts
Va
When the above code is compiled and executed, it produces the following
result:
ee
50
rd
Pa
You can use const prefix to declare constants with a specific type as
follows:
const type variable = value;
int main()
{
const int
LENGTH = 10;
const int
WIDTH
= 5;
When the above code is compiled and executed, it produces the following
result:
50
ts
Va
ee
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.
signed
unsigned
long
short
Pa
rd
as
prefix
C++
allows
a
shorthand
notation
short, or longintegers. You can simply
for
use
declaring unsigned,
the word unsigned,
short, or long, without the int. The int is implied. For example, the
following two statements both declare unsigned integer variables.
unsigned x;
unsigned int y;
To understand the difference between the way that signed and unsigned
integer modifiers are interpreted by C++, you should run the following
short program:
#include <iostream>
ts
Va
*/
ee
int main()
{
Pa
j = 50000;
rd
short int i;
i = j;
cout << i << " " << j;
return 0;
}
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.
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
rd
ee
Va
ts
Qualifier
Pa
auto
register
static
extern
mutable
The example above defines two variables with the same storage class, auto
can only be used within functions, i.e., local variables.
Va
ts
The register storage class is used to define local variables that should be
stored in a register instead of RAM. This means that the variable has a
maximum size equal to the register size (usually one word) and can't have
the unary '&' operator applied to it (as it does not have a memory location).
register int
ee
{
miles;
rd
Pa
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.
The static modifier may also be applied to global variables. When this is
done, it causes that variable's scope to be restricted to the file in which it is
declared.
In C++, when static is used on a class data member, it causes only one
copy of that member to be shared by all objects of its class.
#include <iostream>
// Function declaration
void func(void);
ts
Va
main()
{
while(count--)
ee
{
func();
rd
}
// Function definition
Pa
return 0;
When the above code is compiled and executed, it produces the following
result:
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
Va
ts
ee
When you have multiple files and you define a global variable or function,
which will be used in other files also, then extern will be used in another file
to give reference of defined variable or function. Just for
Pa
rd
int count ;
extern void write_extern();
main()
{
count = 5;
write_extern();
}
void write_extern(void)
{
std::cout << "Count is " << count << std::endl;
ts
Here, extern keyword is being used to declare count in another file. Now
Va
ee
This will produce write executable program, try to execute write and check
Pa
$./write
rd
Operators in C++
An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations. C++ is rich in built-in operators and
provides the following types of operators:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
Va
ts
ee
Arithmetic Operators:
rd
Show Examples
Pa
Operator
Description
Example
A + B will give 30
B / A will give 2
B % A will give 0
++
--
ts
Relational Operators:
Va
ee
Show Examples
Description
==
(A == B) is not true.
!=
(A != B) is true.
>
Pa
rd
Operator
Example
(A < B) is true.
>=
<=
(A <= B) is true.
ts
<
Va
Logical Operators:
Show Examples
rd
ee
Description
&&
(A && B) is false.
||
(A || B) is true.
Pa
Operator
Example
make false.
Bitwise Operators:
Bitwise operator works on bits and perform bit-by-bit operation. The truth
tables for &, |, and ^ are as follows:
q
p&q
p|q
p^q
ee
Va
ts
B = 0000 1101
-----------------
Pa
A = 0011 1100
rd
Assume if A = 60; and B = 13; now in binary format they will be as follows:
Description
Example
&
<<
>>
Pa
rd
ee
Va
ts
Operator
Assignment Operators:
There are following assignment operators supported by C++ language:
Show Examples
Operator
Description
Example
+=
C += A is equivalent to C = C + A
-=
C -= A is equivalent to C = C - A
*=
C *= A is equivalent to C = C * A
/=
C /= A is equivalent to C = C / A
%=
C %= A is equivalent to C = C %
A
<<=
>>=
Pa
rd
ee
Va
ts
&=
^=
C ^= 2 is same as C = C ^ 2
|=
C |= 2 is same as C = C | 2
Misc Operators
There are few other operators supported by C++ Language.
Description
sizeof
Condition ? X : Y
Pa
rd
ee
Va
ts
Operator
Cast
&
Va
ts
Here, operators with the highest precedence appear at the top of the table,
those with the lowest appear at the bottom. Within an expression, higher
precedence operators will be evaluated first.
ee
Show Examples
Operator
Postfix
() [] -> . ++ - -
Left to right
Unary
Right to left
Multiplicative
*/%
Left to right
Additive
+-
Left to right
Shift
<< >>
Left to right
Relational
Left to right
Pa
rd
Category
Associativity
== !=
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
?:
Assignment
Comma
Pa
rd
ee
Va
ts
Equality
Right to left
Right to left
Left to right
Pa
rd
ee
Va
ts
Description
while loop
for loop
do...while loop
nested loops
You can use one or more loop inside any another while,
for or do..while loop.
ts
execution leaves a scope, all automatic objects that were created in that
scope are destroyed.
Va
C++ supports the following control statements. Click the following links to
check their detail.
Description
break statement
goto statement
ee
rd
Pa
continue statement
Control Statement
int main ()
{
for( ; ; )
{
printf("This loop will run forever.\n");
}
return 0;
ts
Va
rd
ee
Pa
ts
Va
if statement
if...else statement
Pa
rd
ee
Statement
switch statement
nested if statements
nested
statements
switch
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;
Where 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 ?
ts
expression. If Exp1 is false, then Exp3 is evaluated and its value becomes
the value of the expression.
Va
C++ Functions
ee
Pa
rd
You can divide up your code into separate functions. How you divide up
your code among different functions is up to you, but logically the division
usually is so each function performs a specific task.
A function declaration tells the compiler about a function's name, return
type, and parameters. A function definition provides the actual body of the
function.
The C++ standard library provides numerous built-in functions that your
program can call. For example, function strcat() to concatenate two
strings, function memcpy() to copy one memory location to another
location and many more functions.
A function is knows as with various names like a method or a sub-routine or
a procedure etc.
Defining a Function:
The general form of a C++ function definition is as follows:
return_type function_name( parameter list )
{
body of the function
}
Return Type: A function may return a value. The return_type is the data type
of the value the function returns. Some functions perform the desired
ts
Va
keyword void.
Function Name: This is the actual name of the function. The function name and
ee
rd
Pa
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:
Va
ts
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.
ee
Pa
rd
For the above defined function max(), following is the function declaration:
Parameter names are not importan in function declaration only their type is
required, so following is also valid declaration:
int max(int, int);
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.
// function declaration
Va
ts
int main ()
ee
rd
int b = 200;
Pa
int ret;
return 0;
}
int result;
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:
ts
Va
Function Arguments:
ee
Pa
rd
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
Call by value
Call by pointer
Description
argument.
Call by reference
ts
Va
ee
This is done by using the assignment operator and assigning values for the
arguments in the function definition. If a value for that parameter is not
#include <iostream>
using namespace std;
result = a + b;
return (result);
}
Pa
rd
passed when the function is called, the default given value is used, but if a
value is specified, this default value is ignored and the passed value is used
instead. Consider the following example:
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int result;
return 0;
Va
ts
result = sum(a);
ee
Pa
rd
When the above code is compiled and executed, it produces the following
result:
Numbers in 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.
#include <iostream>
using namespace std;
int main ()
{
// number definition:
short
s;
int
i;
long
l;
float
f;
double d;
ts
// number assignments;
Va
s = 10;
i = 1000;
l = 1000000;
ee
f = 230.47;
Pa
// number printing;
rd
d = 30949.374;
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
down
To
ts
utilize
these
functions
you
need
double cos(double);
built-in
math
header
the
rd
ee
S.N.
include
useful
Va
file <cmath>.
to
some
Pa
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.
3
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.
The first is a number you wish to raise and the second is the power you
wish to raise it t
6
double sqrt(double);
You pass this function a number and it gives you this square root.
int abs(int);
ts
Va
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
rd
ee
it.
double floor(double);
Pa
10
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;
double d = 200.374;
// mathematical operations;
cout << "sin(d) :" << sin(d) << endl;
cout << "abs(i)
return 0;
ts
When the above code is compiled and executed, it produces the following
Va
result:
:1000
ee
abs(i)
sign(d) :-0.634939
floor(d) :200
rd
sqrt(f) :15.1812
Pa
pow( d, 2 ) :40149.7
#include <cstdlib>
int main ()
{
int i,j;
/* generate 10
random numbers. */
ts
Va
{
// generate actual random number
j= rand();
ee
rd
Pa
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
C++ Arrays
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, ...,
ts
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.
Va
ee
Declaring Arrays:
corresponds to the first element and the highest address to the last
element.
Pa
rd
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 { } can not 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};
You will create exactly the same array as you did in the previous example.
balance[4] = 50.0;
Va
ts
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 representaion of the same array we discussed
rd
ee
above:
Pa
The above statement will take 10th element from the array and assign the
value to salary variable. Following is an example, which will use all the
above-mentioned three concepts viz. declaration, assignment and accessing
arrays:
#include <iostream>
using namespace std;
#include <iomanip>
using std::setw;
int main ()
{
int n[ 10 ]; // n is an array of 10 integers
ts
Va
ee
rd
Pa
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
Multi-dimensional arrays
ts
Concept
ee
Return
functions
array
Pa
rd
Va
Pointer to an array
from
C++ Strings
C++ provides following two types of string representations:
ts
If you follow the rule of array initialization, then you can write the above
Va
statement as follows:
Pa
rd
ee
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>
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
return 0;
}
ts
strcpy(s1, s2);
ee
rd
Pa
S.N.
Va
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);
Returns a pointer to the first occurrence of string s2 in string s1.
ts
Va
int main ()
{
ee
len ;
Pa
int
rd
char str3[10];
cout << "strcpy( str3, str1) : " << str3 << endl;
return 0;
ts
study this class in C++ Standard Library but for now let us check following
example:
Va
At this point, you may not understand this example because so far we have
ee
not discussed Classes and Objects. So can have a look and proceed until
you have understanding on Object Oriented Concepts.
#include <iostream>
int main ()
Pa
rd
#include <string>
{
string str1 = "Hello";
string str2 = "World";
string str3;
int
len ;
return 0;
}
ts
Va
str3 : Hello
str1 + str2 : HelloWorld
10
ee
str3.size() :
rd
C++ Pointers
Pa
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;
}
Va
ts
ee
type *var-name;
Pa
rd
Here, type is the pointer's base type; it must be a valid C++ type and varname is the name of the pointer variable. The asterisk you used to declare
a pointer is the same asterisk that you use for multiplication. However, in
this statement the asterisk is being used to designate a variable as a
pointer. Following are the valid pointer declaration:
int
*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.
ts
available in the pointer variable. This is done by using unary operator * that
returns the value of the variable located at the address specified by its
operand. Following example makes use of these operations:
Va
#include <iostream>
ee
int main ()
rd
{
var = 20;
int
*ip;
// pointer variable
ip = &var;
Pa
int
return 0;
}
Va
ts
Pointers have many but easy concepts and they are very important to C++
programming. There are following few important pointer concepts which
Description
Pa
rd
ee
Concept
Passing
pointers
to
functions
Return
pointer
functions
from
C++ References
Va
ts
You cannot have NULL references. You must always be able to assume that a
rd
ee
References are often confused with pointers but three major differences
between references and pointers are:
Pa
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>
ts
int main ()
Va
{
// declare simple variables
int
i;
r = i;
double& s = d;
i = 5;
Pa
int&
rd
ee
double d;
<< endl;
d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s
return 0;
}
<< endl;
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:
Description
References as parameters
rd
ee
Va
ts
Concept
Pa
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
ee
SN
Va
ts
Following are the important functions, which we use while working with
date and time in C or C++. All these functions are part of standard C and
C++ library and you can check their detail using reference to C++ standard
library given below.
rd
This returns the current calendar time of the system in number of seconds
Pa
returns
pointer
to
string
of
the
form day
month
year
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.
5
Va
ts
This returns the calendar-time equivalent of the time found in the structure
rd
ee
pointed to by time.
Pa
This function calculates the difference in seconds between time1 and time2.
size_t strftime();
This function can be used to format date and time a specific format.
int main( )
{
// current date/time based on current system
time_t now = time(0);
cout << "The local date and time is: " << dt << endl;
ts
tm *gmtm = gmtime(&now);
Va
dt = asctime(gmtm);
cout << "The UTC date and time is:"<< dt << endl;
ee
When the above code is compiled and executed, it produces the following
rd
result:
8 20:07:41 2011
Pa
9 03:07:41 2011
#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;
Va
ts
tm *ltm = localtime(&now);
ee
rd
Pa
When the above code is compiled and executed, it produces the following
result:
Number of sec since January 1, 1970:1294548238
Year: 2011
Month: 1
Day: 8
Time: 22: 44:59
ts
Va
<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>
Pa
rd
ee
Header File
stream insertion operator, which is written as << which are two less than
signs as shown in the following example.
#include <iostream>
int main( )
{
char str[] = "Hello C++";
ts
Va
When the above code is compiled and executed, it produces the following
result:
ee
The C++ compiler also determines the data type of variable to be output
Pa
rd
and selects the appropriate stream insertion operator to display the value.
The << operator is overloaded to output data items of built-in types
integer, float, double, strings and pointer values.
The insertion operator << may be used more than once in a single
statement as shown above and endl is used to add a new-line at the end of
the line.
int main( )
{
char name[50];
ts
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 result something as
Va
follows:
ee
Pa
rd
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;
screen but the object cerr is un-buffered and each stream insertion to cerr
causes its output to appear immediately.
The cerr is also used in conjunction with the stream insertion operator as
shown in the following example.
#include <iostream>
int main( )
{
Va
ts
rd
ee
When the above code is compiled and executed, it produces the following
result:
Pa
int main( )
{
char str[] = "Unable to read....";
When the above code is compiled and executed, it produces the following
result:
Error message : Unable to read....
ts
You would not be able to see any difference in cout, cerr and clog with
these small examples, but while writing and executing big programs then
difference becomes obvious. So this is good practice to display error
rd
ee
Va
messages using cerr stream and while displaying other log messages then
clog should be used.
Pa
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];
ts
ee
Va
char
title[50];
char
author[50];
char
subject[100];
int
book_id;
Pa
rd
struct Books
}book;
#include <cstring>
struct Books
{
char
title[50];
char
author[50];
char
subject[100];
int
book_id;
};
ts
int main( )
Va
ee
// book 1 specification
rd
Pa
// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
return 0;
}
ts
When the above code is compiled and executed, it produces the following
result:
Va
ee
Book 1 id : 6495407
Pa
rd
struct Books
{
char
title[50];
char
author[50];
char
subject[100];
int
book_id;
};
int main( )
{
struct Books Book1;
rd
ee
Book1.book_id = 6495407;
// book 2 specification
Va
ts
// book 1 specification
Pa
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
ts
Book id : 6495407
Va
ee
Book id : 6495700
rd
Pointers to Structures:
Pa
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;
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
title[50];
char
author[50];
char
subject[100];
int
book_id;
Va
char
ts
};
ee
int main( )
rd
Pa
// Book 1 specification
// Book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
return 0;
}
// This function accept pointer to structure as parameter.
void printBook( struct Books *book )
Va
ts
ee
Pa
rd
When the above code is compiled and executed, it produces the following
result:
Book title : Learn C++ Programming
Book author : Chand Miyan
{
char
title[50];
char
author[50];
char
subject[100];
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;
Va
ts
pint32 x, y, z;
ee
rd
types.
Pa
A class definition starts with the keyword class followed by the class name;
and the class body, enclosed by a pair of curly braces. A class definition
must be followed either by a semicolon or a list of declarations. For
example, we defined the Box data type using the keyword class as follows:
class Box
{
public:
double length;
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
};
Va
ts
ee
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.
Pa
rd
Box Box2;
Both of the objects Box1 and Box2 will have their own copy of data
members.
#include <iostream>
class Box
{
public:
double length;
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
};
{
// Declare Box1 of type Box
Box Box2;
Box Box1;
// box 1 specification
Box1.breadth = 7.0;
Pa
Box1.height = 5.0;
ee
rd
Box1.length = 6.0;
Va
ts
int main( )
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// 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;
When the above code is compiled and executed, it produces the following
result:
Volume of Box1 : 210
Volume of Box2 : 1560
ts
accessed directly using direct member access operator (.). We will learn
how private and protected members can be accessed.
ee
Va
So far, you have got very basic idea about C++ Classes and Objects. There
are further interesting concepts related to C++ Classes and Objects which
we will discuss in various sub-sections listed below:
Description
Pa
rd
Concept
ee
Va
ts
rd
C++ Inheritance
Pa
Where access-specifier is one of public, protected, or private, and baseclass is the name of a previously defined class. If the access-specifier is not
used, then it is private by default.
ts
Consider a base class Shape and its derived class Rectangle as follows:
Va
#include <iostream>
ee
// Base class
class Shape
rd
Pa
public:
void setWidth(int w)
{
width = w;
}
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)
{
Va
ts
Rectangle Rect;
Rect.setWidth(5);
ee
Rect.setHeight(7);
return 0;
}
Pa
rd
When the above code is compiled and executed, it produces the following
result:
Total area: 35
Access
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:
Constructors, destructors and copy constructors of the base class.
Va
ee
Type of Inheritance:
ts
Pa
rd
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:
Public
Inheritance: When
deriving
class
from
a public base
class,public members of the base class become public members of the derived
class and protected members of the base class becomeprotected members of
the derived class. A base class's privatemembers are never accessible directly
from
derived
class,
but
can
be
accessed
through
calls
to
Protected
Inheritance: When
deriving
of
from
the
a protected base
base
class
Private
Inheritance: When
deriving
of
from
the
a private base
base
class
Multiple Inheritances:
A C++ class can inherit members from more than one class and here is the
extended syntax:
class derived-class: access baseA, access baseB....
ts
for every base class and they will be separated by comma as shown above.
Let us try the following example:
Va
#include <iostream>
ee
rd
Pa
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape, public PaintCost
ts
Va
public:
int getArea()
ee
int main(void)
{
Pa
rd
};
Rectangle Rect;
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
return 0;
}
When the above code is compiled and executed, it produces the following
result:
Total area: 35
ts
Va
ee
C++ allows you to specify more than one definition for a function name or
called function
rd
anoperator in
the
same
scope,
which
is
overloading andoperator overloading respectively.
Pa
ts
class printData
public:
void print(int i) {
Va
f) {
rd
void print(double
ee
Pa
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
ts
Va
ee
Pa
rd
declares the addition operator that can be used to add two Box objects and
returns final Box object. Most overloaded operators may be defined as
ordinary non-member functions or as class member functions. In case we
define above function as non-member function of a class then we would
have to pass two arguments for each operand as follows:
Box operator+(const Box&, const Box&);
Following is the example to show the concept of operator over loading using
a member function. Here an object is passed as an argument whose
properties will be accessed using this object, the object which will call this
operator can be accessed using this operator as explained below:
#include <iostream>
using namespace std;
class Box
{
public:
double getVolume(void)
{
ts
Va
}
void setLength( double len )
{
length = len;
rd
ee
{
breadth = bre;
}
Pa
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
};
// Main function for the program
int main( )
{
// Declare Box1 of type Box
Box Box2;
Box Box3;
Va
p
ee
// box 1 specification
rd
Box1.setLength(6.0);
Pa
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
ts
Box Box1;
// 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();
// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
return 0;
}
Va
ts
When the above code is compiled and executed, it produces the following
result:
Volume of Box1 : 210
ee
rd
Overloadable/Non-overloadableOperators:
+
Pa
&
<
>
<=
>=
++
--
<<
>>
==
!=
&&
||
+=
-=
/=
%=
^=
&=
|=
*=
<<=
>>=
[]
()
->
->*
new
new []
delete
delete []
.*
?:
ts
examples
Va
p
ee
rd
Pa
S.N.
overloading
to
help
you
in
Va
ts
ee
Polymorphism in C++
Pa
rd
The
word polymorphism means
having
many
forms.
Typically,
polymorphism occurs when there is a hierarchy of classes and they are
related by inheritance.
C++ polymorphism means that a call to a member function will cause a
different function to be executed depending on the type of object that
invokes the function.
Consider the following example where a base class has been derived by
other two classes:
#include <iostream>
using namespace std;
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;
}
};
ts
Va
public:
int area ()
ee
rd
Pa
}
};
Shape *shape;
Rectangle rec(10,7);
Triangle
tri(10,5);
Va
ts
shape->area();
return 0;
ee
When the above code is compiled and executed, it produces the following
Pa
rd
result:
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 calledstatic 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
compilation of the program.
area()
function is set
during the
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:
ts
};
Va
After this slight modification, when the previous example code is compiled
and executed, it produces the following result:
ee
Pa
rd
This time, the compiler looks at the contents of the pointer instead of it's
type. Hence, since addresses of objects of tri and rec classes are stored in
*shape the respective area() function is called.
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.
ts
protected:
Va
ee
{
width = a;
Pa
rd
height = b;
The = 0 tells the compiler that the function has no body and above virtual
function will be called pure virtual function.
Let's take one real life example of a TV, which you can turn on and off,
change the channel, adjust the volume, and add external components such
as speakers, VCRs, and DVD players, BUT you do not know its internal
details, that is, you do not know how it receives signals over the air or
through a cable, how it translates them, and finally displays them on the
screen.
Thus, we can say a television clearly separates its internal implementation
from its external interface and you can play with its interfaces like the
power button, channel changer, and volume control without having zero
knowledge of its internals.
ts
Va
object data, i.e., state without actually knowing how class has been
implemented internally.
ee
For example, your program can make a call to the sort() function without
knowing what algorithm the function actually uses to sort the given values.
Pa
rd
int main( )
{
cout << "Hello C++" <<endl;
return 0;
}
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
ts
type.
Va
There are no restrictions on how often an access label may appear. Each
ee
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.
rd
Pa
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 are public, then any function that directly accesses the
data members of the old representation might be broken.
class Adder{
public:
// constructor
Adder(int i = 0)
ts
Va
total = i;
}
ee
Pa
total += number;
rd
a.addNum(10);
a.addNum(20);
a.addNum(30);
When the above code is compiled and executed, it produces the following
result:
Total 60
ts
Above class adds numbers together, and returns the sum. The public
membersaddNum and getTotal are the interfaces to the outside world and
ee
Designing Strategy:
Va
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.
Pa
rd
ts
Va
C++ supports the properties of encapsulation and data hiding through the
ee
rd
Pa
public:
double getVolume(void)
{
// 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.
ts
Va
#include <iostream>
using namespace std;
class Adder{
ee
public:
rd
// constructor
{
total = i;
}
Pa
Adder(int i = 0)
private:
// hidden data from outside world
int total;
};
int main( )
{
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
ts
Va
return 0;
}
rd
Total 60
ee
When the above code is compiled and executed, it produces the following
result:
Pa
Above class adds numbers together, and returns the sum. The public
membersaddNum 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 is hidden from the outside world, but is needed for the class
to operate properly.
Designing Strategy:
Most of us have learned through bitter experience to make class members
private by default unless we really need to expose them. That's just
goodencapsulation.
This wisdom is applied most frequently to data members, but it applies
equally to all members, including virtual functions.
ts
Va
public:
// pure virtual function
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
rd
double length;
Pa
};
ee
private:
// Base class
ts
class Shape
Va
{
public:
ee
void setWidth(int w)
rd
}
void setHeight(int h)
{
Pa
width = w;
height = h;
}
protected:
int width;
int height;
};
// Derived classes
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
class Triangle: public Shape
{
public:
int getArea()
{
return (width * height)/2;
}
Va
ts
};
int main(void)
Rect.setWidth(5);
Rect.setHeight(7);
rd
Tri;
Pa
Triangle
ee
Rectangle Rect;
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
Designing Strategy:
Va
ts
ee
Pa
rd
Description
ofstream
ifstream
fstream
ts
Data Type
Va
Opening a File:
ee
A file must be opened before you can read from it or write to it. Either
rd
theofstream 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.
Pa
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.
Mode Flag
Description
ios::app
ios::ate
ios::in
ios::out
ios::trunc
ofstream outfile;
Va
ts
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 it already exists, following will be the syntax:
afile;
rd
fstream
ee
Similar way, you can open a file for reading and writing purpose as follows:
Pa
Closing a File
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 anofstream or fstream object instead of the cout object.
you
use
Va
ts
#include <iostream>
ee
rd
int main ()
char data[100];
Pa
ts
ifstream infile;
Va
infile.open("afile.dat");
rd
ee
Pa
// 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
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9
Above examples make use of additional functions from cin object, like
getline() function to read the line from outside and ignore() function to
ignore the extra characters left by previous read statement.
ts
Both istream and ostream provide member functions for repositioning the
Va
file-position pointer. These member functions are seekg ("seek get") for
istream and seekp ("seek put") for ostream.
ee
Pa
rd
Va
ts
fileObject.seekg( 0, ios::end );
ee
Pa
rd
throw: A program throws an exception when a problem shows up. This is done
using a throw keyword.
try: A try block identifies a block of code for which particular exceptions will be
activated. It's followed by one or more catch blocks.
ts
}catch( ExceptionName e2 )
{
Va
// catch block
}catch( ExceptionName eN )
ee
// catch block
rd
Pa
You can list down multiple catch statements to catch different type of
exceptions in case your try block raises more than one exception in
different situations.
Throwing Exceptions:
Exceptions
can
be
thrown
anywhere
within
a
code
block
using throwstatements. The operand of the throw statements 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.
ts
try
{
Va
// protected code
ee
}catch( ExceptionName e )
rd
Pa
#include <iostream>
using namespace std;
ts
int main ()
Va
{
int x = 50;
int y = 0;
ee
double z = 0;
rd
try {
Pa
z = division(x, y);
return 0;
}
Pa
rd
ee
Va
ts
Description
std::exception
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
Pa
rd
ee
Va
ts
std::bad_alloc
std::runtime_error
std::overflow_error
std::range_error
std::underflow_error
ts
Va
{
return "C++ Exception";
ee
};
rd
int main()
try
{
Pa
throw MyException();
}
catch(MyException& e)
{
std::cout << "MyException caught" << std::endl;
std::cout << e.what() << std::endl;
}
catch(std::exception& e)
{
//Other errors
}
Va
ts
The stack: All variables declared inside the function will take up memory from
The heap: This is unused memory of the program and can be used to allocate
rd
ee
the stack.
Pa
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
usedelete operator, which de-allocates memory previously allocated by
new operator.
Here, data-type could be any built-in data type including an array or any
user defined data types include class or structure. Let us start with built-in
data types. For example we can define a pointer to type double and then
request that the memory be allocated at execution time. We can do this
using the newoperator with the following statements:
double* pvalue
= new double;
ts
pvalue
Va
The memory may not have been allocated successfully, if the free store had
= new double ))
rd
if( !(pvalue
= NULL;
ee
double* pvalue
exit(1);
Pa
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;
Va
ts
ee
Pa
rd
If we compile and run above code, this would produce the following result:
= NULL;
To remove the array that we have just created the statement would look
like this:
delete [] pvalue;
Following the similar generic syntax of new operator, you can allocat for a
multi-dimensional array as follows:
double** pvalue
pvalue
= NULL;
However, the syntax to release the memory for multi-dimensional array will
still remain same as above:
delete [] pvalue;
Va
ts
Objects are no different from simple data types. For example, consider the
following code where we are going to use an array of objects to clarify the
concept:
#include <iostream>
ee
class Box
rd
Box() {
Pa
public:
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!
ts
Constructor called!
Va
Destructor called!
Destructor called!
Destructor called!
ee
Destructor called!
rd
Namespaces in C++
Pa
Consider a situation, when we have two persons with the same name, Zara,
in the same class. Whenever we need to differentiate them definitely we
would have to use some additional information along with their name, like
either the area if they live in different area or their mother or father 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
}
Va
name::code;
ts
Let us see how namespace scope the entities including variable and
functions:
ee
#include <iostream>
namespace first_space{
void func(){
Pa
rd
return 0;
}
If we compile and run above code, this would produce the following result:
Inside first_space
ts
Inside second_space
Va
ee
Pa
#include <iostream>
rd
}
using namespace first_space;
int main ()
{
return 0;
}
If we compile and run above code, this would produce the following result:
ts
Inside first_space
ee
Va
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;
#include <iostream>
Pa
rd
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:
using std::cout;
int main ()
{
return 0;
}
If we compile and run above code, this would produce the following result:
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.
Va
ts
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
ee
rd
Nested Namespaces:
Pa
Namespaces can be nested where you can define one namespace inside
another name space as follows:
namespace namespace_name1 {
// code declarations
namespace namespace_name2 {
// code declarations
}
}
ts
Va
void func(){
ee
Pa
rd
return 0;
}
If we compile and run above code, this would produce the following result:
Inside second_space
C++ Templates
Templates are the foundation of generic programming, which involves
writing code in a way that is independent of any particular type.
A template is a blueprint or formula for creating a generic class or a
function. The library containers like iterators and algorithms are examples
of generic programming and have been developed using template concept.
There is a single definition of each container, such as vector, but we can
define many different kinds of vectors for example, vector <int> or vector
<string>.
ts
You can use templates to define functions as well as classes, let us see how
do they work:
Va
Function Template:
ee
Pa
// body of function
rd
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>
{
return a < b ? b:a;
}
int main ()
{
int i = 39;
int j = 20;
cout << "Max(i, j): " << Max(i, j) << endl;
double f1 = 13.5;
Va
cout << "Max(f1, f2): " << Max(f1, f2) << endl;
ts
double f2 = 20.7;
string s1 = "Hello";
string s2 = "World";
ee
cout << "Max(s1, s2): " << Max(s1, s2) << endl;
rd
return 0;
Pa
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 comma-separated list.
Following is the example to define class Stack<> and implement generic
methods to push and pop the elements from the stack:
#include <iostream>
#include <vector>
#include <cstdlib>
ts
#include <string>
Va
#include <stdexcept>
ee
rd
class Stack {
private:
public:
void push(T const&);
// elements
Pa
vector<T> elems;
// push element
void pop();
// pop element
T top() const;
return elems.empty();
}
};
Va
ts
T Stack<T>::top () const
ee
{
if (elems.empty()) {
rd
Pa
int main()
{
try {
Stack<int>
intStack;
Stack<string> stringStack;
// stack of ints
// stack of strings
ts
Va
If we compile and run above code, this would produce the following result:
7
Pa
rd
ee
hello
C++ Preprocessor
The preprocessors are the directives, which give instruction 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:
When this line appears in a file, all subsequent occurrences of macro in that
file will be replaced by replacement-text before the program is compiled.
For example:
#include <iostream>
ts
Va
#define PI 3.14159
int main ()
ee
return 0;
}
Pa
rd
Now, let us do the preprocessing of this code to see the result, assume we
have source code file, so let us compile it with -E option and redirect the
result to test.p. Now, if you will check test.p, it will have lots of information
and at the bottom, you will fine 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;
ts
Va
int main ()
{
int i, j;
i = 100;
ee
j = 30;
Pa
return 0;
rd
If we compile and run above code, this would produce the following result:
The minimum is 30
Conditional Compilation:
There are several directives, which can use to compile selectively 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 and can debugging turn
on or off using a single macro as follows:
#ifdef DEBUG
cerr <<"Variable x = " << x << endl;
#endif
ts
#if 0
Va
ee
Pa
#define DEBUG
rd
#include <iostream>
using namespace std;
#endif
int main ()
{
int i, j;
i = 100;
j = 30;
#ifdef DEBUG
cerr <<"Trace: Inside main function" << endl;
#endif
#if 0
#ifdef DEBUG
cerr <<"Trace: Coming out of main function" << endl;
#endif
return 0;
}
ts
If we compile and run above code, this would produce the following result:
Va
ee
Pa
rd
#define MKSTR( x ) #x
int main ()
{
cout << MKSTR(HELLO C++) << endl;
return 0;
If we compile and run above code, this would produce the following result:
HELLO C++
x ## y
Va
#define CONCAT( x, y )
ts
ee
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.
rd
#include <iostream>
Pa
#define concat(a, b) a ## b
int main()
{
int xy = 100;
If we compile and run above code, this would produce the following result:
100
__LINE__
__FILE__
__DATE__
Pa
rd
ee
Va
ts
Macro
__TIME__
int main ()
{
cout << "Value of __LINE__ : " << __LINE__ << endl;
cout << "Value of __FILE__ : " << __FILE__ << endl;
return 0;
}
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
ts
Va
ee
Pa
rd
There are signals which can not 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
Va
ts
ee
Let us write a simple C++ program where we will catch SIGINT signal using
signal() function. Whatever signal you want to catch in your program, you
#include <iostream>
#include <csignal>
Pa
rd
must register that signal using signal function and associate it with a signal
handler. Examine the following example:
exit(signum);
int main ()
{
// register signal SIGINT and signal handler
signal(SIGINT, signalHandler);
while(1){
cout << "Going to sleep...." << endl;
sleep(1);
ts
Va
return 0;
}
ee
When the above code is compiled and executed, it produces the following
result:
rd
Going to sleep....
Going to sleep....
Pa
Going to sleep....
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.
Here, sig is the signal number to send any of the signals: SIGINT,
SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGTERM, SIGHUP. Following is the
example where we raise a signal internally using raise() function as follows:
#include <iostream>
#include <csignal>
Va
ts
cout << "Interrupt signal (" << signum << ") received.\n";
ee
// terminate program
rd
exit(signum);
int main ()
Pa
{
int i = 0;
// register signal SIGINT and signal handler
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....
Va
ts
C++ Multithreading
ee
Pa
rd
Creating Threads:
There is following routine which we use to create a POSIX thread:
#include <pthread.h>
pthread_create (thread, attr, start_routine, arg)
thread
attr
start_routine
arg
Pa
rd
ee
Va
ts
Parameter
Terminating Threads:
There is following routine which we use to terminate a POSIX thread:
#include <pthread.h>
pthread_exit (status)
Example:
ts
Va
#include <iostream>
#include <cstdlib>
ee
#include <pthread.h>
Pa
#define NUM_THREADS
rd
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);
ts
Va
Pa
rd
ee
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#define NUM_THREADS
struct thread_data{
int
thread_id;
char *message;
ts
};
Va
ee
rd
Pa
pthread_exit(NULL);
}
int main ()
{
pthread_t threads[NUM_THREADS];
struct thread_data td[NUM_THREADS];
int rc;
int i;
ts
When the above code is compiled and executed, it produces the following
Va
result:
ee
Pa
rd
The pthread_join() subroutine blocks the calling thread until the specified
threadid thread terminates. When a thread is created, one of its attributes
defines whether it is joinable or detached. Only threads that are created as
joinable can be joined. If a thread is created as detached, it can never be
joined.
This example demonstrates how to wait for thread completions by using the
Pthread join routine.
#include <iostream>
#include <cstdlib>
#include <pthread.h>
ts
#include <unistd.h>
ee
#define NUM_THREADS
Va
long tid;
Pa
int i;
rd
tid = (long)t;
sleep(1);
cout << "Sleeping in thread " << endl;
cout << "Thread with id : " << tid << "
pthread_exit(NULL);
}
int main ()
{
int rc;
int i;
pthread_t threads[NUM_THREADS];
pthread_attr_t attr;
void *status;
ts
if (rc){
Va
ee
Pa
pthread_attr_destroy(&attr);
rd
rc = pthread_join(threads[i], &status);
if (rc){
cout << "Error:unable to join," << rc << endl;
exit(-1);
}
cout << "Main: completed thread id :" << i ;
cout << "
When the above code is compiled and executed, it produces the following
result:
main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
main() : creating thread, 3
main() : creating thread, 4
Sleeping in thread
Thread with id : 0 .... exiting
Sleeping in thread
Thread with id : 1 .... exiting
ts
Sleeping in thread
Va
Sleeping in thread
ee
Pa
rd
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:
ts
Web Browsing
Your browser contacts the HTTP web server and demand for the URL ie.
ee
Va
To understand the concept of CGI, let's see what happens when we click a
hyperlink to browse a particular web page or URL.
filename.
Web Server will parse the URL and will look for the filename. If it finds
rd
Pa
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.
Pa
rd
ee
Va
ts
<Directory "/var/www/cgi-bin">
AllowOverride None
Options ExecCGI
Order allow,deny
Allow from all
</Directory>
<Directory "/var/www/cgi-bin">
Options All
</Directory>
ts
Here, I assumed that you have Web Server up and running successfully and
you are able to run any other CGI program like Perl or Shell etc.
Va
ee
#include <iostream>
Pa
int main ()
rd
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 clickcplusplus.cgi then this produces the following output:
Va
ts
C++ CGI program can interact with any other exernal system, such as
RDBMS, to exchange information.
ee
HTTP Header
Pa
rd
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:
Location: URL
Last-modified: Date
Content-length: N
Set-Cookie: String
Va
ts
Expires: Date
ee
Variable Name
Pa
rd
All the CGI program will have access to the following environment variables.
These variables play an important role while writing any CGI program.
Description
CONTENT_TYPE
CONTENT_LENGTH
HTTP_COOKIE
Return the set cookies in the form of key & value pair.
PATH_INFO
QUERY_STRING
REMOTE_ADDR
REMOTE_HOST
REQUEST_METHOD
SCRIPT_FILENAME
ee
rd
Pa
SCRIPT_NAME
Va
ts
HTTP_USER_AGENT
SERVER_NAME
SERVER_SOFTWARE
Here is small CGI program to list out all the CGI variables. Click this link to
see the result Get Environment
#include <iostream>
#include <stdlib.h>
using namespace std;
Va
ts
"SERVER_NAME","SERVER_PORT","SERVER_PROTOCOL",
ee
"SERVER_SIGNATURE","SERVER_SOFTWARE" };
int main ()
Pa
rd
if ( value != 0 ){
cout << value;
}else{
cout << "Environment variable does not exist.";
}
cout << "</td></tr>\n";
}
cout << "</table><\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
ts
Va
ee
For real examples, you would need to do many operations by your CGI
program. There is a CGI library written for C++ program which you can
download from ftp://ftp.gnu.org/gnu/cgicc/ and following the following
$cd cgicc-X.X.X/
Pa
rd
$./configure --prefix=/usr
$make
$make install
You
can
check
related
documentation
available
at C++
CGI
Lib
Documentation.
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 upto 1024 characters in a request string.
ts
Va
environment variable
ee
You can pass information by simply concatenating key and value pairs
alongwith any URL or you can use HTML <FORM> tags to pass information
using GET method.
rd
Pa
Here is a simple URL which will pass two values to hello_get.py program
using GET method.
/cgi-bin/cpp_get.cgi?first_name=ZARA&last_name=ALI
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
int main ()
{
Cgicc formData;
ts
Va
ee
rd
Pa
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;
}
Generate cpp_get.cgi and put it in your CGI directory and try to access
using following link:
Va
ts
/cgi-bin/cpp_get.cgi?first_name=ZARA&last_name=ALI
ee
rd
Pa
Here is a simple example which passes two values using HTML FORM and
submit button. We are going to use same CGI script cpp_get.cgi to handle
this input.
<form action="/cgi-bin/cpp_get.cgi" method="get">
First Name: <input type="text" name="first_name">
<br />
Here is the actual output of the above form, You enter First and Last Name
and then click submit button to see the result.
First Name:
Last Name:
Submit
Va
ts
The same cpp_get.cgi program will handle POST method as well. Let us
take same example as above, which passes two values using HTML FORM
and submit button but this time with POST method as follows:
<form action="/cgi-bin/cpp_get.cgi" method="post">
ee
rd
Pa
</form>
Here is the actual output of the above form, You enter First and Last Name
and then click submit button to see the result.
First Name:
Last Name:
Submit
<form action="/cgi-bin/cpp_checkbox.cgi"
method="POST"
target="_blank">
<input type="checkbox" name="maths" value="on" /> Maths
<input type="checkbox" name="physics" value="on" /> Physics
<input type="submit" value="Select Subject" />
</form>
Select Subject
Physics
ts
Va
#include <iostream>
#include <vector>
#include <string>
ee
#include <stdio.h>
#include <cgicc/Cgicc.h>
Pa
#include <cgicc/CgiDefs.h>
rd
#include <stdlib.h>
#include <cgicc/HTTPHTMLHeader.h>
#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;
}
Va
ts
physics_flag = formData.queryCheckbox("physics");
ee
if( physics_flag ) {
}else{
}
cout << "<br/>\n";
cout << "</body>\n";
Pa
rd
return 0;
}
target="_blank">
<input type="radio" name="subject" value="maths"
checked="checked"/> Maths
<input type="radio" name="subject" value="physics" /> Physics
<input type="submit" value="Select Subject" />
</form>
Select Subject
Physics
ts
Va
#include <vector>
#include <string>
#include <stdio.h>
#include <cgicc/Cgicc.h>
Pa
#include <cgicc/CgiDefs.h>
rd
ee
#include <stdlib.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
int main ()
{
Cgicc formData;
form_iterator fi = formData.getElement("subject");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "Radio box selected: " << **fi << endl;
}
ts
Va
return 0;
}
ee
rd
Program.
Pa
Submit
ts
#include <stdlib.h>
Va
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
ee
#include <cgicc/HTMLClasses.h>
int main ()
Pa
rd
{
Cgicc formData;
form_iterator fi = formData.getElement("textcontent");
return 0;
ts
Va
Drop Down Box is used when we have many options available but only one
or two will be selected.
ee
Here is example HTML code for a form with one drop down box
rd
<form action="/cgi-bin/cpp_dropdown.cgi"
<select name="dropdown">
Pa
method="post" target="_blank">
Submit
#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>
ts
Va
int main ()
{
ee
Cgicc formData;
Pa
rd
form_iterator fi = formData.getElement("dropdown");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "Value Selected: " << **fi << endl;
}
return 0;
}
ts
How It Works
Va
Your server sends some data to the visitor's browser in the form of a
ee
cookie. The browser may accept the cookie. If it does, it is stored as a plain
text record on the visitor's hard drive. Now, when the visitor arrives at
another page on your site, the cookie is available for retrieval. Once
retrieved, your server knows/remembers what was stored.
rd
Pa
Path : The path to the directory or web page that set 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
This is very easy to send cookies to browser. These cookies will be sent
along with HTTP Header before to 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 ()
{
ts
Va
ee
Pa
rd
return 0;
}
From this example, you must have understood how to set cookies. We
use Set-Cookie HTTP header to set cookies.
Here, it is optional to set cookies attributes like Expires, Domain, and Path.
It is notable that cookies are set before sending magic line "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
Va
ts
This is very easy to retrieve all the set cookies. Cookies are stored in CGI
environment variable HTTP_COOKIE and they will have following form.
key1=value1;key2=value2;key3=value3....
ee
rd
#include <vector>
#include <stdio.h>
#include <stdlib.h>
Pa
#include <string>
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
int main ()
{
Cgicc cgi;
const_cookie_iterator cci;
Va
ts
cci != env.getCookieList().end();
ee
++cci )
{
Pa
rd
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 at your computer:
UserID XYZ
Password XYZ123
Domain www.tutorialspoint.com
Path /perl
ts
To upload a file the HTML form must have the enctype attribute set
tomultipart/form-data. The input tag with the file type will create a
"Browse" button.
Va
<html>
<form enctype="multipart/form-data"
<body>
ee
action="/cgi-bin/cpp_uploadfile.cgi"
rd
method="post">
</form>
</body>
Pa
</html>
#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>
Va
ts
int main ()
ee
Cgicc cgi;
rd
Pa
return 0;
}
Pa
rd
ee
Va
ts
The above example is 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.