C++ Language
C++ Language
This reference will take you through simple and practical approach while
learning C++ Programming language.
ts
C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in
Va
Murray Hill, New Jersey, as an enhancement to the C language and
originally named C with Classes but later it was renamed C++ in 1983.
p
ee
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.
ts
code you write for Microsoft's compiler will compile without errors, using a
Va
compiler on a Mac, UNIX, a Windows box, or an Alpha.
The ANSI standard has been stable for a while, and all the major C++
p
compiler manufacturers support the ANSI standard.
ee
Learning C++
rd
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 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.
ts
briefly look into what do class, object, methods and instant variables mean.
Va
Object - Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behaviors - wagging, barking, eating. An object is an
p
instance of a class.
ee
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.
#include <iostream>
return 0;
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.
The line using namespace std; tells the compiler to use the std namespace.
ts
Namespaces are a relatively recent addition to C++.
Va
The next line // main() is where program execution begins. is a single-line
comment available in C++. Single-line comments begin with // and stop at the
end of the line.
p
ee
The line int main() is the main function where program execution begins.
rd
The next line cout << "This is my first C++ program."; causes the message
"This is my first C++ program" to be displayed on the screen.
Pa
The next line return 0; terminates main( )function and causes it to return the
value 0 to the calling process.
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
Make sure that g++ is in your path and that you are running it in the
directory containing file hello.cpp.
ts
You can compile C/C++ programs using makefile. For more details, you can
check Makefile Tutorial. Va
Semicolons & Blocks in C++:
p
In C++, the semicolon is a statement terminator. That is, each individual
ee
x = y;
y = y+1;
add(x, y);
return 0;
}
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
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,
ts
underscores, and digits (0 to 9). Va
C++ does not allow punctuation characters such as @, $, and % within
identifiers. C++ is a case-sensitive programming language.
p
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.
ts
const_cast goto signed
Va using
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.
Trigraph Replacement
??= #
??/ \
??' ^
ts
??( [
Va
??) ]
p
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.
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. Therefore, in the
statement,
int age;
ts
and apples, although you are free to include some if you wish for readability
purpose. Va
Comments in C++
p
Program comments are explanatory statements that you can include in the
ee
C++ code that you write and helps anyone reading it's source code. All
programming languages allow for some form of comments.
rd
Pa
C++ comments start with /* and end with */. For example:
/* This is a comment */
*/
A comment can also start with //, extending to the end of the line. For
example:
#include <iostream>
using namespace std;
main()
return 0;
When the above code is compiled, it will ignore // prints Hello World and
final executable will produce the following result:
Hello World
ts
Within a /* and */ comment, // characters have no special meaning. Within
a // comment, /* and */ have no special meaning. Thus, you can "nest" one
Va
kind of comment within the other kind. For example:
p
/* Comment out printing of Hello World:
ee
*/
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.
Primitive Built-in Types:
C++ offer the programmer a rich assortment of built-in as well as user
defined data types. Following table lists down seven basic C++ data types:
Type Keyword
Boolean bool
Character char
Integer int
ts
Floating point float
Va
Double floating point double
p
ee
Valueless void
rd
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.
Type Typical Bit Width Typical Range
ts
signed int 4bytes -2147483648 to 2147483647
Va
short int 2bytes -32768 to 32767
p
ee
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
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
rd
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() 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 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:
For example, the following tells the compiler that feet is another name for
int:
ts
typedef int feet;
Va
Now, the following declaration is perfectly legal and creates an integer
variable called distance:
p
feet distance;
ee
Enumerated Types:
rd
more identifiers that can be used as values of the type. Each enumerator is
a constant whose type is the enumeration.
Here, the enum-name is the enumeration's type name. The list of names is
comma separated.
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.
Here, blue will have a value of 6 because each name will be one greater
than the one that precedes it.
ts
size and layout of the variable's memory; the range of values that can be
Va
stored within that memory; and the set of operations that can be applied to
the variable.
p
Type Description
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
ts
variables.
Va
Variable Definition in C++:
p
A variable definition means to tell the compiler where and how much to
ee
create the storage for the variable. A variable definition specifies a data
type, and contains a list of one or more variables of that type as follows:
rd
type variable_list;
Pa
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.
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:
ts
value of all other variables is undefined.
Va
Variable Declaration in C++:
A variable declaration provides assurance to the compiler that there is one
p
variable existing with the given type and name so that compiler proceed for
ee
program.
A variable declaration is useful when you are using multiple files and you
define your variable in one of the files which will be available at the time of
linking of the program. You will 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;
ts
// actual initialization
Va
a = 10;
p
b = 20;
ee
c = a + b;
rd
f = 70.0/3.0;
return 0;
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();
ts
// function definition
int func()
{
Va
return 0;
p
}
ee
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.
int g = 20;
But following is not a valid statement and would generate compile-time
error:
10 = 20;
ts
Outside of all functions which is called global variables.
Va
We will learn what is a function and it's parameter in subsequent chapters.
Here let us explain what are local and global variables.
p
Local Variables:
ee
Variables that are declared inside a function or block are local variables.
rd
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.
Pa
#include <iostream>
int main ()
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 life-
time of your program.
A global variable can be accessed by any function. That is, a global variable
ts
is available for use throughout your entire program after its declaration.
Va
Following is the example using global and local variables:
p
#include <iostream>
ee
int g;
int main ()
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>
int g = 20;
int main ()
ts
{
cout << g;
rd
return 0;
Pa
When the above code is compiled and executed, it produces the following
result:
10
char '\0'
float 0
double 0
pointer NULL
ts
C++ Constants/Literals Va
Constants refer to fixed values that the program may not alter and they are
p
called literals.
ee
Constants can be of any of the basic data types and can be divided into
Integer Numerals, Floating-Point Numerals, Characters, Strings and Boolean
rd
Values.
Pa
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.
215u // Legal
0xFeeL // Legal
85 // decimal
0213 // octal
0x4b // hexadecimal
30 // int
30l // long
ts
30ul // unsigned long
Va
Floating-point literals:
p
A floating-point literal has an integer part, a decimal point, a fractional part,
ee
and an exponent part. You can represent floating point literals either in
decimal form or exponential form.
rd
While representing using decimal form, you must include the decimal point,
Pa
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.
3.14159 // Legal
314159E-5L // Legal
Boolean literals:
There are two Boolean literals and they are part of standard C++ keywords:
A value of true representing true.
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.
ts
Va
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
p
codes:
ee
\\ \ character
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
ts
\ooo Octal number of one to three digits
Va
\xhh . . . Hexadecimal number of one or more digits
p
ee
#include <iostream>
Pa
int main()
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"
"hello, \
ts
dear"
Va
p
"hello, " "d" "ear"
ee
Defining Constants:
rd
#include <iostream>
#define LENGTH 10
#define WIDTH 5
int main()
int area;
return 0;
ts
When the above code is compiled and executed, it produces the following
Va
result:
p
50
ee
You can use const prefix to declare constants with a specific type as
follows:
Pa
#include <iostream>
int main()
int area;
area = LENGTH * WIDTH;
return 0;
When the above code is compiled and executed, it produces the following
result:
50
ts
C++ Modifier Types
Va
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
p
that it more precisely fits the needs of various situations.
ee
signed
Pa
unsigned
long
short
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
/* This program shows the difference between
j = 50000;
i = j;
return 0;
-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.
Qualifier Meaning
volatile The modifier volatile tells the compiler that a variable's value may be
ts
changed in ways not explicitly specified by the program.
restrict
Va
A pointer qualified by restrict is initially the only means by which the
object it points to can be accessed. Only C99 adds a new type qualifier
p
called restrict.
ee
rd
auto
register
static
extern
mutable
The auto Storage Class
The auto storage class is the default storage class for all local variables.
int mount;
The example above defines two variables with the same storage class, auto
can only be used within functions, i.e., local variables.
ts
maximum size equal to the register size (usually one word) and can't have
Va
the unary '&' operator applied to it (as it does not have a memory location).
{
p
ee
}
rd
The register should only be used for variables that require quick access
Pa
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.
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
main()
{
Va
while(count--)
p
{
ee
func();
}
rd
return 0;
Pa
// Function definition
i++;
std::cout << " and count is " << count << std::endl;
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
ts
cannot be initialized as all it does is point the variable name at a storage
location that has been previously defined.Va
When you have multiple files and you define a global variable or function,
p
which will be used in other files also, then extern will be used in another file
ee
another file.
Pa
The extern modifier is most commonly used when there are two or more
files sharing the same global variables or functions as explained below.
#include <iostream>
int count ;
main()
count = 5;
write_extern();
#include <iostream>
void write_extern(void)
ts
Here, extern keyword is being used to declare count in another file. Now
compile these two files as follows: Va
$g++ main.cpp support.cpp -o write
p
This will produce write executable program, try to execute write and check
ee
$./write
Pa
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
ts
Misc Operators
Va
This chapter will examine the arithmetic, relational, logical, bitwise,
assignment and other operators one by one.
p
Arithmetic Operators:
ee
Show Examples
Relational Operators:
ts
There are following relational operators supported by C++ language
Va
Assume variable A holds 10 and variable B holds 20, then:
p
Show Examples
ee
ts
Logical Operators: Va
There are following logical operators supported by C++ language
p
Assume variable A holds 1 and variable B holds 0, then:
ee
Show Examples
rd
Bitwise Operators:
Bitwise operator works on bits and perform bit-by-bit operation. The truth
tables for &, |, and ^ are as follows:
0 0 0 0 0
0 1 0 1 1
ts
1 1 1 1 0
Va
1 0 0 1 1
p
ee
Assume if A = 60; and B = 13; now in binary format they will be as follows:
rd
A = 0011 1100
Pa
B = 0000 1101
-----------------
~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:
Show Examples
Operator Description Example
& Binary AND Operator copies a bit (A & B) will give 12 which is 0000
to the result if it exists in both 1100
operands.
ts
~ Binary Ones Complement (~A ) will give -61 which is 1100
Operator is unary and has the 0011 in 2's complement form due
Va
effect of 'flipping' bits. to a signed binary number.
p
<< Binary Left Shift Operator. The A << 2 will give 240 which is
ee
>> Binary Right Shift Operator. The A >> 2 will give 15 which is 0000
left operands value is moved right 1111
by the number of bits specified by
the right operand.
Assignment Operators:
There are following assignment operators supported by C++ language:
Show Examples
ts
*= Multiply AND assignment C *= A is equivalent to C = C * A
Va
operator, It multiplies right
operand with the left operand and
assign the result to left operand
p
ee
Misc Operators
There are few other operators supported by C++ Language.
Operator Description
ts
sizeof sizeof operator returns the size of a variable. For
Va
example, sizeof(a), where a is integer, will return 4.
p
Condition ? X : Y Conditional operator. If Condition is true ? then it
ee
. (dot) and -> (arrow) Member operators are used to reference individual
members of classes, structures, and unions.
Here, operators with the highest precedence appear at the top of the table,
ts
those with the lowest appear at the bottom. Within an expression, higher
Va
precedence operators will be evaluated first.
Show Examples
p
ee
ts
Conditional ?: Va Right to left
ts
Va
p
ee
rd
Pa
nested loops You can use one or more loop inside any another while,
for or do..while loop.
ts
C++ supports the following control statements. Click the following links to
check their detail.
Va
Control Statement Description
p
ee
continue statement Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
#include <iostream>
using namespace std;
int main ()
for( ; ; )
return 0;
ts
When the conditional expression is absent, it is assumed to be true. You
may have an initialization and increment expression, but C++ programmers
Va
more commonly use the for(;;) construct to signify an infinite loop.
p
NOTE: You can terminate an infinite loop by pressing Ctrl + C keys.
ee
rd
if statement
followed by one or more statements.
Pa
nested if statements You can use one if or else if statement inside another
if or else if statement(s).
nested switch You can use one swicth statement inside another
switch statement(s).
statements
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:
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and
placement of the colon.
ts
C++ Functions Va
A function is a group of statements that together perform a task.
p
Every C++ program has at least one function, which is main(), and all the
ee
You can divide up your code into separate functions. How you divide up
rd
your code among different functions is up to you, but logically the division
Pa
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.
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
operations without returning a value. In this case, the return_type is the
ts
keyword void.
Va
Function Name: This is the actual name of the function. The function name and
the parameter list together constitute the function signature.
p
ee
argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may
Pa
contain no parameters.
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:
{
// local variable declaration
int result;
result = num1;
else
result = num2;
return result;
Function Declarations:
A function declaration tells the compiler about a function name and how to
ts
call the function. The actual body of the function can be defined separately.
For the above defined function max(), following is the function declaration:
rd
Parameter names are not importan in function declaration only their type is
required, so following is also valid declaration:
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>
// function declaration
ts
int main () Va
{
p
// local variable declaration:
ee
int a = 100;
int b = 200;
rd
int ret;
Pa
return 0;
result = num1;
else
result = num2;
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
Function Arguments: Va
If a function is to use arguments, it must declare variables that accept the
values of the arguments. These variables are called the formal
p
The formal parameters behave like other local variables inside the function
rd
and are created upon entry into the function and destroyed upon exit.
Pa
While calling a function, there are two ways that arguments can be passed
to a function:
Call by pointer This method 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
argument.
ts
When you define a function, you can specify a default value for each of the
last parameters. This value will be used if the corresponding argument is
Va
left blank when calling to the function.
p
This is done by using the assignment operator and assigning values for the
ee
value is specified, this default value is ignored and the passed value is used
instead. Consider the following example:
Pa
#include <iostream>
int result;
result = a + b;
return (result);
}
int main ()
int a = 100;
int b = 200;
int result;
result = sum(a);
ts
cout << "Total value is :" << result << endl;
Va
return 0;
p
}
ee
When the above code is compiled and executed, it produces the following
result:
rd
Pa
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.
int main ()
// number definition:
short s;
int i;
long l;
float f;
double d;
// number assignments;
ts
s = 10;
i = 1000;
Va
l = 1000000;
p
f = 230.47;
ee
d = 30949.374;
rd
// number printing;
Pa
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
ts
To utilize these functions you need to include the math header
file <cmath>. Va
S.N. Function & Purpose
p
ee
1 double cos(double);
rd
This function takes an angle (as a double) and returns the cosine.
Pa
2 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.
4 double log(double);
This function takes a number and returns the natural log of that number.
If you pass this function the length of two sides of a right triangle, it will
return you the length of the hypotenuse.
7 double sqrt(double);
You pass this function a number and it gives you this square root.
8 int abs(int);
ts
This function returns the absolute value of an integer that is passed to it.
9 double fabs(double);
Va
This function returns the absolute value of any decimal number passed to
p
it.
ee
rd
10 double floor(double);
Pa
Finds the integer which is less than or equal to the argument passed to it.
#include <iostream>
#include <cmath>
int main ()
// number definition:
short s = 10;
int i = -1000;
long l = 100000;
float f = 230.47;
double d = 200.374;
// mathematical operations;
return 0;
ts
When the above code is compiled and executed, it produces the following
result: Va
sign(d) :-0.634939
p
abs(i) :1000
ee
floor(d) :200
sqrt(f) :15.1812
rd
pow( d, 2 ) :40149.7
Pa
#include <iostream>
#include <ctime>
#include <cstdlib>
int main ()
int i,j;
ts
{
}
rd
return 0;
Pa
When the above code is compiled and executed, it produces the following
result:
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.
ts
All arrays consist of contiguous memory locations. The lowest address
Va
corresponds to the first element and the highest address to the last
element.
p
Declaring Arrays:
ee
double balance[10];
Initializing Arrays:
You can initialize C++ array elements either one by one or using a single
statement as follows:
If you omit the size of the array, an array just big enough to hold the
initialization is created. Therefore, if you write:
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.
ts
Following is the pictorial representaion of the same array we discussed
Va
above:
p
ee
rd
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>
#include <iomanip>
using std::setw;
int main ()
ts
// output each array element's value
}
rd
return 0;
Pa
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
0 100
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109
Concept Description
ts
You can generate a pointer to the first element
Pointer to an array Va
of an array by simply specifying the array name,
without any index.
p
You can pass to the function a pointer to an
Passing arrays to functions
ee
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
statement as follows: Va
char greeting[] = "Hello";
p
Following is the memory presentation of above defined string in C/C++:
ee
rd
Pa
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>
return 0;
ts
C++ supports a wide range of functions that manipulate null-terminated
Va
strings:
p
S.N. Function & Purpose
ee
1 strcpy(s1, s2);
rd
Pa
2 strcat(s1, s2);
3 strlen(s1);
4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if
s1>s2.
5 strchr(s1, ch);
6 strstr(s1, s2);
#include <iostream>
#include <cstring>
ts
int main () Va
{
char str3[10];
rd
int len ;
Pa
cout << "strcpy( str3, str1) : " << str3 << endl;
cout << "strcat( str1, str2): " << str1 << endl;
len = strlen(str1);
return 0;
}
strlen(str1) : 10
ts
At this point, you may not understand this example because so far we have
Va
not discussed Classes and Objects. So can have a look and proceed until
you have understanding on Object Oriented Concepts.
p
ee
#include <iostream>
#include <string>
rd
int main ()
string str3;
int len ;
str3 = str1;
len = str3.size();
return 0;
ts
str3 : Hello
C++ Pointers
rd
C++ pointers are easy and fun to learn. Some C++ tasks are performed
Pa
more easily with pointers, and other C++ tasks, such as dynamic memory
allocation, cannot be performed without them.
#include <iostream>
int main ()
{
int var1;
char var2[10];
return 0;
ts
something as follows:
any variable or constant, you must declare a pointer before you can work
with it. The general form of a pointer variable declaration is:
Pa
type *var-name;
Here, type is the pointer's base type; it must be a valid C++ type and var-
name 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:
ts
#include <iostream>
Va
using namespace std;
p
ee
int main ()
{
rd
return 0;
ts
programming. There are following few important pointer concepts which
should be clear to a C++ programmer: Va
Concept Description
p
ee
libraries.
Pa
C++ References
A reference variable is an alias, that is, another name for an already
existing variable. Once a reference is initialized with a variable, either the
variable name or the reference name may be used to refer to the variable.
ts
C++ References vs Pointers:
Va
References are often confused with pointers but three major differences
p
between references and pointers are:
ee
You cannot have NULL references. You must always be able to assume that a
rd
int i = 17;
We can declare reference variables for i as follows.
int& 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 ()
ts
{
int i;
Va
double d;
p
ee
int& r = i;
double& s = d;
Pa
i = 5;
d = 11.7;
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
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
ts
References as parameters C++ supports passing references as function
parameter more safely than parameters.
Va
Reference as return value You can return reference from a C++ function
p
like a any other data type can be returned.
ee
rd
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 {
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.
ts
SN Function & Purpose
Va
p
1 time_t time(time_t *time);
ee
This returns the current calendar time of the system in number of seconds
rd
4 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.
This returns a pointer to a string that contains the information stored in the
structure pointed to by time converted into the form: day month date
hours:minutes:seconds year\n\0
This returns a pointer to the time in the form of a tm structure. The time is
represented in Coordinated Universal Time (UTC), which is essentially
Greenwich Mean Time (GMT).
ts
7 time_t mktime(struct tm *time);
Va
This returns the calendar-time equivalent of the time found in the structure
pointed to by time.
p
ee
This function calculates the difference in seconds between time1 and time2.
Pa
9 size_t strftime();
This function can be used to format date and time a specific format.
#include <iostream>
#include <ctime>
char* dt = ctime(&now);
cout << "The local date and time is: " << dt << endl;
tm *gmtm = gmtime(&now);
ts
dt = asctime(gmtm);
cout << "The UTC date and time is:"<< dt << endl;
Va
}
p
When the above code is compiled and executed, it produces the following
ee
result:
rd
The local date and time is: Sat Jan 8 20:07:41 2011
Pa
While using structure in this chapter, I'm making an assumption that you
have basic understanding on C structure and how to access structure
members using arrow -> operator.
#include <iostream>
#include <ctime>
int main( )
cout << "Number of sec since January 1,1970:" << now << endl;
tm *ltm = localtime(&now);
ts
// print various components of tm structure.
Va
cout << "Year: "<< 1900 + ltm->tm_year << endl;
p
cout << "Month: "<< 1 + ltm->tm_mon<< endl;
ee
When the above code is compiled and executed, it produces the following
result:
Year: 2011
Month: 1
Day: 8
C++ I/O occurs in streams, which are sequences of bytes. If bytes flow
from a device like a keyboard, a disk drive, or a network connection etc. to
main memory, this is called input operation and if bytes flow from main
memory to a device like a display screen, a printer, a disk drive, or a
network connection, etc, this is called output operation.
ts
There are following header files important to C++ programs:
<iomanip> This file declares services useful for performing formatted I/O
with so-called parameterized stream manipulators, such
as setwand setprecision.
#include <iostream>
int main( )
ts
When the above code is compiled and executed, it produces the following
result:
Va
Value of str is : Hello C++
p
ee
The C++ compiler also determines the data type of variable to be output
and selects the appropriate stream insertion operator to display the value.
rd
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.
#include <iostream>
using namespace std;
int main( )
char name[50];
cout << "Your name is: " << name << endl;
When the above code is compiled and executed, it will prompt you to enter
ts
a name. You enter a value and then hit enter to see the result something as
follows: Va
Please enter your name: cplusplus
p
Your name is: cplusplus
ee
The C++ compiler also determines the data type of the entered value and
selects the appropriate stream extraction operator to extract the value and
rd
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:
The cerr is also used in conjunction with the stream insertion operator as
shown in the following example.
#include <iostream>
int main( )
ts
cerr << "Error message : " << str << endl;
}
Va
When the above code is compiled and executed, it produces the following
p
result:
ee
The predefined object clog is an instance of ostream class. The clog object
is said to be attached to the standard error device, which is also a display
screen but the object clog is buffered. This means that each insertion to
clog could cause its output to be held in a buffer until the buffer is filled or
until the buffer is flushed.
The clog is also used in conjunction with the stream insertion operator as
shown in the following example.
#include <iostream>
When the above code is compiled and executed, it produces the following
result:
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
ts
messages using cerr stream and while displaying other log messages then
Va
clog should be used.
p
ee
rd
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:
member definition;
member definition;
...
member definition;
ts
variable definition, such as int i; or float f; or any other valid variable
Va
definition. At the end of the structure's definition, before the final
semicolon, you can specify one or more structure variables but it is
p
optional. Here is the way you would declare the Book structure:
ee
struct Books
rd
char title[50];
Pa
char author[50];
char subject[100];
int book_id;
}book;
#include <iostream>
#include <cstring>
struct Books
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( )
ts
{
// book 1 specification
Book1.book_id = 6495407;
// book 2 specification
Book2.book_id = 6495700;
return 0;
When the above code is compiled and executed, it produces the following
result:
ts
Book 1 title : Learn C++ Programming
Book 2 id : 6495700
#include <iostream>
#include <cstring>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( )
// book 1 specification
ts
strcpy( Book1.title, "Learn C++ Programming");
// book 2 specification
rd
Book2.book_id = 6495700;
printBook( Book1 );
printBook( Book2 );
return 0;
When the above code is compiled and executed, it produces the following
result:
Book id : 6495407
ts
Book title : Telecom Billing
Pointers to Structures:
rd
You can define pointers to structures in very similar way as you define
pointer to any other variable as follows:
Pa
Now, you can store the address of a structure variable in the above defined
pointer variable. To find the address of a structure variable, place the &
operator before the structure's name as follows:
struct_pointer = &Book1;
struct_pointer->title;
Let us re-write above example using structure pointer, hope this will be
easy for you to understand the concept:
#include <iostream>
#include <cstring>
struct Books
char title[50];
char author[50];
ts
char subject[100];
};
int book_id; Va
p
int main( )
ee
{
rd
// Book 1 specification
Book1.book_id = 6495407;
// Book 2 specification
Book2.book_id = 6495700;
// Print Book1 info, passing address of structure
printBook( &Book1 );
printBook( &Book2 );
return 0;
ts
cout << "Book author : " << book->author <<endl;
Va
cout << "Book subject : " << book->subject <<endl;
When the above code is compiled and executed, it produces the following
result:
rd
Pa
Book id : 6495407
Book id : 6495700
typedef struct
{
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:
ts
pint32 x, y, z;
Va
x, y and z are all pointers to long ints
p
ee
class Box
public:
};
ts
the class that follow it. A public member can be accessed from outside the
Va
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.
p
ee
from a class. We declare objects of a class with exactly the same sort of
Pa
Both of the objects Box1 and Box2 will have their own copy of data
members.
class Box
public:
};
int main( )
ts
{
// box 1 specification
rd
Box1.height = 5.0;
Pa
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
// volume of box 2
return 0;
When the above code is compiled and executed, it produces the following
result:
ts
So far, you have got very basic idea about C++ Classes and Objects. There
Va
are further interesting concepts related to C++ Classes and Objects which
we will discuss in various sub-sections listed below:
p
ee
Concept Description
rd
The this pointer in C++ Every object has a special pointer this which
points to the object itself.
ts
way a pointer to a structure is. In fact a class is
really just a structure with functions in it.
Va
Both data members and function members of a
Static members of a class
class can be declared as static.
p
ee
C++ Inheritance
rd
When creating a class, instead of writing completely new data members and
member functions, the programmer can designate that the new class should
inherit the members of an existing class. This existing class is called
the baseclass, and the new class is referred to as the derived class.
Consider a base class Shape and its derived class Rectangle as follows:
ts
#include <iostream>
class Shape
{
rd
public:
Pa
void setWidth(int w)
width = w;
void setHeight(int h)
height = h;
protected:
int width;
int height;
};
// Derived class
public:
int getArea()
};
int main(void)
Rectangle Rect;
ts
Rect.setWidth(5);
Va
Rect.setHeight(7);
p
ee
return 0;
When the above code is compiled and executed, it produces the following
result:
Total area: 35
We can summarize the different access types according to who can access
them in the following way:
Access public protected private
A derived class inherits all base class methods with the following
exceptions:
ts
Overloaded operators of the base class.
When deriving a class from a base class, the base class may be inherited
through public, protected or private inheritance. The type of inheritance
rd
Multiple Inheritances:
A C++ class can inherit members from more than one class and here is the
extended syntax:
ts
#include <iostream>
class Shape
{
rd
public:
Pa
void setWidth(int w)
width = w;
void setHeight(int h)
height = h;
protected:
int width;
int height;
};
// Base class PaintCost
class PaintCost
public:
};
// Derived class
ts
public:
int getArea()
Va
{
p
return (width * height);
ee
};
rd
Pa
int main(void)
Rectangle Rect;
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
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
ts
C++ Overloading (Operator and Va
Function)
p
C++ allows you to specify more than one definition for a function name or
ee
Following is the example where same function print() is being used to print
different data types:
#include <iostream>
class printData
ts
{
public:
void print(int i) {
Va
cout << "Printing int: " << i << endl;
p
}
ee
void print(double f) {
rd
void print(char* c) {
};
int main(void)
printData pd;
pd.print(5);
// Call print to print float
pd.print(500.263);
pd.print("Hello C++");
return 0;
When the above code is compiled and executed, it produces the following
result:
Printing int: 5
ts
Operators overloading in C++: Va
You can redefine or overload most of the built-in operators available in
C++. Thus a programmer can use operators with user-defined types as
p
well.
ee
operator followed by the symbol for the operator being defined. Like any
Pa
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:
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>
class Box
public:
double getVolume(void)
ts
}
{
Va
length = len;
p
}
ee
rd
{
Pa
breadth = bre;
height = hei;
Box box;
return box;
private:
};
int main( )
ts
Box Box2; // Declare Box2 of type Box
Box Box3;
Va
// Declare Box3 of type Box
// box 1 specification
Box1.setLength(6.0);
rd
Box1.setBreadth(7.0);
Pa
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();
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
// volume of box 3
volume = Box3.getVolume();
return 0;
When the above code is compiled and executed, it produces the following
ts
result:
Overloadable/Non-overloadableOperators:
rd
+ - * / % ^
& | ~ ! , =
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
:: .* . ?:
ts
1
Va
Unary operators overloading
p
2
ee
3
Relational operators overloading
Pa
4
Input/Output operators overloading
5
++ and -- operators overloading
6
Assignment operators overloading
7
Function call () operator overloading
8
Subscripting [] operator overloading
9
Class member access operator -> overloading
ts
Va
Polymorphism in C++
p
ee
related by inheritance.
Pa
Consider the following example where a base class has been derived by
other two classes:
#include <iostream>
class Shape {
protected:
width = a;
height = b;
int area()
return 0;
};
ts
public:
}
Pa
};
public:
int area ()
};
int main( )
{
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
shape = &rec;
shape->area();
shape = &tri;
shape->area();
ts
return 0;
Va
}
p
When the above code is compiled and executed, it produces the following
ee
result:
rd
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 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:
width = a;
height = b;
return 0;
};
ts
After this slight modification, when the previous example code is compiled
Va
and executed, it produces the following result:
p
Rectangle class area
ee
This time, the compiler looks at the contents of the pointer instead of it's
rd
type. Hence, since addresses of objects of tri and rec classes are stored in
Pa
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.
We can change the virtual function area() in the base class to the following:
class Shape {
protected:
ts
int width, height;
public: Va
Shape( int a=0, int b=0)
{
p
ee
width = a;
height = b;
rd
};
The = 0 tells the compiler that the function has no body and above virtual
function will be called pure virtual function.
ts
object data, i.e., state without actually knowing how class has been
Va
implemented internally.
For example, your program can make a call to the sort() function without
p
knowing what algorithm the function actually uses to sort the given values.
ee
change between releases of the library, and as long as the interface stays
the same, your function call will still work.
Pa
In C++, we use classes to define our own abstract data types (ADT). You
can use the cout object of class ostream to stream data to standard
output like this:
#include <iostream>
int main( )
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
type.
ts
There are no restrictions on how often an access label may appear. Each
Va
access label specifies the access level of the succeeding member definitions.
The specified access level remains in effect until the next access label is
p
encountered or the closing right brace of the class body is seen.
ee
Class internals are protected from inadvertent user-level errors, which might
corrupt the state of the object.
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.
Data Abstraction Example:
Any C++ program where you implement a class with public and private
members is an example of data abstraction. Consider the following
example:
#include <iostream>
class Adder{
public:
// constructor
Adder(int i = 0)
ts
total = i;
}
Va
// interface to outside world
p
void addNum(int number)
ee
total += number;
rd
}
Pa
int getTotal()
return total;
};
private:
int total;
};
int main( )
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
return 0;
When the above code is compiled and executed, it produces the following
result:
Total 60
Above class adds numbers together, and returns the sum. The public
ts
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
Va
something that the user doesn't need to know about, but is needed for the
class to operate properly.
p
Designing Strategy:
ee
In this case whatever programs are using these interfaces, they would not
be impacted and would just need a recompilation with the latest
implementation.
Program data: The data is the information of the program which affected by
the program functions.
ts
C++ supports the properties of encapsulation and data hiding through the
Va
creation of user-defined types, called classes. We already have studied
that a class can contain private, protected and public members. By
default, all items defined in a class are private. For example:
p
ee
class Box
{
rd
public:
Pa
double getVolume(void)
private:
};
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 defined after the public specifier are accessible by all other
functions in your program.
ts
#include <iostream>
// constructor
rd
Adder(int i = 0)
{
Pa
total = i;
total += number;
int getTotal()
return total;
};
private:
int total;
};
int main( )
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
ts
return 0;
}
Va
When the above code is compiled and executed, it produces the following
p
result:
ee
Total 60
rd
Above class adds numbers together, and returns the sum. The public
Pa
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.
The C++ interfaces are implemented using abstract classes and these
abstract classes should not be confused with data abstraction which is a
concept of keeping implementation details separate from associated data.
class Box
ts
public:
};
#include <iostream>
// Base class
class Shape
ts
{
public: Va
// pure virtual function providing interface framework.
{
rd
width = w;
}
Pa
void setHeight(int h)
height = h;
protected:
int width;
int height;
};
// Derived classes
public:
int getArea()
};
public:
int getArea()
};
ts
int main(void)
Va
{
p
Rectangle Rect;
ee
Triangle Tri;
rd
Rect.setWidth(5);
Pa
Rect.setHeight(7);
cout << "Total Rectangle area: " << Rect.getArea() << endl;
Tri.setWidth(5);
Tri.setHeight(7);
cout << "Total Triangle area: " << Tri.getArea() << endl;
return 0;
}
When the above code is compiled and executed, it produces the following
result:
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. Then, through inheritance from that abstract base class,
ts
derived classes are formed that all operate similarly.
Va
The capabilities (i.e., the public functions) offered by the external
applications are provided as pure virtual functions in the abstract base
p
class. The implementations of these pure virtual functions are provided in
ee
the derived classes that correspond to the specific types of the application.
This tutorial will teach you how to read and write from a file. This requires
another standard C++ library called fstream, which defines three new data
types:
Data Type Description
ofstream This data type represents the output file stream and is
used to create files and to write information to files.
ifstream This data type represents the input file stream and is
used to read information from files.
fstream This data type represents the file stream generally, and
has the capabilities of both ofstream and ifstream which
means it can create files, write information to files, and
read information from files.
ts
To perform file processing in C++, header files <iostream> and <fstream>
must be included in your C++ source file. Va
Opening a File:
p
A file must be opened before you can read from it or write to it. Either
ee
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.
rd
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.
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:
ts
ofstream outfile; Va
outfile.open("file.dat", ios::out | ios::trunc );
p
Similar way, you can open a file for reading and writing purpose as follows:
ee
fstream afile;
rd
Closing a File
When a C++ program terminates it automatically closes 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.
void close();
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.
ts
the screen:
#include <fstream>
Va
#include <iostream>
p
using namespace std;
ee
int main ()
rd
{
Pa
char data[100];
ofstream outfile;
outfile.open("afile.dat");
cin.getline(data, 100);
cin.ignore();
outfile.close();
ifstream infile;
ts
infile.open("afile.dat");
Va
cout << "Reading from the file" << endl;
p
infile >> data;
ee
// again read the data from the file and display it.
infile.close();
return 0;
When the above code is compiled and executed, it produces the following
sample input and output:
$./a.out
Zara
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
file-position pointer. These member functions are seekg ("seek get") for
Va
istream and seekp ("seek put") for ostream.
argument can be specified to indicate the seek direction. The seek direction
ee
The file-position pointer is an integer value that specifies the location in the
file as a number of bytes from the file's starting location. Some examples of
positioning the "get" file-position pointer are:
fileObject.seekg( n );
fileObject.seekg( n, ios::cur );
fileObject.seekg( n, ios::end );
// position at end of fileObject
fileObject.seekg( 0, ios::end );
ts
Va
C++ Exception Handling
p
ee
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.
Assuming a block will raise an exception, a method catches an exception
using a combination of the try and catch keywords. A try/catch block is
placed around the code that might generate an exception. Code within a
try/catch block is referred to as protected code, and the syntax for using
try/catch looks like the following:
try
// protected code
}catch( ExceptionName e1 )
// catch block
}catch( ExceptionName e2 )
ts
{
// catch block Va
}catch( ExceptionName eN )
{
p
// catch block
ee
}
rd
You can list down multiple catch statements to catch different type of
exceptions in case your try block raises more than one exception in
Pa
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.
if( b == 0 )
{
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
ts
{
// protected code
}catch( ExceptionName e )
Va
{
p
// code to handle ExceptionName exception
ee
}
rd
thrown in a try block, you must put an ellipsis, ..., between the parentheses
enclosing the exception declaration as follows:
try
// protected code
}catch(...)
if( b == 0 )
return (a/b);
int main ()
ts
{
int x = 50;
Va
int y = 0;
p
double z = 0;
ee
try {
rd
z = division(x, y);
Pa
return 0;
ts
Va
p
ee
rd
Pa
Exception Description
ts
std::domain_error This is an exception thrown when a mathematically invalid
domain is used Va
std::invalid_argument This is thrown due to invalid arguments.
p
ee
std::range_error This is occured when you try to store a value which is out
of range.
#include <iostream>
#include <exception>
ts
{
int main()
rd
{
Pa
try
throw MyException();
catch(MyException& e)
catch(std::exception& e)
//Other errors
}
}
MyException caught
C++ Exception
ts
essential to becoming a good C++ programmer. Memory in your C++
program is divided into two parts: Va
The stack: All variables declared inside the function will take up memory from
p
the stack.
ee
The heap: This is unused memory of the program and can be used to allocate
rd
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.
The new and delete operators:
There is following generic syntax to use new operator to allocate memory
dynamically for any data-type.
new data-type;
Here, data-type could be any built-in data type including an array or any
user defined data types include class or structure. Let us start with built-in
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:
ts
The memory may not have been allocated successfully, if the free store had
Va
been used up. So it is good practice to check if new operator is returning
NULL pointer and take appropriate action as below:
p
double* pvalue = NULL;
ee
exit(1);
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:
#include <iostream>
int main ()
ts
delete pvalue; // free up the memory. Va
return 0;
p
}
ee
If we compile and run above code, this would produce the following result:
rd
To remove the array that we have just created the statement would look
like this:
However, the syntax to release the memory for multi-dimensional array will
still remain same as above:
ts
#include <iostream> Va
using namespace std;
p
ee
class Box
{
rd
public:
Pa
Box() {
~Box() {
};
int main( )
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!
ts
Destructor called!
Destructor called!
Destructor called!
Va
Destructor called!
p
ee
Namespaces in C++
rd
Consider a situation, when we have two persons with the same name, Zara,
Pa
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.
Defining a Namespace:
A namespace definition begins with the keyword namespace followed by
the namespace name as follows:
namespace namespace_name {
// code declarations
ts
name::code; // code could be variable or function.
Va
Let us see how namespace scope the entities including variable and
functions:
p
#include <iostream>
ee
namespace first_space{
void func(){
namespace second_space{
void func(){
int main ()
{
// Calls function from first name space.
first_space::func();
second_space::func();
return 0;
If we compile and run above code, this would produce the following result:
Inside first_space
Inside second_space
ts
The using directive: Va
You can also avoid prepending of namespaces with the using
namespacedirective. This directive tells the compiler that the subsequent
p
ee
#include <iostream>
Pa
namespace first_space{
void func(){
namespace second_space{
void func(){
}
}
int main ()
func();
return 0;
If we compile and run above code, this would produce the following result:
Inside first_space
ts
The using directive can also be used to refer to a particular item within a
Va
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:
p
ee
using std::cout;
Subsequent code can refer to cout without prepending the namespace, but
rd
other items in the std namespace will still need to be explicit as follows:
Pa
#include <iostream>
using std::cout;
int main ()
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
ts
either defines a new namespace or adds new elements to an existing one:
namespace namespace_name {
Va
// code declarations
p
}
ee
Nested Namespaces:
rd
Namespaces can be nested where you can define one namespace inside
another name space as follows:
Pa
namespace namespace_name1 {
// code declarations
namespace namespace_name2 {
// code declarations
#include <iostream>
namespace first_space{
void func(){
ts
// second name space
namespace second_space{
Va
void func(){
p
cout << "Inside second_space" << endl;
ee
}
rd
}
Pa
int main ()
func();
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.
You can use templates to define functions as well as classes, let us see how
do they work:
ts
Function Template: Va
The general form of a template function definition is shown here:
p
template <class type> ret-type func-name(parameter list)
ee
{
rd
// body of function
}
Pa
Here, type is a placeholder name for a data type used by the function. This
name can be used within the function definition.
#include <iostream>
#include <string>
int main ()
int i = 39;
int j = 20;
double f1 = 13.5;
double f2 = 20.7;
cout << "Max(f1, f2): " << Max(f1, f2) << endl;
ts
string s1 = "Hello";
Va
string s2 = "World";
p
cout << "Max(s1, s2): " << Max(s1, s2) << endl;
ee
return 0;
rd
}
Pa
If we compile and run above code, this would produce the following result:
Max(i, j): 39
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:
.
.
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.
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
ts
#include <stdexcept>
class Stack {
rd
private:
public:
return elems.empty();
};
{
// append copy of passed element
elems.push_back(elem);
void Stack<T>::pop ()
if (elems.empty()) {
elems.pop_back();
ts
template <class T>
Va
T Stack<T>::top () const
p
{
ee
if (elems.empty()) {
}
Pa
return elems.back();
int main()
try {
intStack.push(7);
stringStack.push("hello");
stringStack.pop();
stringStack.pop();
return -1;
ts
If we compile and run above code, this would produce the following result:
7
Va
hello
p
Exception: Stack<>::pop(): empty stack
ee
rd
Pa
C++ Preprocessor
The preprocessors are the directives, which give instruction to the compiler
to preprocess the information before actual compilation starts.
You already have seen a #include directive in all the examples. This macro
is used to include a header file into the source file.
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
#define PI 3.14159
Va
int main ()
p
{
ee
return 0;
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:
...
int main ()
{
cout << "Value of PI :" << 3.14159 << endl;
return 0;
Function-Like Macros:
You can use #define to define a macro which will take argument as follows:
#include <iostream>
ts
int main ()
int i, j;
Va
i = 100;
p
j = 30;
ee
return 0;
Pa
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.
#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
#endif
#if 0
ts
code prevented from compiling
#endif
Va
Let us try the following example:
p
ee
#include <iostream>
#define DEBUG
Pa
int main ()
int i, j;
i = 100;
j = 30;
#ifdef DEBUG
#endif
#if 0
/* This is commented part */
#endif
#ifdef DEBUG
#endif
return 0;
If we compile and run above code, this would produce the following result:
ts
Trace: Inside main function
The minimum is 30
Va
Trace: Coming out of main function
p
#include <iostream>
#define MKSTR( x ) #x
int main ()
return 0;
}
If we compile and run above code, this would produce the following result:
HELLO C++
ts
#define CONCAT( x, y ) x ## y
Va
When CONCAT appears in the program, its arguments are concatenated and
used to replace the macro. For example, CONCAT(HELLO, C++) is replaced
p
by "HELLO C++" in the program as follows.
ee
#include <iostream>
rd
#define concat(a, b) a ## b
int main()
int xy = 100;
return 0;
If we compile and run above code, this would produce the following result:
100
Let us see how it worked. It is simple to understand that the C++
preprocessor transforms:
Macro Description
ts
when it is being compiled.
Va
__FILE__ This contain the current file name of the program when it
p
is being compiled.
ee
#include <iostream>
int main ()
return 0;
If we compile and run above code, this would produce the following result:
Value of __LINE__ : 6
ts
C++ Signal Handling Va
Signals are the interrupts delivered to a process by the operating system
which can terminate a program prematurely. You can generate interrupts
p
by pressing Ctrl+C on a UNIX, LINUX, Mac OS X or Windows system.
ee
There are signals which can not be caught by the program but there is a
rd
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++
Pa
Signal Description
ts
an integer which represents signal number and second argument as a
pointer to the signal-handling function.
Va
Let us write a simple C++ program where we will catch SIGINT signal using
p
signal() function. Whatever signal you want to catch in your program, you
ee
must register that signal using signal function and associate it with a signal
handler. Examine the following example:
rd
Pa
#include <iostream>
#include <csignal>
cout << "Interrupt signal (" << signum << ") received.\n";
// terminate program
exit(signum);
}
int main ()
signal(SIGINT, signalHandler);
while(1){
sleep(1);
ts
return 0;
}
Va
When the above code is compiled and executed, it produces the following
p
result:
ee
Going to sleep....
rd
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....
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>
cout << "Interrupt signal (" << signum << ") received.\n";
ts
// cleanup and close up stuff here
Va
// terminate program
p
ee
exit(signum);
rd
}
Pa
int main ()
int i = 0;
signal(SIGINT, signalHandler);
while(++i){
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....
ts
Va
C++ Multithreading
Multithreading is a specialized form of multitasking and a multitasking is the
p
and thread-based.
Pa
C++ does not contain any built-in support for multithreaded applications.
Instead, it relies entirely upon the operating system to provide this feature.
This tutorial assumes that you are working on Linux OS and we are going to
write multi-threaded C++ program using POSIX. POSIX Threads, or
Pthreads provides API which are available on many Unix-like POSIX systems
such as FreeBSD, NetBSD, GNU/Linux, Mac OS X and Solaris.
Creating Threads:
There is following routine which we use to create a POSIX thread:
#include <pthread.h>
Parameter Description
ts
attr
Va
An opaque attribute object that may be used to set thread
attributes. You can specify a thread attributes object, or
NULL for the default values.
p
ee
start_routine The C++ routine that the thread will execute once it is
rd
created.
Pa
Terminating Threads:
There is following routine which we use to terminate a POSIX thread:
#include <pthread.h>
pthread_exit (status)
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().
ts
#include <iostream>
#include <cstdlib>
Va
#include <pthread.h>
p
ee
#define NUM_THREADS 5
Pa
long tid;
tid = (long)threadid;
cout << "Hello World! Thread ID, " << tid << endl;
pthread_exit(NULL);
int main ()
pthread_t threads[NUM_THREADS];
int rc;
int i;
rc = pthread_create(&threads[i], NULL,
if (rc){
exit(-1);
pthread_exit(NULL);
ts
Compile the following program using -lpthread library as follows:
#include <cstdlib>
#include <pthread.h>
#define NUM_THREADS 5
struct thread_data{
int thread_id;
char *message;
};
ts
void *PrintHello(void *threadarg)
{
Va
struct thread_data *my_data;
p
ee
pthread_exit(NULL);
int main ()
pthread_t threads[NUM_THREADS];
int rc;
int i;
td[i].thread_id = i;
rc = pthread_create(&threads[i], NULL,
if (rc){
exit(-1);
pthread_exit(NULL);
ts
When the above code is compiled and executed, it produces the following
result: Va
main() : creating thread, 0
p
main() : creating thread, 1
ee
pthread_detach (threadid)
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>
#include <unistd.h>
ts
using namespace std;
Va
#define NUM_THREADS 5
p
ee
{
rd
int i;
Pa
long tid;
tid = (long)t;
sleep(1);
cout << "Thread with id : " << tid << " ...exiting " << endl;
pthread_exit(NULL);
int main ()
int rc;
int i;
pthread_t threads[NUM_THREADS];
pthread_attr_t attr;
void *status;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
if (rc){
ts
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
Va
}
p
}
ee
pthread_attr_destroy(&attr);
Pa
rc = pthread_join(threads[i], &status);
if (rc){
exit(-1);
cout << " exiting with status :" << status << endl;
pthread_exit(NULL);
}
When the above code is compiled and executed, it produces the following
result:
Sleeping in thread
Sleeping in thread
Sleeping in thread
ts
Thread with id : 2 .... exiting
Sleeping in thread
The CGI specs are currently maintained by the NCSA and NCSA defines CGI is as
follows:
Web Browsing
ts
To understand the concept of CGI, let's see what happens when we click a
Va
hyperlink to browse a particular web page or URL.
p
Your browser contacts the HTTP web server and demand for the URL ie.
ee
filename.
Web Server will parse the URL and will look for the filename. If it finds
rd
requested file then web server sends that file back to the browser otherwise
Pa
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.
ts
Va
p
ee
rd
Pa
AllowOverride None
Options ExecCGI
Order allow,deny
</Directory>
<Directory "/var/www/cgi-bin">
Options All
</Directory>
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.
ts
First CGI Program Va
Consider the following C++ Program content:
p
#include <iostream>
ee
int main ()
Pa
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:
ts
CGI and you can write many complicated CGI programs using Python. A
Va
C++ CGI program can interact with any other exernal system, such as
RDBMS, to exchange information.
p
HTTP Header
ee
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
Location: URL The URL that should be returned instead of the URL
requested. You can use this filed to redirect a request to
any file.
ts
Set-Cookie: String
Va
Set the cookie passed through the string
p
All the CGI program will have access to the following environment variables.
rd
These variables play an important role while writing any CGI program.
Pa
CONTENT_TYPE The data type of the content. Used when the client is
sending attached content to the server. For example file
upload etc.
HTTP_COOKIE Return the set cookies in the form of key & value pair.
HTTP_USER_AGENT The User-Agent request-header field contains information
about the user agent originating the request. Its name of
the web browser.
ts
REMOTE_HOST The fully qualified name of the host making the request.
If this information is not available then REMOTE_ADDR
Va
can be used to get IR address.
p
REQUEST_METHOD The method used to make the request. The most
ee
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>
"HTTP_ACCEPT", "HTTP_ACCEPT_ENCODING",
"HTTP_ACCEPT_LANGUAGE", "HTTP_CONNECTION",
ts
"SCRIPT_NAME", "SERVER_ADDR", "SERVER_ADMIN",
Va
"SERVER_NAME","SERVER_PORT","SERVER_PROTOCOL",
"SERVER_SIGNATURE","SERVER_SOFTWARE" };
p
ee
int main ()
{
rd
Pa
}else{
return 0;
ts
C++ CGI Library Va
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
p
ee
$cd cgicc-X.X.X/
$./configure --prefix=/usr
$make
$make install
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 upto 1024 characters in a request string.
ts
header and will be accessible in your CGI Program through QUERY_STRING
environment variable Va
You can pass information by simply concatenating key and value pairs
alongwith any URL or you can use HTML <FORM> tags to pass information
p
ee
Here is a simple URL which will pass two values to hello_get.py program
Pa
/cgi-bin/cpp_get.cgi?first_name=ZARA&last_name=ALI
#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
int main ()
Cgicc formData;
ts
cout << "<html>\n";
form_iterator fi = formData.getElement("first_name");
Pa
}else{
cout << "No text entered for first name" << endl;
fi = formData.getElement("last_name");
}else{
cout << "No text entered for last name" << endl;
return 0;
Generate cpp_get.cgi and put it in your CGI directory and try to access
using following link:
/cgi-bin/cpp_get.cgi?first_name=ZARA&last_name=ALI
ts
This would generate following result: Va
First name: ZARA
p
Last name: ALI
ee
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
Pa
this input.
</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:
Submit
Last Name:
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:
ts
<form action="/cgi-bin/cpp_get.cgi" method="post">
Va
First Name: <input type="text" name="first_name"><br />
p
Last Name: <input type="text" name="last_name" />
ee
</form>
Pa
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:
Submit
Last Name:
method="POST"
target="_blank">
</form>
Select Subject
Maths Physics
ts
#include <iostream> Va
#include <vector>
#include <string>
p
#include <stdio.h>
ee
#include <stdlib.h>
rd
#include <cgicc/CgiDefs.h>
Pa
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
int main ()
Cgicc formData;
maths_flag = formData.queryCheckbox("maths");
if( maths_flag ) {
}else{
ts
Va
physics_flag = formData.queryCheckbox("physics");
if( physics_flag ) {
p
cout << "Physics Flag: ON " << endl;
ee
}else{
}
Pa
return 0;
Here is example HTML code for a form with two radio button:
<form action="/cgi-bin/cpp_radiobutton.cgi"
method="post"
target="_blank">
checked="checked"/> Maths
</form>
Select Subject
Maths Physics
ts
#include <iostream>
#include <vector> Va
#include <string>
#include <stdio.h>
p
#include <stdlib.h>
ee
rd
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
Pa
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
int main ()
Cgicc formData;
form_iterator fi = formData.getElement("subject");
cout << "Radio box selected: " << **fi << endl;
ts
return 0;
}
Va
Passing Text Area Data to CGI Program
p
ee
TEXTAREA element is used when multiline text has to be passed to the CGI
Program.
rd
<form action="/cgi-bin/cpp_textarea.cgi"
method="post"
target="_blank">
</textarea>
</form>
#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <stdlib.h>
ts
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h> Va
#include <cgicc/HTTPHTMLHeader.h>
p
#include <cgicc/HTMLClasses.h>
ee
int main ()
Cgicc formData;
form_iterator fi = formData.getElement("textcontent");
if( !fi->isEmpty() && fi != (*formData).end()) {
}else{
return 0;
ts
Passing Drop Down Box Data to CGI Program
Va
Drop Down Box is used when we have many options available but only one
or two will be selected.
p
Here is example HTML code for a form with one drop down box
ee
<form action="/cgi-bin/cpp_dropdown.cgi"
rd
method="post" target="_blank">
Pa
<select name="dropdown">
<option value="Physics">Physics</option>
</select>
</form>
Maths Submit
#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
ts
int main ()
{
Va
Cgicc formData;
p
ee
form_iterator fi = formData.getElement("dropdown");
How It Works
ts
Your server sends some data to the visitor's browser in the form of a
Va
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
p
Expires : The date the cookie will expire. If this is blank, the cookie will expire
Pa
when the visitor quits the browser.
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>
int main ()
ts
cout << "Set-Cookie:Password=XYZ123;\r\n";
Va
cout << "Set-Cookie:Domain=www.tutorialspoint.com;\r\n";
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 "Content-
type:text/html\r\n\r\n.
/cgi-bin/setcookies.cgi
Retrieving Cookies
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.
ts
key1=value1;key2=value2;key3=value3....
Va
Here is an example of how to retrieving cookies.
p
ee
#include <iostream>
#include <vector>
rd
#include <string>
Pa
#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;
ts
for( cci = env.getCookieList().begin();
Va
cci != env.getCookieList().end();
p
++cci )
ee
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
<html> Va
<body>
<form enctype="multipart/form-data"
p
action="/cgi-bin/cpp_uploadfile.cgi"
ee
method="post">
rd
</form>
</body>
</html>
File:
Upload
#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
int main ()
Va
{
p
Cgicc cgi;
ee
if(file != cgi.getFiles().end()) {
file->writeToStream(cout);
}
cout << "<File uploaded successfully>\n";
return 0;
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.
ts
Va
p
ee
rd
Pa