C++ Language
C++ Language
programming.
C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill,
C++ is a superset of C, and that virtually any legal C program is a legal C++ program.
Object-Oriented Programming
Encapsulation
Data hiding
Inheritance
Polymorphism
Standard Libraries
The core language giving all the building blocks including variables, data
The C++ Standard Library giving a rich set of functions manipulating files,
strings, etc.
Microsoft's compiler will compile without errors, using a compiler on a Mac, UNIX, a
The ANSI standard has been stable for a while, and all the major C++ compiler
Learning C++
The most important thing while learning C++ is to focus on concepts.
that is, to become more effective at designing and implementing new systems and at
Smalltalk, etc., in any language. Each style can achieve its aims effectively while
Use of C++
C++ is used by hundreds of thousands of programmers in essentially every application
domain.
C++ is being highly used to write device drivers and other software that rely on direct
C++ is widely used for teaching and research because it is clean enough for successful
Anyone who has used either an Apple Macintosh or a PC running Windows has
indirectly used C++ because the primary user interfaces of these systems are written in
C++.
Text Editor
This will be used to type your program. Examples of few editors include Windows
Notepad will be used on Windows and vim or vi can be used on windows as well as
Linux, or UNIX.
The files you create with your editor are called source files and for C++ they typically
C++ Compiler
This is an actual C++ compiler, which will be used to compile your source code into
Most C++ compilers don't care what extension you give to your source code, but if you
Most frequently used and free available compiler is GNU C/C++ compiler, otherwise
you can have compilers either from HP or Solaris if you have the respective Operating
Systems.
your system by entering the following command from the command line −
$ g++ -v
If you have installed GCC, then it should print a message such as the
following −
Using built-in specs.
Target: i386-redhat-linux
Configured with: ../configure --prefix=/usr .......
Thread model: posix
gcc version 4.1.2 20080704 (Red Hat 4.1.2-46)
If GCC is not installed, then you will have to install it yourself using the detailed
Mac OS X Installation
If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode
development environment from Apple's website and follow the simple installation
instructions.
Windows Installation
To install GCC at Windows you need to install MinGW. To install MinGW, go to the
MinGW homepage, www.mingw.org, and follow the link to the MinGW download
page. Download the latest version of the MinGW installation program which should be
named MinGW-<version>.exe.
While installing MinGW, at a minimum, you must install gcc-core, gcc-g++, binutils,
and the MinGW runtime, but you may wish to install more.
Add the bin subdirectory of your MinGW installation to your PATH environment
variable so that you can specify these tools on the command line by their simple
names.
When the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool,
and several other GNU tools from the Windows command line.
C++ Basic Syntax
When we consider a C++ program, it can be defined as a collection of objects that
communicate via invoking each other's methods. Let us now briefly look into what a
class.
support.
executed.
Live Demo
#include <iostream>
using namespace std;
// main() is where program execution begins.
int main() {
cout << "Hello World"; // prints Hello World
return 0;
}
The C++ language defines several headers, which contain information that is
either necessary or useful to your program. For this program, the header
<iostream> is needed.
The line using namespace std; tells the compiler to use the std namespace.
The next line '// main() is where program execution begins.' is a single-line
The line int main() is the main function where program execution begins.
The next line cout << "Hello World"; causes the message "Hello World" to
The next line return 0; terminates main( )function and causes it to return the
Let's look at how to save the file, compile and run the program.
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
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
You can compile C/C++ programs using makefile. For more details, you can check our
'Makefile Tutorial'.
must be ended with a semicolon. It indicates the end of one logical entity.
x = y;
y = y + 1;
add(x, y);
{
cout << "Hello World"; // prints Hello World
return 0;
}
C++ does not recognize the end of the line as a terminator. For this
reason, it does not matter where you put a statement in a line. For
example −
x = y;
y = y + 1;
add(x, y);
is the same as
x = y; y = y + 1; add(x, y);
C++ Identifiers
A C++ identifier is a name used to identify a variable, function, class, module, or any
underscore (_) followed by zero or more letters, underscores, and digits (0 to 9).
C++ does not allow punctuation characters such as @, $, and % within identifiers. C++
C++ Keywords
The following list shows the reserved words in C++. These reserved words may not be
Trigraphs
A few characters have an alternative representation, called a trigraph sequence. A
Trigraphs are expanded anywhere they appear, including within string literals and
Trigraph Replacement
??= #
??/ \
??' ^
??( [
??) ]
??! |
??< {
??> }
??- ~
All the compilers do not support trigraphs and they are not advised to be used because
Whitespace in C++
A line containing only whitespace, possibly with a comment, is known as a blank line,
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
Statement 1
int age;
In the above statement there must be at least one whitespace character (usually a
space) between int and age for the compiler to be able to distinguish them.
Statement 2
fruit = apples + oranges; // Get the total fruit
In the above statement 2, no whitespace characters are necessary between fruit and =,
or between = and apples, although you are free to include some if you wish for
readability purpose.
Comments in C++
Program comments are explanatory statements that you can include in the C++ code.
These comments help anyone reading the source code. All programming languages
C++ supports single-line and multi-line comments. All characters available inside any
/* This is a comment */
A comment can also start with //, extending to the end of the line.
For example −
Live Demo
#include <iostream>
using namespace std;
main() {
cout << "Hello World"; // prints Hello World
return 0;
}
When the above code is compiled, it will ignore // prints Hello World
Hello World
"nest" one kind of comment within the other kind. For example −
*/
C++ Data Types
While writing program in any language, you need to use various variables to store
various information. Variables are nothing but reserved memory locations to store
values. This means that when you create a variable you reserve some space in
memory.
You may like to store information of various data types like character, wide character,
integer, floating point, double floating point, boolean etc. Based on the data type of a
variable, the operating system allocates memory and decides what can be stored in the
reserved memory.
user defined data types. Following table lists down seven basic C++
data types −
Type Keyword
Boolean bool
Character char
Integer int
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
float 4bytes
double 8bytes
The size of variables might be different from those shown in the above table,
Following is the example, which will produce correct size of various data types on your
computer.
Live Demo
#include <iostream>
using namespace std;
int main() {
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
return 0;
}
This example uses endl, which inserts a new-line character after every line and <<
operator is being used to pass multiple values out to the screen. We are also using
Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 4
Size of float : 4
Size of double : 8
Size of wchar_t : 4
typedef Declarations
You can create a new name for an existing type using typedef.
For example, the following tells the compiler that feet is another
feet distance;
Enumerated Types
An enumerated type declares an optional type name and a set of zero or more
identifiers that can be used as values of the type. Each enumerator is a constant whose
Here, the enum-name is the enumeration's type name. The list of names is comma
separated.
For example, the following code defines an enumeration of colors called colors and the
By default, the value of the first name is 0, the second name has the value 1, and the
third has the value 2, and so on. But you can give a name, a specific value by adding an
initializer. For example, in the following enumeration, green will have the value 5.
Here, blue will have a value of 6 because each name will be one greater than the one
variable in C++ has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory; and the
case-sensitive −
last chapter −
1
bool
2
char
3
int
5
double
6
void
7
wchar_t
C++ also allows to define various other types of variables, which we will cover in
subsequent chapters like Enumeration, Pointer, Array, Reference, Data structures, and
Classes.
Following section will cover how to define, declare and use various types of variables.
A variable definition tells the compiler where and how much storage
follows −
type variable_list;
Here, type must be a valid C++ data type including char, w_char, int,
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
For definition without an initializer: variables with static storage duration are implicitly
initialized with NULL (all bytes have the value 0); the initial value of all other variables
is undefined.
existing with the given type and name so that compiler proceed for further compilation
without needing complete detail about the variable. A variable declaration has its
meaning at the time of compilation only, compiler needs actual variable definition at
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,
Example
Try the following example where a variable has been declared at the
Live Demo
#include <iostream>
using namespace std;
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main () {
// Variable definition:
int a, b;
int c;
float f;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c << endl ;
f = 70.0/3.0;
cout << f << endl ;
return 0;
}
following result −
30
23.3333
// function declaration
int func();
int main() {
// function call
int i = func();
}
// function definition
int func() {
return 0;
}
side of an assignment.
statement −
int g = 20;
compile-time error −
10 = 20;
Local Variables
variables. They can be used only by statements that are inside that
Live Demo
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
Global Variables
Global variables are defined outside of all the functions, usually on top of the program.
The global variables will hold their value throughout the life-time of your program.
A global variable can be accessed by any function. That is, a global
variables −
Live Demo
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
A program can have same name for local and global variables but value
Live Demo
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
following result −
10
follows −
int 0
char '\0'
float 0
double 0
pointer NULL
literals.
Constants can be of any of the basic data types and can be divided into Integer
Again, constants are treated just like regular variables except that their values cannot
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.
212 // Legal
215u // Legal
0xFeeL // Legal
078 // Illegal: 8 is not an octal digit
032UU // Illegal: cannot repeat a suffix
85 // decimal
0213 // octal
0x4b // hexadecimal
30 // int
30u // unsigned int
30l // long
30ul // unsigned long
Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an
exponent part. You can represent floating point literals either in decimal form or
exponential form.
While representing using decimal form, you must include the decimal point, the
exponent, or both and while representing using exponential form, you must include the
integer part, the fractional part, or both. The signed exponent is introduced by e or E.
3.14159 // Legal
314159E-5L // Legal
510E // Illegal: incomplete exponent
210f // Illegal: no decimal or exponent
.e55 // Illegal: missing integer or fraction
Boolean Literals
There are two Boolean literals and they are part of standard C++
keywords −
You should not consider the value of true equal to 1 and value of false equal to 0.
Character Literals
Character literals are enclosed in single quotes. If the literal begins with L (uppercase
only), it is a wide character literal (e.g., L'x') and should be stored in wchar_t type of
variable . Otherwise, it is a narrow character literal (e.g., 'x') and can be stored in a
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or 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
\\ \ character
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
Live Demo
#include <iostream>
using namespace std;
int main() {
cout << "Hello\tWorld\n\n";
return 0;
}
following result −
Hello World
String Literals
String literals are enclosed in double quotes. A string contains characters that are
characters.
You can break a long line into multiple lines using string literals and separate them
using whitespaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
Defining Constants
constant −
Live Demo
#include <iostream>
using namespace std;
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main() {
int area;
following result −
50
You can use const prefix to declare constants with a specific type as
follows −
Live Demo
#include <iostream>
using namespace std;
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
following result −
50
modifier is used to alter the meaning of the base type so that it more precisely fits the
signed
unsigned
long
short
The modifiers signed, unsigned, long, and short can be applied to integer base types. In
addition, signed and unsigned can be applied to char, and long can be applied to
double.
The modifiers signed and unsigned can also be used as prefix to long or short
C++ allows a shorthand notation for declaring unsigned, short, or long integers. You
can simply use the word unsigned, short, or long, without int. It automatically implies
int. For example, the following two statements both declare unsigned integer
variables.
unsigned x;
unsigned int y;
To understand the difference between the way signed and unsigned
Live Demo
#include <iostream>
using namespace std;
j = 50000;
i = j;
cout << i << " " << j;
return 0;
}
-15536 50000
The above result is because the bit pattern that represents 50,000 as a short unsigned
1
const
2
volatile
The modifier volatile tells the compiler that a variable's value may be
3
restrict
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 called restrict.
within a C++ Program. These specifiers precede the type that they modify. There are
auto
register
static
extern
mutable
The auto Storage Class
The auto storage class is the default storage class for all local variables.
{
int mount;
auto int month;
}
The example above defines two variables with the same storage class, auto can only
register instead of RAM. This means that the variable has a maximum size equal to the
register size (usually one word) and can't have the unary '&' operator applied to it (as it
{
register int miles;
}
The register should only be used for variables that require quick access such as
counters. It should also be noted that defining 'register' does not mean that the
during the life-time of the program instead of creating and destroying it each time it
comes into and goes out of scope. Therefore, making local variables static allows them
The static modifier may also be applied to global variables. When this is done, it
In C++, when static is used on a class data member, it causes only one copy of that
Live Demo
#include <iostream>
// Function declaration
void func(void);
main() {
while(count--) {
func();
}
return 0;
}
// Function definition
void func( void ) {
static int i = 5; // local static variable
i++;
std::cout << "i is " << i ;
std::cout << " and count is " << count << std::endl;
}
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
to ALL the program files. When you use 'extern' the variable cannot be initialized as all
it does is point the variable name at a storage location that has been previously
defined.
When you have multiple files and you define a global variable or function, which will
be used in other files also, then extern will be used in another file to give reference of
defined variable or function. Just for understanding extern is used to declare a global
The extern modifier is most commonly used when there are two or more files sharing
main() {
count = 5;
write_extern();
}
Second File: support.cpp
#include <iostream>
void write_extern(void) {
std::cout << "Count is " << count << std::endl;
}
This will produce write executable program, try to execute write and
$./write
5
tutorial. It allows a member of an object to override const member function. That is, a
Operators in C++
An operator is a symbol that tells the compiler to perform specific
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
This chapter will examine the arithmetic, relational, logical, bitwise, assignment and
Arithmetic Operators
Show Examples
Relational Operators
There are following relational operators supported by C++ language
Show Examples
Logical Operators
There are following logical operators supported by C++ language.
Show Examples
Bitwise Operators
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
follows −
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the
then −
Show Examples
& Binary AND Operator copies a bit to (A & B) will give 12 which is 0000
the result if it exists in both operands. 1100
^ Binary XOR Operator copies the bit if (A ^ B) will give 49 which is 0011
it is set in one operand but not both. 0001
~ Binary Ones Complement Operator is (~A ) will give -61 which is 1100
unary and has the effect of 'flipping' 0011 in 2's complement form due to
bits. a signed binary number.
Show Examples
Misc Operators
The following table lists some other operators that C++ supports.
1
sizeof
sizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’
2
Condition ? X : Y
of the entire comma expression is the value of the last expression of the
comma-separated list.
4
. (dot) and -> (arrow)
5
Cast
Casting operators convert one data type to another. For example, int(2.2000)
would return 2.
6
&
Pointer operator & returns the address of a variable. For example &a; will
7
*
variable var.
operator −
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom. Within an expression, higher precedence operators
Show Examples
Programming languages provide various control structures that allow for more
requirements.
1 while loop
2 for loop
3 do...while loop
Like a ‘while’ statement, except that it tests the condition at the end of the
loop body.
4 nested loops
You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’
loop.
leaves a scope, all automatic objects that were created in that scope are destroyed.
1 break statement
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its
3 goto statement
traditionally used for this purpose. Since none of the three expressions that form the
‘for’ loop are required, you can make an endless loop by leaving the conditional
expression empty.
#include <iostream>
using namespace std;
int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
}
return 0;
}
When the conditional expression is absent, it is assumed to be true. You may have an
initialization and increment expression, but C++ programmers more commonly use the
1 if statement
statements.
2 if...else statement
3 switch statement
A ‘switch’ statement allows a variable to be tested for equality against a list
of values.
4 nested if statements
You can use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’
statement(s).
You can use one ‘switch’ statement inside another ‘switch’ statement(s).
The ? : Operator
form −
Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ‘?’ expression is determined like this: Exp1 is evaluated. If it is true, then
Exp2 is evaluated and becomes the value of the entire ‘?’ expression. If Exp1 is false,
then Exp3 is evaluated and its value becomes the value of the expression.
C++ Functions
A function is a group of statements that together perform a task. Every C++ program
has at least one function, which is main(), and all the most trivial programs can define
additional functions.
You can divide up your code into separate functions. How you divide up your code
among different functions is up to you, but logically the division usually is such that
A function declaration tells the compiler about a function's name, return type, and
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.
etc.
Defining a Function
Example
function takes two parameters num1 and num2 and return the biggest of
both −
Function Declarations
A function declaration tells the compiler about a function name and how to call the
declaration −
Function declaration is required when you define a function in one source file and you
call that function in another file. In such case, you should declare the function at the
Calling a Function
While creating a C++ function, you give a definition of what the function has to do. To
A called function performs defined task and when it’s return statement is executed or
when its function-ending closing brace is reached, it returns program control back to
along with function name, and if function returns a value, then you
Live Demo
#include <iostream>
using namespace std;
// function declaration
int max(int num1, int num2);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int ret;
return 0;
}
I kept max() function along with main() function and compiled the
following result −
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be
passed to a function −
1 Call by Value
This method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the parameter inside
2 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.
3 Call by Reference
This method copies the reference of an argument into the formal parameter.
Inside the function, the reference is used to access the actual argument used
in the call. This means that changes made to the parameter affect the
argument.
By default, C++ uses call by value to pass arguments. In general, this means that code
within a function cannot alter the arguments used to call the function and above
mentioned example while calling max() function used the same method.
parameters. This value will be used if the corresponding argument is left blank when
following example −
Live Demo
#include <iostream>
using namespace std;
return (result);
}
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int result;
return 0;
}
following result −
Numbers in C++
Normally, when we work with Numbers, we use primitive data types such as int, short,
long, float and double, etc. The number data types, their possible values and number
Live Demo
#include <iostream>
using namespace std;
int main () {
// number definition:
short s;
int i;
long l;
float f;
double d;
// number assignments;
s = 10;
i = 1000;
l = 1000000;
f = 230.47;
d = 30949.374;
// number printing;
cout << "short s :" << s << endl;
cout << "int i :" << i << endl;
cout << "long l :" << l << endl;
cout << "float f :" << f << endl;
cout << "double d :" << d << endl;
return 0;
}
following result −
short s :10
int i :1000
long l :1000000
float f :230.47
double d :30949.4
functions you can use. These functions are available in standard C and C++ libraries
and called built-in functions. These are functions that can be included in your program
C++ has a rich set of mathematical operations, which can be performed on various
numbers. Following table lists down some useful built-in mathematical functions
available in C++.
To utilize these functions you need to include the math header file <cmath>.
1
double cos(double);
This function takes an angle (as a double) and returns the cosine.
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.
5
double pow(double, double);
The first is a number you wish to raise and the second is the power you wish
to raise it t
6
double hypot(double, double);
If you pass this function the length of two sides of a right triangle, it will
7
double sqrt(double);
You pass this function a number and it gives you the square root.
8
int abs(int);
This function returns the absolute value of an integer that is passed to it.
9
double fabs(double);
This function returns the absolute value of any decimal number passed to it.
10
double floor(double);
Finds the integer which is less than or equal to the argument passed to it.
operations −
Live Demo
#include <iostream>
#include <cmath>
using namespace std;
int main () {
// number definition:
short s = 10;
int i = -1000;
long l = 100000;
float f = 230.47;
double d = 200.374;
// mathematical operations;
cout << "sin(d) :" << sin(d) << endl;
cout << "abs(i) :" << abs(i) << endl;
cout << "floor(d) :" << floor(d) << endl;
cout << "sqrt(f) :" << sqrt(f) << endl;
cout << "pow( d, 2) :" << pow(d, 2) << endl;
return 0;
}
following result −
sign(d) :-0.634939
abs(i) :1000
floor(d) :200
sqrt(f) :15.1812
pow( d, 2 ) :40149.7
Random Numbers in C++
There are many cases where you will wish to generate a random number. There are
actually two functions you will need to know about random number generation. The
first is rand(), this function will only return a pseudo random number. The way to fix
Live Demo
#include <iostream>
#include <ctime>
#include <cstdlib>
int main () {
int i,j;
return 0;
}
following result −
Random Number : 1748144778
Random Number : 630873888
Random Number : 2134540646
Random Number : 219404170
Random Number : 902129458
Random Number : 920445370
Random Number : 1319072661
Random Number : 257938873
Random Number : 1256201101
Random Number : 580322989
C++ Arrays
C++ provides a data structure, the array, which stores a fixed-size sequential collection
of elements of the same type. An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99,
you declare one array variable such as numbers and use numbers[0], numbers[1],
accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to
the first element and the highest address to the last element.
Declaring Arrays
integer constant greater than zero and type can be any valid C++ data
double balance[10];
Initializing Arrays
You can initialize C++ array elements either one by one or using a
The number of values between braces { } can not be larger than the
the array −
If you omit the size of the array, an array just big enough to hold
You will create exactly the same array as you did in the previous example.
balance[4] = 50.0;
The above statement assigns element number 5 th in the array a value of 50.0. Array
with 4th index will be 5th, i.e., last element because all arrays have 0 as
the index of their first element which is also called base index.
Following is the pictorial representaion of the same array we
discussed above −
placing the index of the element within square brackets after the
The above statement will take 10th element from the array and assign the
accessing arrays −
Live Demo
#include <iostream>
using namespace std;
#include <iomanip>
using std::setw;
int main () {
return 0;
}
This program makes use of setw() function to format the output. When
result −
Element Value
0 100
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109
Arrays in C++
Arrays are important to C++ and should need lots of more detail.
a C++ programmer −
1 Multi-dimensional arrays
C++ supports multidimensional arrays. The simplest form of the
2 Pointer to an array
You can pass to the function a pointer to an array by specifying the array's
C++ Strings
C++ provides following two types of string representations −
The following declaration and initialization create a string consisting of the word
"Hello". To hold the null character at the end of the array, the size of the character
array containing the string is one more than the number of characters in the word
"Hello."
If you follow the rule of array initialization, then you can write
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
above-mentioned string −
Live Demo
#include <iostream>
int main () {
return 0;
}
following result −
terminated strings −
1
strcpy(s1, s2);
2
strcat(s1, s2);
3
strlen(s1);
Returns the length of string 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);
Live Demo
#include <iostream>
#include <cstring>
int main () {
return 0;
}
something as follows −
The standard C++ library provides a string class type that supports
Live Demo
#include <iostream>
#include <string>
int main () {
return 0;
}
something as follows −
str3 : Hello
str1 + str2 : HelloWorld
str3.size() : 10
C++ Pointers
C++ pointers are easy and fun to learn. Some C++ tasks are performed more easily
with pointers, and other C++ tasks, such as dynamic memory allocation, cannot be
the following which will print the address of the variables defined −
Live Demo
#include <iostream>
return 0;
}
following result −
before you can work with it. The general form of a pointer variable
declaration is −
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
declaration −
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
The actual data type of the value of all pointers, whether integer, float, character, or
otherwise, is the same, a long hexadecimal number that represents a memory address.
The only difference between pointers of different data types is the data type of the
Live Demo
#include <iostream>
int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable
return 0;
}
something as follows −
Pointers in C++
Pointers have many but easy concepts and they are very important to
1 Null Pointers
C++ supports null pointer, which is a constant with a value of zero defined in
2 Pointer Arithmetic
There are four arithmetic operators that can be used on pointers: ++, --, +, -
3 Pointers vs Arrays
4 Array of Pointers
5 Pointer to Pointer
C++ allows a function to return a pointer to local variable, static variable and
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
You cannot have NULL references. You must always be able to assume that a
at any time.
label attached to that memory location. Therefore, you can access the
int i = 17;
int& r = i;
Read the & in these declarations as reference. Thus, read the first
Live Demo
#include <iostream>
int main () {
// declare simple variables
int i;
double d;
i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;
d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;
return 0;
}
Value of i : 5
Value of i reference : 5
Value of d : 11.7
Value of d reference : 11.7
References are usually used for function argument lists and function
1 References as Parameters
parameters.
You can return reference from a C++ function like any other data type.
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
struct tm {
int tm_sec; // seconds of minutes from 0 to 61
int tm_min; // minutes of hour from 0 to 59
int tm_hour; // hours of day from 0 to 24
int tm_mday; // day of month from 1 to 31
int tm_mon; // month of year from 0 to 11
int tm_year; // year since 1900
int tm_wday; // days since sunday
int tm_yday; // days since January 1st
int tm_isdst; // hours of daylight savings time
}
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.
1
time_t time(time_t *time);
This returns the current calendar time of the system in number of seconds
2
char *ctime(const time_t *time);
hours:minutes:seconds year\n\0.
3
struct tm *localtime(const time_t *time);
4
clock_t clock(void);
This returns a value that approximates the amount of time the calling
5
char * asctime ( const struct tm * time );
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
6
struct tm *gmtime(const time_t *time);
This returns a pointer to the time in the form of a tm structure. The time is
7
time_t mktime(struct tm *time);
This returns the calendar-time equivalent of the time found in the structure
pointed to by time.
8
double difftime ( time_t time2, time_t time1 );
This function calculates the difference in seconds between time1 and time2.
9
size_t strftime();
This function can be used to format date and time in a specific format.
Live Demo
#include <iostream>
#include <ctime>
int main() {
// current date/time based on current system
time_t now = time(0);
cout << "The local date and time is: " << dt << endl;
following result −
The local date and time is: Sat Jan 8 20:07:41 2011
The tm structure is very important while working with date and time
in either C or C++. This structure holds the date and time in the
makes use of various date and time related functions and tm structure
While using structure in this chapter, I'm making an assumption that you have basic
understanding on C structure and how to access structure members using arrow ->
operator.
Live Demo
#include <iostream>
#include <ctime>
int main() {
// current date/time based on current system
time_t now = time(0);
cout << "Number of sec since January 1,1970 is:: " << now << endl;
tm *ltm = localtime(&now);
following result −
we will see in subsequent chapters. This chapter will discuss very basic and most
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.
1
<iostream>
This file defines the cin, cout, cerr and clog objects, which correspond to the
standard input stream, the standard output stream, the un-buffered standard
2
<iomanip>
This file declares services useful for performing formatted I/O with so-called
This file declares services for user-controlled file processing. We will discuss
"connected to" the standard output device, which usually is the display screen. The
cout is used in conjunction with the stream insertion operator, which is written as <<
which are two less than signs as shown in the following example.
Live Demo
#include <iostream>
int main() {
char str[] = "Hello C++";
following result −
The C++ compiler also determines the data type of variable to be output and selects
the appropriate stream insertion operator to display the value. The << operator is
overloaded to output data items of built-in types integer, float, double, strings and
pointer values.
The insertion operator << may be used more than once in a single statement as shown
above and endl is used to add a new-line at the end of the line.
attached to the standard input device, which usually is the keyboard. The cin is used in
conjunction with the stream extraction operator, which is written as >> which are two
Live Demo
#include <iostream>
int main() {
char name[50];
When the above code is compiled and executed, it will prompt you to
enter a name. You enter a value and then hit enter to see the
following result −
The C++ compiler also determines the data type of the entered value and selects the
appropriate stream extraction operator to extract the value and store it in the given
variables.
The stream extraction operator >> may be used more than once in a
single statement. To request more than one datum you can use the
following −
attached to the standard error device, which is also a display screen but the object cerr
is un-buffered and each stream insertion to cerr causes its output to appear
immediately.
The cerr is also used in conjunction with the stream insertion operator as shown in the
following example.
Live Demo
#include <iostream>
int main() {
char str[] = "Unable to read....";
following result −
Error message : Unable to read....
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
The clog is also used in conjunction with the stream insertion operator as shown in the
following example.
Live Demo
#include <iostream>
int main() {
char str[] = "Unable to read....";
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 the difference becomes
obvious. So it is good practice to display error messages using cerr stream and while
same kind, but structure is another user defined data type which allows you to
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
the final semicolon, you can specify one or more structure variables
but it is optional. Here is the way you would declare the Book
structure −
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
the structure variable name and the structure member that we wish to
Live Demo
#include <iostream>
#include <cstring>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
return 0;
}
following result −
as you pass any other variable or pointer. You would access structure
example −
Live Demo
#include <iostream>
#include <cstring>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
return 0;
}
void printBook( struct Books book ) {
cout << "Book title : " << book.title <<endl;
cout << "Book author : " << book.author <<endl;
cout << "Book subject : " << book.subject <<endl;
cout << "Book id : " << book.book_id <<endl;
}
following result −
Pointers to Structures
Now, you can store the address of a structure variable in the above
struct_pointer = &Book1;
struct_pointer->title;
Let us re-write above example using structure pointer, hope this will
Live Demo
#include <iostream>
#include <cstring>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book
// Book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
// Book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
return 0;
}
following result −
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
pint32 x, y, z;
programming language and classes are the central feature of C++ that supports
A class is used to specify the form of an object and it combines data representation
and methods for manipulating that data into one neat package. The data and functions
define any data, but it does define what the class name means, that is, what an object
of the class will consist of and what operations can be performed on such an object.
class name; and the class body, enclosed by a pair of curly braces. A
declarations. For example, we defined the Box data type using the
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The keyword public determines the access attributes of the members of the class that
follows it. A public member can be accessed from outside the class anywhere within
the scope of the class object. You can also specify the members of a class as private or
Both of the objects Box1 and Box2 will have their own copy of data members.
the direct member access operator (.). Let us try the following
Live Demo
#include <iostream>
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
following result −
It is important to note that private and protected members can not be accessed directly
using direct member access operator (.). We will learn how private and protected
So far, you have got very basic idea about C++ Classes and Objects.
4 Copy Constructor
with an object of the same class, which has been created previously.
5 Friend Functions
a class.
6 Inline Functions
With an inline function, the compiler tries to expand the code in the body of
7 this Pointer
Every object has a special pointer this which points to the object itself.
static.
C++ Inheritance
One of the most important concepts in object-oriented programming is that of
makes it easier to create and maintain an application. This also provides an opportunity
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 base class, and the new
The idea of inheritance implements the is a relationship. For example, mammal IS-A
animal, dog IS-A mammal hence dog IS-A animal as well and so on.
A class can be derived from more than one classes, which means it can
name of a previously defined class. If the access-specifier is not used, then it is private
by default.
follows −
Live Demo
#include <iostream>
// Base class
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};
int main(void) {
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
return 0;
}
following result −
Total area: 35
class members that should not be accessible to the member functions of derived
exceptions −
Type of Inheritance
When deriving a class from a base class, the base class may be inherited through
Multiple Inheritance
A C++ class can inherit members from more than one class and here is
given for every base class and they will be separated by comma as
Live Demo
#include <iostream>
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape, public PaintCost {
public:
int getArea() {
return (width * height);
}
};
int main(void) {
Rectangle Rect;
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
return 0;
}
following result −
Total area: 35
Total paint cost: $2450
in the same scope, which is called function overloading and operator overloading
respectively.
previously declared declaration in the same scope, except that both declarations have
When you call an overloaded function or operator, the compiler determines the most
appropriate definition to use, by comparing the argument types you have used to call
the function or operator with the parameter types specified in the definitions. The
overload resolution.
definition of the function must differ from each other by the types and/or the number of
arguments in the argument list. You cannot overload function declarations that differ
Live Demo
#include <iostream>
using namespace std;
class printData {
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};
int main(void) {
printData pd;
return 0;
}
following result −
Printing int: 5
Printing float: 500.263
Printing character: Hello C++
followed by the symbol for the operator being defined. Like any other function, an
declares the addition operator that can be used to add two Box
objects and returns final Box object. Most overloaded operators may
a class then we would have to pass two arguments for each operand as
follows −
whose properties will be accessed using this object, the object which
explained below −
Live Demo
#include <iostream>
using namespace std;
class Box {
public:
double getVolume(void) {
return length * breadth * height;
}
void setLength( double len ) {
length = len;
}
void setBreadth( double bre ) {
breadth = bre;
}
void setHeight( double hei ) {
height = hei;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
return 0;
}
following result −
Overloadable/Non-overloadableOperators
+ - * / % ^
& | ~ ! , =
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
:: .* . ?:
concept.
Polymorphism in C++
The word polymorphism means having many forms. Typically, polymorphism occurs
C++ polymorphism means that a call to a member function will cause a different
function to be executed depending on the type of object that invokes the function.
Consider the following example where a base class has been derived by
Live Demo
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a = 0, int b = 0){
width = a;
height = b;
}
int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape {
public:
Rectangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
return 0;
}
following result −
The reason for the incorrect output is that the call of the function area() is being set
once by the compiler as the version defined in the base class. This is called static
resolution of the function call, or static linkage - the function call is fixed before the
program is executed. This is also sometimes called early binding because the area()
the declaration of area() in the Shape class with the keyword virtual
class Shape {
protected:
int width, height;
public:
Shape( int a = 0, int b = 0) {
width = a;
height = b;
}
virtual int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};
This time, the compiler looks at the contents of the pointer instead of it's type. Hence,
since addresses of objects of tri and rec classes are stored in *shape the respective
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
redefined in a derived class to suit the objects of that class, but that there is no
meaningful definition you could give for the function in the base class.
We can change the virtual function area() in the base class to the
following −
class Shape {
protected:
int width, height;
public:
Shape(int a = 0, int b = 0) {
width = a;
height = b;
}
and hiding their background details, i.e., to represent the needed information in
Data abstraction is a programming (and design) technique that relies on the separation
Let's take one real life example of a TV, which you can turn on and off, change the
channel, adjust the volume, and add external components such as speakers, VCRs, and
DVD players, BUT you do not know its internal details, that is, you do not know how it
receives signals over the air or through a cable, how it translates them, and finally
Thus, we can say a television clearly separates its internal implementation from its
external interface and you can play with its interfaces like the power button, channel
changer, and volume control without having any knowledge of its internals.
In C++, classes provides great level of data abstraction. They provide sufficient public
methods to the outside world to play with the functionality of the object and to
manipulate object data, i.e., state without actually knowing how class has been
implemented internally.
For example, your program can make a call to the sort() function without knowing
what algorithm the function actually uses to sort the given values. In fact, the
underlying implementation of the sorting functionality could change between releases
of the library, and as long as the interface stays the same, your function call will still
work.
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
Live Demo
#include <iostream>
using namespace std;
int main() {
cout << "Hello C++" <<endl;
return 0;
}
Here, you don't need to understand how cout displays the text on the user's screen.
You need to only know the public interface and the underlying implementation of ‘cout’
is free to change.
Members defined with a public label are accessible to all parts of the
members.
Members defined with a private label are not accessible to code that uses the
class. The private sections hide the implementation from code that uses
the type.
There are no restrictions on how often an access label may appear. Each access label
specifies the access level of the succeeding member definitions. The specified access
level remains in effect until the next access label is encountered or the closing right
Class internals are protected from inadvertent user-level errors, which might
By defining data members only in the private section of the class, the class author is
free to make changes in the data. If the implementation changes, only the class code
needs to be examined to see what affect the change may have. If data is public, then
any function that directly access the data members of the old representation might be
broken.
Any C++ program where you implement a class with public and private
example −
Live Demo
#include <iostream>
using namespace std;
class Adder {
public:
// constructor
Adder(int i = 0) {
total = i;
}
private:
// hidden data from outside world
int total;
};
int main() {
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
following result −
Total 60
Above class adds numbers together, and returns the sum. The public members -
addNum and getTotal are the interfaces to the outside world and a user needs to know
them to use the class. The private member total is something that the user doesn't
need to know about, but is needed for the class to operate properly.
Designing Strategy
Abstraction separates code into interface and implementation. So while designing your
component, you must keep interface independent of the implementation so that if you
In this case whatever programs are using these interfaces, they would not be impacted
elements −
Encapsulation is an Object Oriented Programming concept that binds together the data
and functions that manipulate the data, and that keeps both safe from outside
interference and misuse. Data encapsulation led to the important OOP concept of data
hiding.
Data encapsulation is a mechanism of bundling the data, and the functions that use
them and data abstraction is a mechanism of exposing only the interfaces and hiding
example −
class Box {
public:
double getVolume(void) {
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The variables length, breadth, and height are private. This means that they can be
accessed only by other members of the Box class, and not by any other part of your
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
encapsulation. The ideal is to keep as many of the details of each class hidden from all
Any C++ program where you implement a class with public and private
Live Demo
#include <iostream>
using namespace std;
class Adder {
public:
// constructor
Adder(int i = 0) {
total = i;
}
private:
// hidden data from outside world
int total;
};
int main() {
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
following result −
Total 60
Above class adds numbers together, and returns the sum. The public members
addNum and getTotal are the interfaces to the outside world and a user needs to know
them to use the class. The private member total is something that is hidden from the
Designing Strategy
Most of us have learnt to make class members private by default unless we really
This is applied most frequently to data members, but it applies equally to all members,
class Box {
public:
// pure virtual function
virtual double getVolume() = 0;
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
appropriate base class from which other classes can inherit. Abstract classes cannot be
virtual functions, which means that it supports the interface declared by the ABC.
Classes that can be used to instantiate objects are called concrete classes.
Live Demo
#include <iostream>
// Base class
class Shape {
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
// Derived classes
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};
Rect.setWidth(5);
Rect.setHeight(7);
Tri.setWidth(5);
Tri.setHeight(7);
return 0;
}
following result −
You can see how an abstract class defined an interface in terms of getArea() and two
other classes implemented same function but with different algorithm to calculate the
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, derived classes are formed that operate
similarly.
The capabilities (i.e., the public functions) offered by the external applications are
provided as pure virtual functions in the abstract base class. The implementations of
these pure virtual functions are provided in the derived classes that correspond to the
This architecture also allows new applications to be added to a system easily, even
methods for reading from standard input and writing to standard output respectively.
This tutorial will teach you how to read and write from a file. This
1
ofstream
This data type represents the output file stream and is used to create files
2
ifstream
This data type represents the input file stream and is used to read
This data type represents the file stream generally, and has the capabilities
of both ofstream and ifstream which means it can create files, write
To perform file processing in C++, header files <iostream> and <fstream> must be
Opening a File
A file must be opened before you can read from it or write to it. Either ofstream or
fstream object may be used to open a file for writing. And ifstream object is used to
Following is the standard syntax for open() function, which is a member of fstream,
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.
1
ios::app
Open a file for output and move the read/write control to the end of the file.
3
ios::in
4
ios::out
5
ios::trunc
If the file already exists, its contents will be truncated before opening the
file.
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
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as
follows −
fstream afile;
afile.open("file.dat", ios::out | ios::in );
Closing a File
When a C++ program terminates it automatically flushes all the streams, release all
the allocated memory and close all the opened files. But it is always a good practice
that a programmer should close all the opened files before program termination.
Following is the standard syntax for close() function, which is a member of fstream,
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 an ofstream or fstream
operator (>>) just as you use that operator to input information from the keyboard. The
only difference is that you use an ifstream or fstream object instead of the cin object.
Live Demo
#include <fstream>
#include <iostream>
using namespace std;
int main () {
char data[100];
return 0;
}
$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9
Above examples make use of additional functions from cin object, like getline()
function to read the line from outside and ignore() function to ignore the extra
pointer. These member functions are seekg ("seek get") for istream and seekp ("seek
The argument to seekg and seekp normally is a long integer. A second argument can
be specified to indicate the seek direction. The seek direction can be ios::beg (the
default) for positioning relative to the beginning of a stream, ios::cur for positioning
relative to the current position in a stream or ios::end for positioning relative to the end
of a stream.
pointer are −
Exceptions provide a way to transfer control from one part of a program to another. C+
+ exception handling is built upon three keywords: try, catch, and throw.
exception.
try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {
// catch block
}
You can list down multiple catch statements to catch different type of exceptions in
case your try block raises more than one exception in different situations.
Throwing Exceptions
Exceptions can be thrown anywhere within a code block using throw statement. The
operand of the throw statement determines a type for the exception and can be any
expression and the type of the result of the expression determines the type of
exception thrown.
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
try {
// protected code
} catch( ExceptionName e ) {
// code to handle ExceptionName exception
}
that is thrown in a try block, you must put an ellipsis, ..., between
try {
// protected code
} catch(...) {
// code to handle any exception
}
The following is an example, which throws a division by zero exception and we catch it
in catch block.
Live Demo
#include <iostream>
using namespace std;
int main () {
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
} catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}
If we compile and run above code, this would produce the following
result −
above hierarchy −
2
std::bad_alloc
3
std::bad_cast
4
std::bad_exception
5
std::bad_typeid
6
std::logic_error
7
std::domain_error
8
std::invalid_argument
This is thrown due to invalid arguments.
9
std::length_error
10
std::out_of_range
This can be thrown by the 'at' method, for example a std::vector and
std::bitset<>::operator[]().
11
std::runtime_error
12
std::overflow_error
13
std::range_error
This is occurred when you try to store a value which is out of range.
14
std::underflow_error
how you can use std::exception class to implement your own exception
in standard way −
Live Demo
#include <iostream>
#include <exception>
using namespace std;
int main() {
try {
throw MyException();
} catch(MyException& e) {
std::cout << "MyException caught" << std::endl;
std::cout << e.what() << std::endl;
} catch(std::exception& e) {
//Other errors
}
}
MyException caught
C++ Exception
Here, what() is a public method provided by exception class and it has been overridden
by all the child exception classes. This returns the cause of an exception.
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
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
If you are not in need of dynamically allocated memory anymore, you can use delete
operator, which de-allocates memory that was previously allocated by new operator.
new data-type;
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
time. We can do this using the new operator with the following
statements −
The memory may not have been allocated successfully, if the free
below −
The malloc() function from C, still exists in C++, but it is recommended to avoid using
malloc() function. The main advantage of new over malloc() is that new doesn't just
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
Let us put above concepts and form the following example to show how
int main () {
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
return 0;
}
If we compile and run above code, this would produce the following
result −
characters. Using the same syntax what we have used above we can allocate memory
To remove the array that we have just created the statement would
Live Demo
#include <iostream>
using namespace std;
class Box {
public:
Box() {
cout << "Constructor called!" <<endl;
}
~Box() {
cout << "Destructor called!" <<endl;
}
};
int main() {
Box* myBoxArray = new Box[4];
delete [] myBoxArray; // Delete array
return 0;
}
If you were to allocate an array of four Box objects, the Simple constructor would be
called four times and similarly while deleting these objects, destructor will also be
If we compile and run above code, this would produce the following
result −
Constructor called!
Constructor called!
Constructor called!
Constructor called!
Destructor called!
Destructor called!
Destructor called!
Destructor called!
Namespaces in C++
Consider a situation, when we have two persons with the same name, Zara, in the
same class. Whenever we need to differentiate them definitely we would have to use
some additional information along with their name, like either the area, if they live in
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
information to differentiate similar functions, classes, variables etc. with the same
name available in different libraries. Using namespace, you can define the context in
Defining a Namespace
namespace namespace_name {
// code declarations
}
Let us see how namespace scope the entities including variable and
functions −
Live Demo
#include <iostream>
using namespace std;
int main () {
// Calls function from first name space.
first_space::func();
return 0;
}
If we compile and run above code, this would produce the following
result −
Inside first_space
Inside second_space
You can also avoid prepending of namespaces with the using namespace
directive. This directive tells the compiler that the subsequent code
Live Demo
#include <iostream>
using namespace std;
return 0;
}
If we compile and run above code, this would produce the following
result −
Inside first_space
follows −
using std::cout;
but other items in the std namespace will still need to be explicit
as follows −
Live Demo
#include <iostream>
using std::cout;
int main () {
cout << "std::endl is used with std!" << std::endl;
return 0;
}
If we compile and run above code, this would produce the following
result −
Names introduced in a using directive obey normal scope rules. The name is visible
from the point of the using directive to the end of the scope in which the directive is
found. Entities with the same name defined in an outer scope are hidden.
Discontiguous Namespaces
A namespace can be defined in several parts and so a namespace is made up of the
sum of its separately defined parts. The separate parts of a namespace can be spread
existing one −
namespace namespace_name {
// code declarations
}
Nested Namespaces
Namespaces can be nested where you can define one namespace inside
operators as follows −
follows −
Live Demo
#include <iostream>
using namespace std;
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
library containers like iterators and algorithms are examples of generic programming
There is a single definition of each container, such as vector, but we can define many
Function Template
Live Demo
#include <iostream>
#include <string>
int main () {
int i = 39;
int j = 20;
cout << "Max(i, j): " << Max(i, j) << endl;
double f1 = 13.5;
double f2 = 20.7;
cout << "Max(f1, f2): " << Max(f1, f2) << endl;
string s1 = "Hello";
string s2 = "World";
cout << "Max(s1, s2): " << Max(s1, s2) << endl;
return 0;
}
If we compile and run above code, this would produce the following
result −
Max(i, j): 39
Max(f1, f2): 20.7
Max(s1, s2): World
Class Template
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.
generic methods to push and pop the elements from the stack −
Live Demo
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>
public:
void push(T const&); // push element
void pop(); // pop element
T top() const; // return top element
int main() {
try {
Stack<int> intStack; // stack of ints
Stack<string> stringStack; // stack of strings
If we compile and run above code, this would produce the following
result −
7
hello
Exception: Stack<>::pop(): empty stack
C++ Preprocessor
The preprocessors are the directives, which give instructions to the compiler to
All preprocessor directives begin with #, and only white-space characters may appear
You already have seen a #include directive in all the examples. This macro is used to
directives −
The #define Preprocessor
directive is −
#include <iostream>
using namespace std;
#define PI 3.14159
int main () {
cout << "Value of PI :" << PI << endl;
return 0;
}
option and redirect the result to test.p. Now, if you check test.p,
it will have lots of information and at the bottom, you will find the
...
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 −
Live Demo
#include <iostream>
using namespace std;
int main () {
int i, j;
i = 100;
j = 30;
return 0;
}
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 be used to compile selective portions of your
#ifndef NULL
#define NULL 0
#endif
You can compile a program for debugging purpose. You can also turn on
#ifdef DEBUG
cerr <<"Variable x = " << x << endl;
#endif
DEBUG. You can use #if 0 statment to comment out a portion of the
program as follows −
#if 0
code prevented from compiling
#endif
Live Demo
#include <iostream>
using namespace std;
#define DEBUG
int main () {
int i, j;
i = 100;
j = 30;
#ifdef DEBUG
cerr <<"Trace: Inside main function" << endl;
#endif
#if 0
/* This is commented part */
cout << MKSTR(HELLO C++) << endl;
#endif
#ifdef DEBUG
cerr <<"Trace: Coming out of main function" << endl;
#endif
return 0;
}
If we compile and run above code, this would produce the following
result −
The minimum is 30
Trace: Inside main function
Trace: Coming out of main function
quotes.
Live Demo
#include <iostream>
using namespace std;
#define MKSTR( x ) #x
int main () {
return 0;
}
If we compile and run above code, this would produce the following
result −
HELLO C++
#define CONCAT( x, y ) x ## y
When CONCAT appears in the program, its arguments are concatenated and used to
replace the macro. For example, CONCAT(HELLO, C++) is replaced by "HELLO C++" in
Live Demo
#include <iostream>
using namespace std;
#define concat(a, b) a ## b
int main() {
int xy = 100;
If we compile and run above code, this would produce the following
result −
100
preprocessor transforms −
1
__LINE__
This contains the current line number of the program when it is being
compiled.
2
__FILE__
This contains the current file name of the program when it is being compiled.
3
__DATE__
This contains a string of the form month/day/year that is the date of the
4
__TIME__
Live Demo
#include <iostream>
using namespace std;
int main () {
cout << "Value of __LINE__ : " << __LINE__ << endl;
cout << "Value of __FILE__ : " << __FILE__ << endl;
cout << "Value of __DATE__ : " << __DATE__ << endl;
cout << "Value of __TIME__ : " << __TIME__ << endl;
return 0;
}
If we compile and run above code, this would produce the following
result −
Value of __LINE__ : 6
Value of __FILE__ : test.cpp
Value of __DATE__ : Feb 28 2011
Value of __TIME__ : 18:52:48
C++ Signal Handling
Signals are the interrupts delivered to a process by the operating system which can
There are signals which can not be caught by the program but there is a following list
of signals which you can catch in your program and can take appropriate actions based
on the signal. These signals are defined in C++ header file <csignal>.
1
SIGABRT
2
SIGFPE
resulting in overflow.
3
SIGILL
4
SIGINT
6
SIGTERM
Keeping it simple, this function receives two arguments: first argument as an integer
which represents signal number and second argument as a pointer to the signal-
handling function.
Let us write a simple C++ program where we will catch SIGINT signal
program, you must register that signal using signal function and
#include <iostream>
#include <csignal>
exit(signum);
}
int main () {
// register signal SIGINT and signal handler
signal(SIGINT, signalHandler);
while(1) {
cout << "Going to sleep...." << endl;
sleep(1);
}
return 0;
}
following result −
Going to sleep....
Going to sleep....
Going to sleep....
Now, press Ctrl+c to interrupt the program and you will see that your
program will catch the signal and would come out by printing
something as follows −
Going to sleep....
Going to sleep....
Going to sleep....
Interrupt signal (2) received.
Here, sig is the signal number to send any of the signals: SIGINT,
follows −
#include <iostream>
#include <csignal>
exit(signum);
}
int main () {
int i = 0;
// register signal SIGINT and signal handler
signal(SIGINT, signalHandler);
while(++i) {
cout << "Going to sleep...." << endl;
if( i == 3 ) {
raise( SIGINT);
}
sleep(1);
}
return 0;
}
Going to sleep....
Going to sleep....
Going to sleep....
Interrupt signal (2) received.
C++ Multithreading
Multithreading is a specialized form of multitasking and a multitasking is the feature
that allows your computer to run two or more programs concurrently. In general, there
based multitasking deals with the concurrent execution of pieces of the same program.
A multithreaded program contains two or more parts that can run concurrently. Each
part of such a program is called a thread, and each thread defines a separate path of
execution.
Before C++ 11, there is no built-in support for multithreaded applications. Instead, it
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,
#include <pthread.h>
pthread_create (thread, attr, start_routine, arg)
This routine can be called any number of times from anywhere within
1
thread
An opaque, unique identifier for the new thread returned by the subroutine.
2
attr
An opaque attribute object that may be used to set thread attributes. You can
3
start_routine
The C++ routine that the thread will execute once it is created.
4
arg
to be passed.
dependent. Once created, threads are peers, and may create other threads. There is no
Terminating Threads
#include <pthread.h>
pthread_exit (status)
routine is called after a thread has completed its work and is no longer required to
exist.
If main() finishes before the threads it has created, and exits with pthread_exit(), the
Example
This simple example code creates 5 threads with the pthread_create() routine. Each
thread prints a "Hello World!" message, and then terminates with a call to
pthread_exit().
#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
#define NUM_THREADS 5
int main () {
pthread_t threads[NUM_THREADS];
int rc;
int i;
if (rc) {
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
pthread_exit(NULL);
}
You can pass any data type in a thread callback because it points to
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#define NUM_THREADS 5
struct thread_data {
int thread_id;
char *message;
};
pthread_exit(NULL);
}
int main () {
pthread_t threads[NUM_THREADS];
struct thread_data td[NUM_THREADS];
int rc;
int i;
for( i = 0; i < NUM_THREADS; i++ ) {
cout <<"main() : creating thread, " << i << endl;
td[i].thread_id = i;
td[i].message = "This is message";
rc = pthread_create(&threads[i], NULL, PrintHello, (void *)&td[i]);
if (rc) {
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
pthread_exit(NULL);
}
following result −
There are following two routines which we can use to join or detach
threads −
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
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>
#define NUM_THREADS 5
tid = (long)t;
sleep(1);
cout << "Sleeping in thread " << endl;
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;
if (rc) {
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
following result −
What is CGI?
The Common Gateway Interface, or CGI, is a set of standards that define how
The CGI specs are currently maintained by the NCSA and NCSA
Web Browsing
To understand the concept of CGI, let's see what happens when we click a hyperlink to
Your browser contacts the HTTP web server and demand for the URL ie.
filename.
Web Server will parse the URL and will look for the filename. If it finds
requested file then web server sends that file back to the browser
otherwise sends an error message indicating that you have requested a
wrong file.
Web browser takes response from web server and displays either the
However, it is possible to set up the HTTP server in such a way that whenever a file in
a certain directory is requested, that file is not sent back; instead it is executed as a
program, and produced output from the program is sent back to your browser to
display.
The Common Gateway Interface (CGI) is a standard protocol for enabling applications
(called CGI programs or CGI scripts) to interact with Web servers and with clients.
These CGI programs can be a written in Python, PERL, Shell, C or C++ etc.
CGI and it is configured to handle CGI Programs. All the CGI Programs to be executed
by the HTTP server are kept in a pre-configured directory. This directory is called CGI
your CGI scripts, you can modify the following section in the
httpd.conf file −
<Directory "/var/www/cgi-bin">
AllowOverride None
Options ExecCGI
Order allow,deny
Allow from all
</Directory>
<Directory "/var/www/cgi-bin">
Options All
</Directory>
Here, I assume that you have Web Server up and running successfully and you are
able to run any other CGI program like Perl or Shell etc.
#include <iostream>
using namespace std;
int main () {
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>Hello World - First CGI Program</title>\n";
cout << "</head>\n";
cout << "<body>\n";
cout << "<h2>Hello World! This is my first CGI program</h2>\n";
cout << "</body>\n";
cout << "</html>\n";
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
file i.e. screen. There is one important and extra feature available which is first line
printing Content-type:text/html\r\n\r\n. This line is sent back to the browser and specify
the content type to be displayed on the browser screen. Now you must have
understood the basic concept of CGI and you can write many complicated CGI
programs using Python. A C++ CGI program can interact with any other external
HTTP Header
which is sent to the browser to understand the content. All the HTTP
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.
1
Content-type:
A MIME string defining the format of the file being returned. Example is
Content-type:text/html.
2
Expires: Date
The date the information becomes invalid. This should be used by the
3
Location: URL
The URL that should be returned instead of the URL requested. You can use
4
Last-modified: Date
5
Content-length: N
The length, in bytes, of the data being returned. The browser uses this value
6
Set-Cookie: String
1
CONTENT_TYPE
The data type of the content, used when the client is sending attached
2
CONTENT_LENGTH
The length of the query information that is available only for POST requests.
3
HTTP_COOKIE
Returns the set cookies in the form of key & value pair.
4
HTTP_USER_AGENT
5
PATH_INFO
6
QUERY_STRING
The URL-encoded information that is sent with GET method request.
7
REMOTE_ADDR
The IP address of the remote host making the request. This can be useful for
8
REMOTE_HOST
The fully qualified name of the host making the request. If this information is
9
REQUEST_METHOD
The method used to make the request. The most common methods are GET
and POST.
10
SCRIPT_FILENAME
11
SCRIPT_NAME
12
SERVER_NAME
Here is small CGI program to list out all the CGI variables.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main () {
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>CGI Environment Variables</title>\n";
cout << "</head>\n";
cout << "<body>\n";
cout << "<table border = \"0\" cellspacing = \"2\">";
return 0;
}
is a CGI library written for C++ program which you can download from
You can check related documentation available at ‘C++ CGI Lib Documentation.
from your browser to web server and ultimately to your CGI Program. Most frequently
browser uses two methods to pass this information to web server. These methods are
page request. The page and the encoded information are separated by
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.
When using GET method, information is passed using QUERY_STRING http header
variable.
You can pass information by simply concatenating key and value pairs alongwith any
URL or you can use HTML <FORM> tags to pass information using GET method.
method.
/cgi-bin/cpp_get.cgi?first_name=ZARA&last_name=ALI
input given by web browser. We are going to use C++ CGI library which
#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;
form_iterator fi = formData.getElement("first_name");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "First name: " << **fi << endl;
} else {
cout << "No text entered for first name" << endl;
}
/cgi-bin/cpp_get.cgi?first_name=ZARA&last_name=ALI
button. We are going to use same CGI script cpp_get.cgi to handle this input.
method. This packages the information in exactly the same way as GET methods, but
message. This message comes into the CGI script in the form of the standard input.
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 −
Maths Physics
Below is C++ program, which will generate cpp_checkbox.cgi script to handle input
#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;
bool maths_flag, physics_flag;
maths_flag = formData.queryCheckbox("maths");
if( maths_flag ) {
cout << "Maths Flag: ON " << endl;
} else {
cout << "Maths Flag: OFF " << endl;
}
cout << "<br/>\n";
physics_flag = formData.queryCheckbox("physics");
if( physics_flag ) {
cout << "Physics Flag: ON " << endl;
} else {
cout << "Physics Flag: OFF " << endl;
}
return 0;
}
Here is example HTML code for a form with two radio button −
Maths Physics
Below is C++ program, which will generate cpp_radiobutton.cgi script to handle input
#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>
form_iterator fi = formData.getElement("subject");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "Radio box selected: " << **fi << endl;
}
return 0;
}
#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;
form_iterator fi = formData.getElement("textcontent");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "Text Content: " << **fi << endl;
} else {
cout << "No text entered" << endl;
}
return 0;
}
Passing Drop down Box Data to CGI Program
Drop down Box is used when we have many options available but only one or two will
be selected.
Here is example HTML code for a form with one drop down box −
Maths Physics
Below is C++ program, which will generate cpp_dropdown.cgi script to handle input
#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;
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>Drop Down Box Data to CGI</title>\n";
cout << "</head>\n";
cout << "<body>\n";
form_iterator fi = formData.getElement("dropdown");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "Value Selected: " << **fi << endl;
}
return 0;
}
maintain session information among different pages. For example one user registration
ends after completing many pages. But how to maintain user's session information
In many situations, using cookies is the most efficient method of remembering and
How It Works
Your server sends some data to the visitor's browser in the form of a cookie. The
browser may accept the cookie. If it does, it is stored as a plain text record on the
visitor's hard drive. Now, when the visitor arrives at another page on your site, the
cookie is available for retrieval. Once retrieved, your server knows/remembers what
was stored.
blank, the cookie will expire when the visitor quits the
browser.
Path − This shows path to the directory or web page that set
Setting up Cookies
It is very easy to send cookies to browser. These cookies will be sent along with HTTP
Header before the Content-type filed. Assuming you want to set UserID and Password
#include <iostream>
using namespace std;
int main () {
cout << "Set-Cookie:UserID = XYZ;\r\n";
cout << "Set-Cookie:Password = XYZ123;\r\n";
cout << "Set-Cookie:Domain = www.tutorialspoint.com;\r\n";
cout << "Set-Cookie:Path = /perl;\n";
cout << "Content-type:text/html\r\n\r\n";
return 0;
}
From this example, you must have understood how to set cookies. We use Set-Cookie
Here, it is optional to set cookies attributes like Expires, Domain, and Path. It is notable
computer −
/cgi-bin/setcookies.cgi
Retrieving Cookies
It is easy to retrieve all the set cookies. Cookies are stored in CGI environment variable
#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
int main () {
Cgicc cgi;
const_cookie_iterator cci;
return 0;
}
/cgi-bin/getcookies.cgi
This will produce a list of all the four cookies set in previous
UserID XYZ
Password XYZ123
Domain www.tutorialspoint.com
Path /perl
data. The input tag with the file type will create a "Browse" button.
<html>
<body>
<form enctype = "multipart/form-data" action = "/cgi-bin/cpp_uploadfile.cgi"
method = "post">
<p>File: <input type = "file" name = "userfile" /></p>
<p><input type = "submit" value = "Upload" /></p>
</form>
</body>
</html>
File:
Note − Above example has been disabled intentionally to stop people
uploading files on our server. But you can try above code with your
server.
#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
int main () {
Cgicc cgi;
return 0;
}
The above example is for writing content at cout stream but you can open your file
stream and save the content of uploaded file in a file at desired location.
Hope you have enjoyed this tutorial. If yes, please send us your feedback.
Discuss C++
C++ is a middle-level programming language developed by Bjarne Stroustrup starting
in 1979 at Bell Labs. C++ runs on a variety of platforms, such as Windows, Mac OS,
and the various versions of UNIX. This tutorial adopts a simple and practical approach
to describe the concepts of C++.