0% found this document useful (0 votes)
29 views122 pages

C++ Part III

The document discusses inheritance in C++. It explains that inheritance allows a class to inherit attributes and behaviors from a parent class, making it easier to create and maintain applications. It also covers different types of inheritance like public, protected and private inheritance and multiple inheritance.

Uploaded by

randrandraina1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views122 pages

C++ Part III

The document discusses inheritance in C++. It explains that inheritance allows a class to inherit attributes and behaviors from a parent class, making it easier to create and maintain applications. It also covers different types of inheritance like public, protected and private inheritance and multiple inheritance.

Uploaded by

randrandraina1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 122

C++

// Print total number of objects after creating object.


cout << "Final Stage Count: " << Box::getCount() << endl;

return 0;
}

When the above code is compiled and executed, it produces the following result:

Inital Stage Count: 0


Constructor called.
Constructor called.
Final Stage Count: 2

189
C++

24. INHERITANCE

One of the most important concepts in object-oriented programming is that of


inheritance. Inheritance allows us to define a class in terms of another class,
which makes it easier to create and maintain an application. This also provides
an opportunity to reuse the code functionality and fast implementation time.

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 class is referred to as the derived class.

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.

Base & Derived Classes

A class can be derived from more than one classes, which means it can inherit
data and functions from multiple base classes. To define a derived class, we use
a class derivation list to specify the base class(es). A class derivation list names
one or more base classes and has the form:

class derived-class: access-specifier base-class

Where access-specifier is one of public, protected, or private, and base-class


is the name of a previously defined class. If the access-specifier is not used,
then it is private by default.

Consider a base class Shape and its derived class Rectangle as follows:

#include <iostream>

using namespace std;

// Base class
class Shape
{
public:
void setWidth(int w)
{
width = w;
}

190
C++

void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};

// Derived class
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};

int main(void)
{
Rectangle Rect;

Rect.setWidth(5);
Rect.setHeight(7);

// Print the area of the object.


cout << "Total area: " << Rect.getArea() << endl;

return 0;
}

When the above code is compiled and executed, it produces the following result:

191
C++

Total area: 35

Access Control and Inheritance

A derived class can access all the non-private members of its base class. Thus
base-class members that should not be accessible to the member functions of
derived classes should be declared private in the base class.

We can summarize the different access types according to - who can access
them, in the following way:

Access public protected private

Same class yes yes yes

Derived classes yes yes no

Outside classes yes no no

A derived class inherits all base class methods with the following exceptions:

 Constructors, destructors and copy constructors of the base class.

 Overloaded operators of the base class.

 The friend functions of the base class.

Type of Inheritance

When deriving a class from a base class, the base class may be inherited
through public, protected or private inheritance. The type of inheritance is
specified by the access-specifier as explained above.

We hardly use protected or private inheritance, but public inheritance is


commonly used. While using different type of inheritance, following rules are
applied:

 Public Inheritance: When deriving a class from a public base


class, public members of the base class become public members of the
derived class and protected members of the base class
become protected members of the derived class. A base
class's private members are never accessible directly from a derived
class, but can be accessed through calls to
the public and protected members of the base class.

 Protected Inheritance: When deriving from a protected base


class, public and protected members of the base class
become protected members of the derived class.

192
C++

 Private Inheritance: When deriving from a private base


class, public and protected members of the base class
become private members of the derived class.

Multiple Inheritance

A C++ class can inherit members from more than one class and here is the
extended syntax:

class derived-class: access baseA, access baseB....

Where access is one of public, protected, or private and would be given for
every base class and they will be separated by comma as shown above. Let us
try the following example:

#include <iostream>

using namespace std;

// Base class Shape


class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};

// Base class PaintCost


class PaintCost
{

193
C++

public:
int getCost(int area)
{
return area * 70;
}
};

// 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();

// Print the area of the object.


cout << "Total area: " << Rect.getArea() << endl;

// Print the total cost of painting


cout << "Total paint cost: $" << Rect.getCost(area) << endl;

return 0;

194
C++

When the above code is compiled and executed, it produces the following result:

Total area: 35
Total paint cost: $2450

195
C++

25. OVERLOADING (OPERATOR &


FUNCTION)
C++ allows you to specify more than one definition for a function name or
an operator in the same scope, which is called function
overloading and operator overloading respectively.

An overloaded declaration is a declaration that is declared with the same name


as a previously declared declaration in the same scope, except that both
declarations have different arguments and obviously different definition
(implementation).

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 process of selecting the most appropriate overloaded function or
operator is called overload resolution.

Function Overloading in C++

You can have multiple definitions for the same function name in the same scope.
The 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 only by return type.

Following is the example where same function print() is being used to print
different data types:

#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;
}

196
C++

void print(char* c) {
cout << "Printing character: " << c << endl;
}
};

int main(void)
{
printData pd;

// Call print to print integer


pd.print(5);
// Call print to print float
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");

return 0;
}

When the above code is compiled and executed, it produces the following result:

Printing int: 5
Printing float: 500.263
Printing character: Hello C++

Operators Overloading in C++

You can redefine or overload most of the built-in operators available in C++.
Thus, a programmer can use operators with user-defined types as well.

Overloaded operators are functions with special names the keyword operator
followed by the symbol for the operator being defined. Like any other function,
an overloaded operator has a return type and a parameter list.

Box operator+(const Box&);

Declares the addition operator that can be used to add two Box objects and
returns final Box object. Most overloaded operators may be defined as ordinary
non-member functions or as class member functions. In case we define above
function as non-member function of a class then we would have to pass two
arguments for each operand as follows:
197
C++

Box operator+(const Box&, const Box&);

Following is the example to show the concept of operator over loading using a
member function. Here an object is passed as an argument whose properties will
be accessed using this object, the object which will call this operator can be
accessed using this operator as explained below:

#include <iostream>
using namespace std;

class Box
{
public:

double getVolume(void)
{
return length * breadth * height;
}
void setLength( double len )
{
length = len;
}

void setBreadth( double bre )


{
breadth = bre;
}

void setHeight( double hei )


{
height = hei;
}
// Overload + operator to add two Box objects.
Box operator+(const Box& b)
{
Box box;

198
C++

box.length = this->length + b.length;


box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
// Main function for the program
int main( )
{
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here

// 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();

199
C++

cout << "Volume of Box2 : " << volume <<endl;

// Add two object as follows:


Box3 = Box1 + Box2;

// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;

return 0;
}

When the above code is compiled and executed, it produces the following result:

Volume of Box1 : 210


Volume of Box2 : 1560
Volume of Box3 : 5400

Overloadable/Non-overloadable Operators

Following is the list of operators which can be overloaded:

+ - * / % ^

& | ~ ! , =

< > <= >= ++ --

<< >> == != && ||

+= -= /= %= ^= &=

|= *= <<= >>= [] ()

-> ->* new new [] delete delete []

Following is the list of operators, which cannot be overloaded:

200
C++

:: .* . ?:

Operator Overloading Examples

Here are various operator overloading examples to help you in understanding


the concept.

S.N. Operators and Example

1 Unary operators overloading

2 Binary operators overloading

3 Relational operators overloading

4 Input/Output operators overloading

5 ++ and -- operators overloading

6 Assignment operators overloading

7 Function call () operator overloading

8 Subscripting [] operator overloading

9 Class member access operator -> overloading

Unary Operators Overloading

The unary operators operate on a single operand and following are the examples
of Unary operators:

 The increment (++) and decrement (--) operators.

 The unary minus (-) operator.

 The logical not (!) operator.

The unary operators operate on the object for which they were called and
normally, this operator appears on the left side of the object, as in !obj, -obj,
and ++obj but sometime they can be used as postfix as well like obj++ or obj--.

Following example explain how minus (-) operator can be overloaded for prefix
as well as postfix usage.

201
C++

#include <iostream>
using namespace std;

class Distance
{
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
// method to display distance
void displayDistance()
{
cout << "F: " << feet << " I:" << inches <<endl;
}
// overloaded minus (-) operator
Distance operator- ()
{
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
};
int main()
{
Distance D1(11, 10), D2(-5, 11);

202
C++

-D1; // apply negation


D1.displayDistance(); // display D1

-D2; // apply negation


D2.displayDistance(); // display D2

return 0;
}

When the above code is compiled and executed, it produces the following result:

F: -11 I:-10
F: 5 I:-11

Hope above example makes your concept clear and you can apply similar
concept to overload Logical Not Operators (!).

Increment (++) and Decrement (- -) Operators

The increment (++) and decrement (--) operators are two important unary
operators available in C++.

Following example explain how increment (++) operator can be overloaded for
prefix as well as postfix usage. Similar way, you can overload operator (--).

#include <iostream>
using namespace std;

class Time
{
private:
int hours; // 0 to 23
int minutes; // 0 to 59
public:
// required constructors
Time(){
hours = 0;
minutes = 0;
}
203
C++

Time(int h, int m){


hours = h;
minutes = m;
}
// method to display time
void displayTime()
{
cout << "H: " << hours << " M:" << minutes <<endl;
}
// overloaded prefix ++ operator
Time operator++ ()
{
++minutes; // increment this object
if(minutes >= 60)
{
++hours;
minutes -= 60;
}
return Time(hours, minutes);
}
// overloaded postfix ++ operator
Time operator++( int )
{
// save the orignal value
Time T(hours, minutes);
// increment this object
++minutes;
if(minutes >= 60)
{
++hours;
minutes -= 60;
}
// return old original value
return T;

204
C++

}
};
int main()
{
Time T1(11, 59), T2(10,40);

++T1; // increment T1
T1.displayTime(); // display T1
++T1; // increment T1 again
T1.displayTime(); // display T1

T2++; // increment T2
T2.displayTime(); // display T2
T2++; // increment T2 again
T2.displayTime(); // display T2
return 0;
}

When the above code is compiled and executed, it produces the following result:

H: 12 M:0
H: 12 M:1
H: 10 M:41
H: 10 M:42

Binary Operators Overloading

The unary operators take two arguments and following are the examples of
Binary operators. You use binary operators very frequently like addition (+)
operator, subtraction (-) operator and division (/) operator.

Following example explains how addition (+) operator can be overloaded.


Similar way, you can overload subtraction (-) and division (/) operators.

#include <iostream>
using namespace std;

205
C++

class Box
{
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
public:

double getVolume(void)
{
return length * breadth * height;
}
void setLength( double len )
{
length = len;
}

void setBreadth( double bre )


{
breadth = bre;
}

void setHeight( double hei )


{
height = hei;
}
// Overload + operator to add two Box objects.
Box operator+(const Box& b)
{
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;

206
C++

}
};
// Main function for the program
int main( )
{
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here

// 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;

// Add two object as follows:


Box3 = Box1 + Box2;

// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;

207
C++

return 0;
}

When the above code is compiled and executed, it produces the following result:

Volume of Box1 : 210


Volume of Box2 : 1560
Volume of Box3 : 5400

Relational Operators Overloading

There are various relational operators supported by C++ language like (<, >,
<=, >=, ==, etc.) which can be used to compare C++ built-in data types.

You can overload any of these operators, which can be used to compare the
objects of a class.

Following example explains how a < operator can be overloaded and similar way
you can overload other relational operators.

#include <iostream>
using namespace std;

class Distance
{
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
// method to display distance
208
C++

void displayDistance()
{
cout << "F: " << feet << " I:" << inches <<endl;
}
// overloaded minus (-) operator
Distance operator- ()
{
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
// overloaded < operator
bool operator <(const Distance& d)
{
if(feet < d.feet)
{
return true;
}
if(feet == d.feet && inches < d.inches)
{
return true;
}
return false;
}
};
int main()
{
Distance D1(11, 10), D2(5, 11);

if( D1 < D2 )
{
cout << "D1 is less than D2 " << endl;
}
else

209
C++

{
cout << "D2 is less than D1 " << endl;
}
return 0;
}

When the above code is compiled and executed, it produces the following result:

D2 is less than D1

Input/Output Operators Overloading

C++ is able to input and output the built-in data types using the stream
extraction operator >> and the stream insertion operator <<. The stream
insertion and stream extraction operators also can be overloaded to perform
input and output for user-defined types like an object.

Here, it is important to make operator overloading function a friend of the class


because it would be called without creating an object.

Following example explains how extraction operator >> and insertion operator
<<.

#include <iostream>
using namespace std;

class Distance
{
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;

210
C++

}
friend ostream &operator<<( ostream &output,
const Distance &D )
{
output << "F : " << D.feet << " I : " << D.inches;
return output;
}

friend istream &operator>>( istream &input, Distance &D )


{
input >> D.feet >> D.inches;
return input;
}
};
int main()
{
Distance D1(11, 10), D2(5, 11), D3;

cout << "Enter the value of object : " << endl;


cin >> D3;
cout << "First Distance : " << D1 << endl;
cout << "Second Distance :" << D2 << endl;
cout << "Third Distance :" << D3 << endl;

return 0;
}

When the above code is compiled and executed, it produces the following result:

$./a.out
Enter the value of object :
70
10
First Distance : F : 11 I : 10

211
C++

Second Distance :F : 5 I : 11
Third Distance :F : 70 I : 10

++ and - - Operators Overloading

The increment (++) and decrement (--) operators are two important unary
operators available in C++.

Following example explain how increment (++) operator can be overloaded for
prefix as well as postfix usage. Similar way, you can overload operator (--).

#include <iostream>
using namespace std;

class Time
{
private:
int hours; // 0 to 23
int minutes; // 0 to 59
public:
// required constructors
Time(){
hours = 0;
minutes = 0;
}
Time(int h, int m){
hours = h;
minutes = m;
}
// method to display time
void displayTime()
{
cout << "H: " << hours << " M:" << minutes <<endl;
}
// overloaded prefix ++ operator
Time operator++ ()
{

212
C++

++minutes; // increment this object


if(minutes >= 60)
{
++hours;
minutes -= 60;
}
return Time(hours, minutes);
}
// overloaded postfix ++ operator
Time operator++( int )
{
// save the orignal value
Time T(hours, minutes);
// increment this object
++minutes;
if(minutes >= 60)
{
++hours;
minutes -= 60;
}
// return old original value
return T;
}
};
int main()
{
Time T1(11, 59), T2(10,40);

++T1; // increment T1
T1.displayTime(); // display T1
++T1; // increment T1 again
T1.displayTime(); // display T1

T2++; // increment T2

213
C++

T2.displayTime(); // display T2
T2++; // increment T2 again
T2.displayTime(); // display T2
return 0;
}

When the above code is compiled and executed, it produces the following result:

H: 12 M:0
H: 12 M:1
H: 10 M:41
H: 10 M:42

Assignment Operators Overloading

You can overload the assignment operator (=) just as you can other operators
and it can be used to create an object just like the copy constructor.

Following example explains how an assignment operator can be overloaded.

#include <iostream>
using namespace std;

class Distance
{
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}

214
C++

void operator=(const Distance &D )


{
feet = D.feet;
inches = D.inches;
}
// method to display distance
void displayDistance()
{
cout << "F: " << feet << " I:" << inches << endl;
}

};
int main()
{
Distance D1(11, 10), D2(5, 11);

cout << "First Distance : ";


D1.displayDistance();
cout << "Second Distance :";
D2.displayDistance();

// use assignment operator


D1 = D2;
cout << "First Distance :";
D1.displayDistance();

return 0;
}

When the above code is compiled and executed, it produces the following result:

First Distance : F: 11 I:10


Second Distance :F: 5 I:11
First Distance :F: 5 I:11

Function Call () Operator Overloading


215
C++

The function call operator () can be overloaded for objects of class type. When
you overload ( ), you are not creating a new way to call a function. Rather, you
are creating an operator function that can be passed an arbitrary number of
parameters.

Following example explains how a function call operator () can be overloaded.

#include <iostream>
using namespace std;

class Distance
{
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
// overload function call
Distance operator()(int a, int b, int c)
{
Distance D;
// just put random calculation
D.feet = a + c + 10;
D.inches = b + c + 100 ;
return D;
}
// method to display distance
void displayDistance()
{
216
C++

cout << "F: " << feet << " I:" << inches << endl;
}

};
int main()
{
Distance D1(11, 10), D2;

cout << "First Distance : ";


D1.displayDistance();

D2 = D1(10, 10, 10); // invoke operator()


cout << "Second Distance :";
D2.displayDistance();

return 0;
}

When the above code is compiled and executed, it produces the following result:

First Distance : F: 11 I:10


Second Distance :F: 30 I:120

Subscripting [ ] Operator Overloading

The subscript operator [] is normally used to access array elements. This


operator can be overloaded to enhance the existing functionality of C++ arrays.

Following example explains how a subscript operator [] can be overloaded.

#include <iostream>
using namespace std;
const int SIZE = 10;

class safearay
{
private:

217
C++

int arr[SIZE];
public:
safearay()
{
register int i;
for(i = 0; i < SIZE; i++)
{
arr[i] = i;
}
}
int &operator[](int i)
{
if( i > SIZE )
{
cout << "Index out of bounds" <<endl;
// return first element.
return arr[0];
}
return arr[i];
}
};
int main()
{
safearay A;

cout << "Value of A[2] : " << A[2] <<endl;


cout << "Value of A[5] : " << A[5]<<endl;
cout << "Value of A[12] : " << A[12]<<endl;

return 0;
}

When the above code is compiled and executed, it produces the following result:

Value of A[2] : 2

218
C++

Value of A[5] : 5
Index out of bounds
Value of A[12] : 0

Class Member Access Operator - > Overloading

The class member access operator (->) can be overloaded but it is bit trickier. It
is defined to give a class type a "pointer-like" behavior. The operator -> must be
a member function. If used, its return type must be a pointer or an object of a
class to which you can apply.

The operator-> is used often in conjunction with the pointer-dereference


operator * to implement "smart pointers." These pointers are objects that
behave like normal pointers except they perform other tasks when you access
an object through them, such as automatic object deletion either when the
pointer is destroyed, or the pointer is used to point to another object.

The dereferencing operator-> can be defined as a unary postfix operator. That


is, given a class:

class Ptr{
//...
X * operator->();
};

Objects of class Ptr can be used to access members of class X in a very similar
manner to the way pointers are used. For example:

void f(Ptr p )
{
p->m = 10 ; // (p.operator->())->m = 10
}

The statement p->m is interpreted as (p.operator->())->m. Using the same


concept, following example explains how a class access operator -> can be
overloaded.

#include <iostream>
#include <vector>
using namespace std;

// Consider an actual class.


class Obj {

219
C++

static int i, j;
public:
void f() const { cout << i++ << endl; }
void g() const { cout << j++ << endl; }
};

// Static member definitions:


int Obj::i = 10;
int Obj::j = 12;

// Implement a container for the above class


class ObjContainer {
vector<Obj*> a;
public:
void add(Obj* obj)
{
a.push_back(obj); // call vector's standard method.
}
friend class SmartPointer;
};

// implement smart pointer to access member of Obj class.


class SmartPointer {
ObjContainer oc;
int index;
public:
SmartPointer(ObjContainer& objc)
{
oc = objc;
index = 0;
}
// Return value indicates end of list:
bool operator++() // Prefix version
{

220
C++

if(index >= oc.a.size()) return false;


if(oc.a[++index] == 0) return false;
return true;
}
bool operator++(int) // Postfix version
{
return operator++();
}
// overload operator->
Obj* operator->() const
{
if(!oc.a[index])
{
cout << "Zero value";
return (Obj*)0;
}
return oc.a[index];
}
};

int main() {
const int sz = 10;
Obj o[sz];
ObjContainer oc;
for(int i = 0; i < sz; i++)
{
oc.add(&o[i]);
}
SmartPointer sp(oc); // Create an iterator
do {
sp->f(); // smart pointer call
sp->g();
} while(sp++);
return 0;

221
C++

When the above code is compiled and executed, it produces the following result:

10
12
11
13
12
14
13
15
14
16
15
17
16
18
17
19
18
20
19
21

222
C++

26. POLYMORPHISM

The word polymorphism means having many forms. Typically, polymorphism


occurs when there is a hierarchy of classes and they are related by inheritance.

C++ polymorphism means that a call to a member function will cause a different
function to be executed depending on the type of object that invokes the
function.

Consider the following example where a base class has been derived by other
two classes:

#include <iostream>
using namespace std;

class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
int area()
{
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape{
public:
Rectangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << "Rectangle class area :" <<endl;

223
C++

return (width * height);


}
};
class Triangle: public Shape{
public:
Triangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
// Main function for the program
int main( )
{
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);

// store the address of Rectangle


shape = &rec;
// call rectangle area.
shape->area();

// store the address of Triangle


shape = &tri;
// call triangle area.
shape->area();

return 0;
}

224
C++

When the above code is compiled and executed, it produces the following result:

Parent class area


Parent class area

The reason for the incorrect output is that the call of the function area() is being
set once by the compiler as the version defined in the base class. This is
called static resolution of the function call, or static linkage - the function call
is fixed before the program is executed. This is also sometimes called early
binding because the area() function is set during the compilation of the
program.

But now, let's make a slight modification in our program and precede the
declaration of area() in the Shape class with the keyword virtual so that it looks
like this:

class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
virtual int area()
{
cout << "Parent class area :" <<endl;
return 0;
}
};

After this slight modification, when the previous example code is compiled and
executed, it produces the following result:

Rectangle class area


Triangle class area

This time, the compiler looks at the contents of the pointer instead of its type.
Hence, since addresses of objects of tri and rec classes are stored in *shape the
respective area() function is called.

225
C++

As you can see, each of the child classes has a separate implementation for the
function area(). This is how polymorphism is generally used. You have different
classes with a function of the same name, and even the same parameters, but
with different implementations.

Virtual Function

A virtual function is a function in a base class that is declared using the


keyword virtual. Defining in a base class a virtual function, with another version
in a derived class, signals to the compiler that we don't want static linkage for
this function.

What we do want is the selection of the function to be called at any given point
in the program to be based on the kind of object for which it is called. This sort
of operation is referred to as dynamic linkage, or late binding.

Pure Virtual Functions

It is possible that you want to include a virtual function in a base class so that it
may be redefined in a derived class to suit the objects of that class, but that
there is no meaningful definition you could give for the function in the 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;
}
// pure virtual function
virtual int area() = 0;
};

The = 0 tells the compiler that the function has no body and above virtual
function will be called pure virtual function.

226
C++

27. DATA ABSTRACTION

Data abstraction refers to providing only essential information to the outside


world and hiding their background details, i.e., to represent the needed
information in program without presenting the details.

Data abstraction is a programming (and design) technique that relies on the


separation of interface and implementation.

Let's take one real life example of a TV, which you can turn on and off, change
the channel, adjust the volume, and add external components such as speakers,
VCRs, and DVD players, BUT you do not know its internal details, that is, you do
not know how it receives signals over the air or through a cable, how it
translates them, and finally displays them on the screen.

Thus, we can say a television clearly separates its internal implementation from
its external interface and you can play with its interfaces like the power button,
channel changer, and volume control without having zero knowledge of its
internals.

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 standard output like
this:

#include <iostream>
using namespace std;

int main( )
{
cout << "Hello C++" <<endl;
return 0;
}

227
C++

Here, you don't need to understand how cout displays the text on the user's
screen. You need to only know the public interface and the underlying
implementation of ‘cout’ is free to change.

Access Labels Enforce Abstraction

In C++, we use access labels to define the abstract interface to the class. A
class may contain zero or more access labels:

 Members defined with a public label are accessible to all parts of the
program. The data-abstraction view of a type is defined by its public
members.

 Members defined with a private label are not accessible to code that uses
the class. The private sections hide the implementation from code that
uses the type.

There are no restrictions on how often an access label may appear. Each access
label specifies the access level of the succeeding member definitions. The
specified access level remains in effect until the next access label is encountered
or the closing right brace of the class body is seen.

Benefits of Data Abstraction

Data abstraction provides two important advantages:

 Class internals are protected from inadvertent user-level errors, which


might corrupt the state of the object.

 The class implementation may evolve over time in response to changing


requirements or bug reports without requiring change in user-level code.

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.

Data Abstraction Example

Any C++ program where you implement a class with public and private
members is an example of data abstraction. Consider the following example:

#include <iostream>
using namespace std;

class Adder{
public:
// constructor
Adder(int i = 0)

228
C++

{
total = i;
}
// interface to outside world
void addNum(int number)
{
total += number;
}
// interface to outside world
int getTotal()
{
return total;
};
private:
// hidden data from outside world
int total;
};
int main( )
{
Adder a;

a.addNum(10);
a.addNum(20);
a.addNum(30);

cout << "Total " << a.getTotal() <<endl;


return 0;
}

When the above code is compiled and executed, it produces the following result:

Total 60

Above class adds numbers together, and returns the sum. The public 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.
229
C++

Designing Strategy

Abstraction separates code into interface and implementation. So while


designing your component, you must keep interface independent of the
implementation so that if you change underlying implementation then interface
would remain intact.

In this case whatever programs are using these interfaces, they would not be
impacted and would just need a recompilation with the latest implementation.

230
C++

28. DATA ENCAPSULATION

All C++ programs are composed of the following two fundamental elements:

 Program statements (code): This is the part of a program that


performs actions and they are called functions.

 Program data: The data is the information of the program which gets
affected by the program functions.

Encapsulation is an Object Oriented Programming concept that binds together


the data and functions that manipulate the data, and that keeps both safe from
outside interference and misuse. Data encapsulation led to the important OOP
concept of data hiding.

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 the implementation details from the user.

C++ supports the properties of encapsulation and data hiding through the
creation of user-defined types, called classes. We already have studied that a
class can contain private, protected and public members. By default, all items
defined in a class are private. For example:

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 program. This is one way encapsulation is achieved.

To make parts of a class public (i.e., accessible to other parts of your program),
you must declare them after the public keyword. All variables or functions
231
C++

defined after the public specifier are accessible by all other functions in your
program.

Making one class a friend of another, exposes the implementation details and
reduces encapsulation. The ideal is to keep as many of the details of each class
hidden from all other classes as possible.

Data Encapsulation Example

Any C++ program where you implement a class with public and private
members is an example of data encapsulation and data abstraction. Consider the
following example:

#include <iostream>
using namespace std;

class Adder{
public:
// constructor
Adder(int i = 0)
{
total = i;
}
// interface to outside world
void addNum(int number)
{
total += number;
}
// interface to outside world
int getTotal()
{
return total;
};
private:
// hidden data from outside world
int total;
};
int main( )
{
232
C++

Adder a;

a.addNum(10);
a.addNum(20);
a.addNum(30);

cout << "Total " << a.getTotal() <<endl;


return 0;
}

When the above code is compiled and executed, it produces the following result:

Total 60

Above class adds numbers together, and returns the sum. The public 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 outside world, but is needed for the class to operate properly.

Designing Strategy

Most of us have learnt to make class members private by default unless we


really need to expose them. That's just good encapsulation.

This is applied most frequently to data members, but it applies equally to all
members, including virtual functions.

233
C++

29. INTERFACES

An interface describes the behavior or capabilities of a C++ class without


committing to a particular implementation of that class.

The C++ interfaces are implemented using abstract classes and these abstract
classes should not be confused with data abstraction which is a concept of
keeping implementation details separate from associated data.

A class is made abstract by declaring at least one of its functions as pure


virtual function. A pure virtual function is specified by placing "= 0" in its
declaration as follows:

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
};

The purpose of an abstract class (often referred to as an ABC) is to provide an


appropriate base class from which other classes can inherit. Abstract classes
cannot be used to instantiate objects and serves only as an interface.
Attempting to instantiate an object of an abstract class causes a compilation
error.

Thus, if a subclass of an ABC needs to be instantiated, it has to implement each


of the virtual functions, which means that it supports the interface declared by
the ABC. Failure to override a pure virtual function in a derived class, then
attempting to instantiate objects of that class, is a compilation error.

Classes that can be used to instantiate objects are called concrete classes.

Abstract Class Example

Consider the following example where parent class provides an interface to the
base class to implement a function called getArea():

#include <iostream>

234
C++

using namespace std;

// Base class
class Shape
{
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};

// Derived classes
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
class Triangle: public Shape
{
public:

235
C++

int getArea()
{
return (width * height)/2;
}
};

int main(void)
{
Rectangle Rect;
Triangle Tri;

Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total Rectangle area: " << Rect.getArea() << endl;

Tri.setWidth(5);
Tri.setHeight(7);
// Print the area of the object.
cout << "Total Triangle area: " << Tri.getArea() << endl;

return 0;
}

When the above code is compiled and executed, it produces the following result:

Total Rectangle area: 35


Total Triangle area: 17

You can see how an abstract class defined an interface in terms of getArea() and
two other classes implemented same function but with different algorithm to
calculate the area specific to the shape.

Designing Strategy

An object-oriented system might use an abstract base class to provide a


common and standardized interface appropriate for all the external applications.
Then, through inheritance from that abstract base class, derived classes are
formed that operate similarly.
236
C++

The capabilities (i.e., the public functions) offered by the external applications
are provided as pure virtual functions in the abstract base class. The
implementations of these pure virtual functions are provided in the derived
classes that correspond to the specific types of the application.

This architecture also allows new applications to be added to a system easily,


even after the system has been defined.

237
C++

30. FILES AND STREAMS

So far, we have been using the iostream standard library, which


provides cin and cout methods for reading from standard input and writing to
standard output respectively.

This tutorial will teach you how to read and write from a file. This requires
another standard C++ library called fstream, which defines three new data
types:

Data Type Description

ofstream This data type represents the output file stream and is
used to create files and to write information to files.

ifstream This data type represents the input file stream and is
used to read information from files.

fstream This data type represents the file stream generally,


and has the capabilities of both ofstream and ifstream
which means it can create files, write information to
files, and read information from files.

To perform file processing in C++, header files <iostream> and <fstream> must
be included in your C++ source file.

Opening a File

A file must be opened before you can read from it or write to it. Either
ofstream or fstream object may be used to open a file for writing. And ifstream
object is used to open a file for reading purpose only.

Following is the standard syntax for open() function, which is a member of


fstream, ifstream, and ofstream objects.

void open(const char *filename, ios::openmode mode);

Here, the first argument specifies the name and location of the file to be opened
and the second argument of the open() member function defines the mode in
which the file should be opened.

Mode Flag Description

238
C++

ios::app Append mode. All output to that file to be appended to


the end.

ios::ate Open a file for output and move the read/write control
to the end of the file.

ios::in Open a file for reading.

ios::out Open a file for writing.

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 truncate it in case
that already exists, following will be the syntax:

ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );

Similar way, you can open a file for reading and writing purpose as follows:

fstream afile;
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, ifstream, and ofstream objects.

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 object instead of the cout object.

Reading from a File


239
C++

You read information from a file into your program using the stream extraction
operator (>>) just as you use that operator to input information from the
keyboard. The only difference is that you use an ifstream or fstream object
instead of the cin object.

Read & Write Example

Following is the C++ program which opens a file in reading and writing mode.
After writing information entered by the user to a file named afile.dat, the
program reads information from the file and outputs it onto the screen:

#include <fstream>
#include <iostream>
using namespace std;

int main ()
{

char data[100];

// open a file in write mode.


ofstream outfile;
outfile.open("afile.dat");

cout << "Writing to the file" << endl;


cout << "Enter your name: ";
cin.getline(data, 100);

// write inputted data into the file.


outfile << data << endl;

cout << "Enter your age: ";


cin >> data;
cin.ignore();

// again write inputted data into the file.


outfile << data << endl;

240
C++

// close the opened file.


outfile.close();

// open a file in read mode.


ifstream infile;
infile.open("afile.dat");

cout << "Reading from the file" << endl;


infile >> data;

// write the data at the screen.


cout << data << endl;

// again read the data from the file and display it.
infile >> data;
cout << data << endl;

// close the opened file.


infile.close();

return 0;
}

When the above code is compiled and executed, it produces the following
sample input and output:

$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9

Above examples make use of additional functions from cin object, like getline()
function to read the line from outside, and ignore() function to ignore the extra
characters left by previous read statement.
241
C++

File Position Pointers

Both istream and ostream provide member functions for repositioning the file-
position pointer. These member functions are seekg ("seek get") for istream
and seekp ("seek put") for ostream.

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.

The file-position pointer is an integer value that specifies the location in the file
as a number of bytes from the file's starting location. Some examples of
positioning the "get" file-position pointer are:

// position to the nth byte of fileObject (assumes ios::beg)


fileObject.seekg( n );

// position n bytes forward in fileObject


fileObject.seekg( n, ios::cur );

// position n bytes back from end of fileObject


fileObject.seekg( n, ios::end );

// position at end of fileObject


fileObject.seekg( 0, ios::end );

242
C++

31. EXCEPTION HANDLING

An exception is a problem that arises during the execution of a program. A C++


exception is a response to an exceptional circumstance that arises while a
program is running, such as an attempt to divide by zero.

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.

 throw: A program throws an exception when a problem shows up. This is


done using a throw keyword.

 catch: A program catches an exception with an exception handler at the


place in a program where you want to handle the problem.
The catch keyword indicates the catching of an exception.

 try: A try block identifies a block of code for which particular exceptions
will be activated. It is followed by one or more catch blocks.

Assuming a block will raise an exception, a method catches an exception using a


combination of the try and catch keywords. A try/catch block is placed around
the code that might generate an exception. Code within a try/catch block is
referred to as protected code, and the syntax for using try/catch is as follows:

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.

243
C++

Throwing Exceptions

Exceptions can be thrown anywhere within a code block using throw statement.
The operand of the throw statement determines a type for the exception and can
be any expression and the type of the result of the expression determines the
type of exception thrown.

Following is an example of throwing an exception when dividing by zero


condition occurs:

double division(int a, int b)


{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}

Catching Exceptions

The catch block following the try block catches any exception. You can specify
what type of exception you want to catch and this is determined by the
exception declaration that appears in parentheses following the keyword catch.

try
{
// protected code
}catch( ExceptionName e )
{
// code to handle ExceptionName exception
}

Above code will catch an exception of ExceptionName type. If you want to


specify that a catch block should handle any type of exception that is thrown in a
try block, you must put an ellipsis, ..., between the parentheses enclosing the
exception declaration as follows:

try
{
// protected code
}catch(...)

244
C++

{
// code to handle any exception
}

The following is an example, which throws a division by zero exception and we


catch it in catch block.

#include <iostream>
using namespace std;

double division(int a, int b)


{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}

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;
}

245
C++

Because we are raising an exception of type const char*, so while catching this
exception, we have to use const char* in catch block. If we compile and run
above code, this would produce the following result:

Division by zero condition!

C++ Standard Exceptions

C++ provides a list of standard exceptions defined in <exception> which we


can use in our programs. These are arranged in a parent-child class hierarchy
shown below:

Here is the small description of each exception mentioned in the above


hierarchy:

Exception Description

std::exception An exception and parent class of all the standard C++


exceptions.

246
C++

std::bad_alloc This can be thrown by new.

std::bad_cast This can be thrown by dynamic_cast.

std::bad_exception This is useful device to handle unexpected exceptions


in a C++ program.

std::bad_typeid This can be thrown by typeid.

std::logic_error An exception that theoretically can be detected by


reading the code.

std::domain_error This is an exception thrown when a mathematically


invalid domain is used.

std::invalid_argument This is thrown due to invalid arguments.

std::length_error This is thrown when a too big std::string is created.

std::out_of_range This can be thrown by the ‘at’ method, for example a


std::vector and std::bitset<>::operator[]().

std::runtime_error An exception that theoretically cannot be detected by


reading the code.

std::overflow_error This is thrown if a mathematical overflow occurs.

std::range_error This is occurred when you try to store a value which is


out of range.

std::underflow_error This is thrown if a mathematical underflow occurs.

Define New Exceptions

You can define your own exceptions by inheriting and overriding exception class
functionality. Following is the example, which shows how you can use
std::exception class to implement your own exception in standard way:

#include <iostream>
#include <exception>
using namespace std;
247
C++

struct MyException : public exception


{
const char * what () const throw ()
{
return "C++ Exception";
}
};

int main()
{
try
{
throw MyException();
}
catch(MyException& e)
{
std::cout << "MyException caught" << std::endl;
std::cout << e.what() << std::endl;
}
catch(std::exception& e)
{
//Other errors
}
}

This would produce the following result:

MyException caught
C++ Exception

Here, what() is a public method provided by exception class and it has been
overridden by all the child exception classes. This returns the cause of an
exception.

248
C++

32. DYNAMIC MEMORY

A good understanding of how dynamic memory really works in C++ is essential


to becoming a good C++ programmer. Memory in your C++ program is divided
into two parts:

 The stack: All variables declared inside the function will take up memory
from the stack.

 The heap: This is unused memory of the program and can be used to
allocate the memory dynamically when program runs.

Many times, you are not aware in advance how much memory you will need to
store particular information in a defined variable and the size of required
memory can be determined at run time.

You can allocate memory at run time within the heap for the variable of a given
type using a special operator in C++ which returns the address of the space
allocated. This operator is called new operator.

If you are not in need of dynamically allocated memory anymore, you can use
delete operator, which de-allocates memory previously allocated by new
operator.

The new and delete Operators

There is following generic syntax to use new operator to allocate memory


dynamically for any data-type.

new data-type;

Here, data-type could be any built-in data type including an array or any user
defined data types include class or structure. Let us start with built-in data
types. For example we can define a pointer to type double and then request that
the memory be allocated at execution time. We can do this using the new
operator with the following statements:

double* pvalue = NULL; // Pointer initialized with null


pvalue = new double; // Request memory for the variable

The memory may not have been allocated successfully, if the free store had
been used up. So it is good practice to check if new operator is returning NULL
pointer and take appropriate action as below:

249
C++

double* pvalue = NULL;


if( !(pvalue = new double ))
{
cout << "Error: out of memory." <<endl;
exit(1);

The malloc() function from C, still exists in C++, but it is recommended to


avoid using malloc() function. The main advantage of new over malloc() is that
new doesn't just allocate memory, it constructs objects which is prime purpose
of C++.

At any point, when you feel a variable that has been dynamically allocated is not
anymore required, you can free up the memory that it occupies in the free store
with the delete operator as follows:

delete pvalue; // Release memory pointed to by pvalue

Let us put above concepts and form the following example to show how new and
delete work:

#include <iostream>
using namespace std;

int main ()
{
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable

*pvalue = 29494.99; // Store value at allocated address


cout << "Value of pvalue : " << *pvalue << endl;

delete pvalue; // free up the memory.

return 0;
}

If we compile and run above code, this would produce the following result:

250
C++

Value of pvalue : 29495

Dynamic Memory Allocation for Arrays

Consider you want to allocate memory for an array of characters, i.e., string of
20 characters. Using the same syntax what we have used above we can allocate
memory dynamically as shown below.

char* pvalue = NULL; // Pointer initialized with null


pvalue = new char[20]; // Request memory for the variable

To remove the array that we have just created the statement would look like
this:

delete [] pvalue; // Delete array pointed to by pvalue

Following is the syntax of new operator for a multi-dimensional array as follows:

int ROW = 2;
int COL = 3;
double **pvalue = new double* [ROW]; // Allocate memory for rows

// Now allocate memory for columns


for(int i = 0; i < COL; i++) {
pvalue[i] = new double[COL];
}

The syntax to release the memory for multi-dimensional will be as follows:

for(int i = 0; i < COL; i++) {


delete[] pvalue[i];
}
delete [] pvalue;

Dynamic Memory Allocation for Objects

Objects are no different from simple data types. For example, consider the
following code where we are going to use an array of objects to clarify the
concept:

#include <iostream>
using namespace std;

251
C++

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 called same number of times.

If we compile and run above code, this would produce the following result:

Constructor called!
Constructor called!
Constructor called!
Constructor called!
Destructor called!
Destructor called!
Destructor called!
Destructor called!

252
C++

33. NAMESPACES

Consider a situation, when we have two persons with the same name, Zara, in
the same class. Whenever we need to differentiate them definitely we would
have to use some additional information along with their name, like either the
area, if they live in different area or their mother’s or father’s name, etc.

Same situation can arise in your C++ applications. For example, you might be
writing some code that has a function called xyz() and there is another library
available which is also having same function xyz(). Now the compiler has no way
of knowing which version of xyz() function you are referring to within your code.

A namespace is designed to overcome this difficulty and is used as additional


information to differentiate similar functions, classes, variables etc. with the
same name available in different libraries. Using namespace, you can define the
context in which names are defined. In essence, a namespace defines a scope.

Defining a Namespace

A namespace definition begins with the keyword namespace followed by the


namespace name as follows:

namespace namespace_name {
// code declarations
}

To call the namespace-enabled version of either function or variable, prepend


(::) the namespace name as follows:

name::code; // code could be variable or function.

Let us see how namespace scope the entities including variable and functions:

#include <iostream>
using namespace std;

// first name space


namespace first_space{
void func(){
cout << "Inside first_space" << endl;
}
}

253
C++

// second name space


namespace second_space{
void func(){
cout << "Inside second_space" << endl;
}
}
int main ()
{

// Calls function from first name space.


first_space::func();

// Calls function from second name space.


second_space::func();

return 0;
}

If we compile and run above code, this would produce the following result:

Inside first_space
Inside second_space

The using directive

You can also avoid prepending of namespaces with the using


namespace directive. This directive tells the compiler that the subsequent code
is making use of names in the specified namespace. The namespace is thus
implied for the following code:

#include <iostream>
using namespace std;

// first name space


namespace first_space{
void func(){
cout << "Inside first_space" << endl;
}

254
C++

}
// second name space
namespace second_space{
void func(){
cout << "Inside second_space" << endl;
}
}
using namespace first_space;
int main ()
{

// This calls function from first name space.


func();

return 0;
}

If we compile and run above code, this would produce the following result:

Inside first_space

The ‘using’ directive can also be used to refer to a particular item within a
namespace. For example, if the only part of the std namespace that you intend
to use is cout, you can refer to it as follows:

using std::cout;

Subsequent code can refer to cout without prepending the namespace, but other
items in the std namespace will still need to be explicit as follows:

#include <iostream>
using std::cout;

int main ()
{

cout << "std::endl is used with std!" << std::endl;

255
C++

return 0;
}

If we compile and run above code, this would produce the following result:

std::endl is used with std!

Names introduced in a using directive obey normal scope rules. The name is
visible from the point of the using directive to the end of the scope in which the
directive is found. Entities with the same name defined in an outer scope are
hidden.

Discontiguous Namespaces

A namespace can be defined in several parts and so a namespace is made up of


the sum of its separately defined parts. The separate parts of a namespace can
be spread over multiple files.

So, if one part of the namespace requires a name defined in another file, that
name must still be declared. Writing a following namespace definition either
defines a new namespace or adds new elements to an existing one:

namespace namespace_name {
// code declarations
}

Nested Namespaces

Namespaces can be nested where you can define one namespace inside another
namespace as follows:

namespace namespace_name1 {
// code declarations
namespace namespace_name2 {
// code declarations
}
}

You can access members of nested namespace by using resolution operators as


follows:

// to access members of namespace_name2


using namespace namespace_name1::namespace_name2;
256
C++

// to access members of namespace:name1


using namespace namespace_name1;

In the above statements if you are using namespace_name1, then it will make
elements of namespace_name2 available in the scope as follows:

#include <iostream>
using namespace std;

// first name space


namespace first_space{
void func(){
cout << "Inside first_space" << endl;
}
// second name space
namespace second_space{
void func(){
cout << "Inside second_space" << endl;
}
}
}
using namespace first_space::second_space;
int main ()
{

// This calls function from second name space.


func();

return 0;
}

If we compile and run above code, this would produce the following result:

Inside second_space

257
C++

34. TEMPLATES

Templates are the foundation of generic programming, which involves writing


code in a way that is independent of any particular type.

A template is a blueprint or formula for creating a generic class or a function.


The library containers like iterators and algorithms are examples of generic
programming and have been developed using template concept.

There is a single definition of each container, such as vector, but we can define
many different kinds of vectors for example, vector <int> or vector <string>.

You can use templates to define functions as well as classes, let us see how
they work:

Function Template

The general form of a template function definition is shown here:

template <class type> ret-type func-name(parameter list)


{
// body of function
}

Here, type is a placeholder name for a data type used by the function. This
name can be used within the function definition.

The following is the example of a function template that returns the maximum of
two values:

#include <iostream>
#include <string>

using namespace std;

template <typename T>


inline T const& Max (T const& a, T const& b)
{
return a < b ? b:a;
}
int main ()
{
258
C++

int i = 39;
int j = 20;
cout << "Max(i, j): " << Max(i, j) << endl;

double f1 = 13.5;
double f2 = 20.7;
cout << "Max(f1, f2): " << Max(f1, f2) << endl;

string s1 = "Hello";
string s2 = "World";
cout << "Max(s1, s2): " << Max(s1, s2) << endl;

return 0;
}

If we compile and run above code, this would produce the following result:

Max(i, j): 39
Max(f1, f2): 20.7
Max(s1, s2): World

Class Template

Just as we can define function templates, we can also define class templates.
The general form of a generic class declaration is shown here:

template <class type> class class-name {


.
.
.
}

Here, type is the placeholder type name, which will be specified when a class is
instantiated. You can define more than one generic data type by using a comma-
separated list.

Following is the example to define class Stack<> and implement generic


methods to push and pop the elements from the stack:

259
C++

#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>

using namespace std;

template <class T>


class Stack {
private:
vector<T> elems; // elements

public:
void push(T const&); // push element
void pop(); // pop element
T top() const; // return top element
bool empty() const{ // return true if empty.
return elems.empty();
}
};

template <class T>


void Stack<T>::push (T const& elem)
{
// append copy of passed element
elems.push_back(elem);
}

template <class T>


void Stack<T>::pop ()
{
if (elems.empty()) {
throw out_of_range("Stack<>::pop(): empty stack");

260
C++

}
// remove last element
elems.pop_back();
}

template <class T>


T Stack<T>::top () const
{
if (elems.empty()) {
throw out_of_range("Stack<>::top(): empty stack");
}
// return copy of last element
return elems.back();
}

int main()
{
try {
Stack<int> intStack; // stack of ints
Stack<string> stringStack; // stack of strings

// manipulate int stack


intStack.push(7);
cout << intStack.top() <<endl;

// manipulate string stack


stringStack.push("hello");
cout << stringStack.top() << std::endl;
stringStack.pop();
stringStack.pop();
}
catch (exception const& ex) {
cerr << "Exception: " << ex.what() <<endl;
return -1;

261
C++

}
}

If we compile and run above code, this would produce the following result:

7
hello
Exception: Stack<>::pop(): empty stack

262
C++

35. PREPROCESSOR

The preprocessors are the directives, which give instructions to the compiler to
preprocess the information before actual compilation starts.

All preprocessor directives begin with #, and only white-space characters may
appear before a preprocessor directive on a line. Preprocessor directives are not
C++ statements, so they do not end in a semicolon (;).

You already have seen a #include directive in all the examples. This macro is
used to include a header file into the source file.

There are number of preprocessor directives supported by C++ like #include,


#define, #if, #else, #line, etc. Let us see important directives:

The #define Preprocessor

The #define preprocessor directive creates symbolic constants. The symbolic


constant is called a macro and the general form of the directive is:

#define macro-name replacement-text

When this line appears in a file, all subsequent occurrences of macro in that file
will be replaced by replacement-text before the program is compiled. For
example:

#include <iostream>
using namespace std;

#define PI 3.14159

int main ()
{

cout << "Value of PI :" << PI << endl;

return 0;
}

Now, let us do the preprocessing of this code to see the result assuming we have
the source code file. So let us compile it with -E option and redirect the result to

263
C++

test.p. Now, if you check test.p, it will have lots of information and at the
bottom, you will find the value replaced as follows:

$gcc -E test.cpp > test.p

...
int main ()
{

cout << "Value of PI :" << 3.14159 << endl;

return 0;
}

Function-Like Macros

You can use #define to define a macro which will take argument as follows:

#include <iostream>
using namespace std;

#define MIN(a,b) (((a)<(b)) ? a : b)

int main ()
{
int i, j;
i = 100;
j = 30;
cout <<"The minimum is " << MIN(i, j) << endl;

return 0;
}

If we compile and run above code, this would produce the following result:

The minimum is 30

Conditional Compilation

264
C++

There are several directives, which can be used to compile selective portions of
your program's source code. This process is called conditional compilation.

The conditional preprocessor construct is much like the ‘if’ selection structure.
Consider the following preprocessor code:

#ifndef NULL
#define NULL 0
#endif

You can compile a program for debugging purpose. You can also turn on or off
the debugging using a single macro as follows:

#ifdef DEBUG
cerr <<"Variable x = " << x << endl;
#endif

This causes the cerr statement to be compiled in the program if the symbolic
constant DEBUG has been defined before directive #ifdef DEBUG. You can use
#if 0 statement to comment out a portion of the program as follows:

#if 0
code prevented from compiling
#endif

Let us try the following example:

#include <iostream>
using namespace std;
#define DEBUG

#define MIN(a,b) (((a)<(b)) ? a : b)

int main ()
{
int i, j;
i = 100;
j = 30;
#ifdef DEBUG
cerr <<"Trace: Inside main function" << endl;
#endif
265
C++

#if 0
/* This is commented part */
cout << MKSTR(HELLO C++) << endl;
#endif

cout <<"The minimum is " << MIN(i, j) << endl;

#ifdef DEBUG
cerr <<"Trace: Coming out of main function" << endl;
#endif
return 0;
}

If we compile and run above code, this would produce the following result:

Trace: Inside main function


The minimum is 30
Trace: Coming out of main function

The # and # # Operators

The # and ## preprocessor operators are available in C++ and ANSI/ISO C. The
# operator causes a replacement-text token to be converted to a string
surrounded by quotes.

Consider the following macro definition:

#include <iostream>
using namespace std;

#define MKSTR( x ) #x

int main ()
{
cout << MKSTR(HELLO C++) << endl;

return 0;

266
C++

If we compile and run above code, this would produce the following result:

HELLO C++

Let us see how it worked. It is simple to understand that the C++ preprocessor
turns the line:

cout << MKSTR(HELLO C++) << endl;

Above line will be turned into the following line:

cout << "HELLO C++" << endl;

The ## operator is used to concatenate two tokens. Here is an example:

#define CONCAT( x, y ) x ## y

When CONCAT appears in the program, its arguments are concatenated and
used to replace the macro. For example, CONCAT(HELLO, C++) is replaced by
"HELLO C++" in the program as follows.

#include <iostream>
using namespace std;

#define concat(a, b) a ## b
int main()
{
int xy = 100;

cout << concat(x, y);


return 0;
}

If we compile and run above code, this would produce the following result:

100

Let us see how it worked. It is simple to understand that the C++ preprocessor
transforms:

cout << concat(x, y);

267
C++

Above line will be transformed into the following line:

cout << xy;

Predefined C++ Macros

C++ provides a number of predefined macros mentioned below:

Macro Description

__LINE__ This contains the current line number of the program


when it is being compiled.

__FILE__ This contains the current file name of the program


when it is being compiled.

__DATE__ This contains a string of the form month/day/year that


is the date of the translation of the source file into
object code.

__TIME__ This contains a string of the form hour:minute:second


that is the time at which the program was compiled.

Let us see an example for all the above macros:

#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:

268
C++

Value of __LINE__ : 6
Value of __FILE__ : test.cpp
Value of __DATE__ : Feb 28 2011
Value of __TIME__ : 18:52:48

269
C++

36. SIGNAL HANDLING

Signals are the interrupts delivered to a process by the operating system which
can terminate a program prematurely. You can generate interrupts by pressing
Ctrl+C on a UNIX, LINUX, Mac OS X or Windows system.

There are signals which cannot be caught by the program but there is a
following list of signals which you can catch in your program and can take
appropriate actions based on the signal. These signals are defined in C++
header file <csignal>.

Signal Description

SIGABRT Abnormal termination of the program, such as a call to abort.

SIGFPE An erroneous arithmetic operation, such as a divide by zero or


an operation resulting in overflow.

SIGILL Detection of an illegal instruction.

SIGINT Receipt of an interactive attention signal.

SIGSEGV An invalid access to storage.

SIGTERM A termination request sent to the program.

The signal() Function

C++ signal-handling library provides function signal to trap unexpected events.


Following is the syntax of the signal() function:

void (*signal (int sig, void (*func)(int)))(int);

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 using
signal() function. Whatever signal you want to catch in your program, you must
register that signal using signal function and associate it with a signal handler.
Examine the following example:

#include <iostream>
270
C++

#include <csignal>

using namespace std;

void signalHandler( int signum )


{
cout << "Interrupt signal (" << signum << ") received.\n";

// cleanup and close up stuff here


// terminate program

exit(signum);

int main ()
{
// register signal SIGINT and signal handler
signal(SIGINT, signalHandler);

while(1){
cout << "Going to sleep...." << endl;
sleep(1);
}

return 0;
}

When the above code is compiled and executed, it produces the following result:

Going to sleep....
Going to sleep....
Going to sleep....

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:

271
C++

Going to sleep....
Going to sleep....
Going to sleep....
Interrupt signal (2) received.

The raise() Function

You can generate signals by function raise(), which takes an integer signal
number as an argument and has the following syntax.

int raise (signal sig);

Here, sig is the signal number to send any of the signals: SIGINT, SIGABRT,
SIGFPE, SIGILL, SIGSEGV, SIGTERM, SIGHUP. Following is the example where
we raise a signal internally using raise() function as follows:

#include <iostream>
#include <csignal>

using namespace std;

void signalHandler( int signum )


{
cout << "Interrupt signal (" << signum << ") received.\n";

// cleanup and close up stuff here


// terminate program

exit(signum);

int main ()
{
int i = 0;
// register signal SIGINT and signal handler
signal(SIGINT, signalHandler);

272
C++

while(++i){
cout << "Going to sleep...." << endl;
if( i == 3 ){
raise( SIGINT);
}
sleep(1);
}

return 0;
}

When the above code is compiled and executed, it produces the following result
and would come out automatically:

Going to sleep....
Going to sleep....
Going to sleep....
Interrupt signal (2) received.

273
C++

37. 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 are two types of multitasking: process-based and thread-based.

Process-based multitasking handles the concurrent execution of programs.


Thread-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.

C++ does not contain any built-in support for multithreaded applications.
Instead, it relies entirely upon the operating system to provide this feature.

This tutorial assumes that you are working on Linux OS and we are going to
write multi-threaded C++ program using POSIX. POSIX Threads, or Pthreads
provides API which are available on many Unix-like POSIX systems such as
FreeBSD, NetBSD, GNU/Linux, Mac OS X and Solaris.

Creating Threads

The following routine is used to create a POSIX thread:

#include <pthread.h>
pthread_create (thread, attr, start_routine, arg)

Here, pthread_create creates a new thread and makes it executable. This


routine can be called any number of times from anywhere within your code.
Here is the description of the parameters:

Parameter Description

thread An opaque, unique identifier for the new thread returned


by the subroutine.

attr An opaque attribute object that may be used to set thread


attributes. You can specify a thread attributes object, or
NULL for the default values.

start_routine The C++ routine that the thread will execute once it is
created.

274
C++

arg A single argument that may be passed to start_routine. It


must be passed by reference as a pointer cast of type
void. NULL may be used if no argument is to be passed.

The maximum number of threads that may be created by a process is


implementation dependent. Once created, threads are peers, and may create
other threads. There is no implied hierarchy or dependency between threads.

Terminating Threads

There is following routine which we use to terminate a POSIX thread:

#include <pthread.h>
pthread_exit (status)

Here pthread_exit is used to explicitly exit a thread. Typically, the


pthread_exit() routine is called after a thread has completed its work and is no
longer required to exist.

If main() finishes before the threads it has created, and exits with
pthread_exit(), the other threads will continue to execute. Otherwise, they will
be automatically terminated when main() finishes.

Example:
This simple example code creates 5 threads with the pthread_create() routine.
Each thread prints a "Hello World!" message, and then terminates with a call to
pthread_exit().

#include <iostream>
#include <cstdlib>
#include <pthread.h>

using namespace std;

#define NUM_THREADS 5

void *PrintHello(void *threadid)


{
long tid;
tid = (long)threadid;
cout << "Hello World! Thread ID, " << tid << endl;

275
C++

pthread_exit(NULL);
}

int main ()
{
pthread_t threads[NUM_THREADS];
int rc;
int i;
for( i=0; i < NUM_THREADS; i++ ){
cout << "main() : creating thread, " << i << endl;
rc = pthread_create(&threads[i], NULL,
PrintHello, (void *)i);
if (rc){
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
pthread_exit(NULL);
}

Compile the following program using -lpthread library as follows:

$gcc test.cpp -lpthread

Now, execute your program which gives the following output:

main() : creating thread, 0


main() : creating thread, 1
main() : creating thread, 2
main() : creating thread, 3
main() : creating thread, 4
Hello World! Thread ID, 0
Hello World! Thread ID, 1
Hello World! Thread ID, 2
Hello World! Thread ID, 3
Hello World! Thread ID, 4

276
C++

Passing Arguments to Threads

This example shows how to pass multiple arguments via a structure. You can
pass any data type in a thread callback because it points to void as explained in
the following example:

#include <iostream>
#include <cstdlib>
#include <pthread.h>

using namespace std;

#define NUM_THREADS 5

struct thread_data{
int thread_id;
char *message;
};

void *PrintHello(void *threadarg)


{
struct thread_data *my_data;

my_data = (struct thread_data *) threadarg;

cout << "Thread ID : " << my_data->thread_id ;


cout << " Message : " << my_data->message << endl;

pthread_exit(NULL);
}

int main ()
{
pthread_t threads[NUM_THREADS];
struct thread_data td[NUM_THREADS];
int rc;

277
C++

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);
}

When the above code is compiled and executed, it produces the following result:

main() : creating thread, 0


main() : creating thread, 1
main() : creating thread, 2
main() : creating thread, 3
main() : creating thread, 4
Thread ID : 3 Message : This is message
Thread ID : 2 Message : This is message
Thread ID : 0 Message : This is message
Thread ID : 1 Message : This is message
Thread ID : 4 Message : This is message

Joining and Detaching Threads

There are following two routines which we can use to join or detach threads:

pthread_join (threadid, status)


pthread_detach (threadid)

278
C++

The pthread_join() subroutine blocks the calling thread until the specified
‘threadid’ thread terminates. When a thread is created, one of its attributes
defines whether it is joinable or detached. Only threads that are created as
joinable can be joined. If a thread is created as detached, it can never be joined.

This example demonstrates how to wait for thread completions by using the
Pthread join routine.

#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>

using namespace std;

#define NUM_THREADS 5

void *wait(void *t)


{
int i;
long tid;

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;
279
C++

// Initialize and set thread joinable


pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

for( i=0; i < NUM_THREADS; i++ ){


cout << "main() : creating thread, " << i << endl;
rc = pthread_create(&threads[i], NULL, wait, (void *)i );
if (rc){
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}

// free attribute and wait for the other threads


pthread_attr_destroy(&attr);
for( i=0; i < NUM_THREADS; i++ ){
rc = pthread_join(threads[i], &status);
if (rc){
cout << "Error:unable to join," << rc << endl;
exit(-1);
}
cout << "Main: completed thread id :" << i ;
cout << " exiting with status :" << status << endl;
}

cout << "Main: program exiting." << endl;


pthread_exit(NULL);
}

When the above code is compiled and executed, it produces the following result:

main() : creating thread, 0


main() : creating thread, 1
main() : creating thread, 2

280
C++

main() : creating thread, 3


main() : creating thread, 4
Sleeping in thread
Thread with id : 0 .... exiting
Sleeping in thread
Thread with id : 1 .... exiting
Sleeping in thread
Thread with id : 2 .... exiting
Sleeping in thread
Thread with id : 3 .... exiting
Sleeping in thread
Thread with id : 4 .... exiting
Main: completed thread id :0 exiting with status :0
Main: completed thread id :1 exiting with status :0
Main: completed thread id :2 exiting with status :0
Main: completed thread id :3 exiting with status :0
Main: completed thread id :4 exiting with status :0
Main: program exiting.

281
C++

38. WEB PROGRAMMING

What is CGI?

The Common Gateway Interface, or CGI, is a set of standards that define how
information is exchanged between the web server and a custom script.

The CGI specs are currently maintained by the NCSA and NCSA defines CGI is as
follows:

The Common Gateway Interface, or CGI, is a standard for external gateway


programs to interface with information servers such as HTTP servers.

The current version is CGI/1.1 and CGI/1.2 is under progress.

Web Browsing

To understand the concept of CGI, let's see what happens when we click a
hyperlink to browse a particular web page or URL.

 Your browser contacts the HTTP web server and demand for the URL i.e.
filename.

 Web Server will parse the URL and will look for the filename. If it finds the
requested file then web server sends that file back to the browser
otherwise sends an error message indicating that you have requested a
wrong file.

 Web browser takes response from web server and displays either the
received file or error message based on the received response.

However, it is possible to set up the HTTP server in such a way that whenever a
file in a certain directory is requested, that file is not sent back; instead it is
executed as a program, and produced output from the program is sent back to
your browser to display.

The Common Gateway Interface (CGI) is a standard protocol for enabling


applications (called CGI programs or CGI scripts) to interact with Web servers
and with clients. These CGI programs can be a written in Python, PERL, Shell, C
or C++ etc.

CGI Architecture Diagram

The following simple program shows a simple architecture of CGI:

282
C++

Web Server Configuration

Before you proceed with CGI Programming, make sure that your Web Server
supports CGI and it is configured to handle CGI Programs. All the CGI Programs
to be executed by the HTTP server are kept in a pre-configured directory. This
directory is called CGI directory and by convention it is named as /var/www/cgi-
bin. By convention CGI files will have extension as .cgi, though they are C++
executable.

By default, Apache Web Server is configured to run CGI programs in


/var/www/cgi-bin. If you want to specify any other directory to run your CGI
scripts, you can modify the following section in the httpd.conf file:

<Directory "/var/www/cgi-bin">
AllowOverride None
Options ExecCGI
Order allow,deny
Allow from all
</Directory>

283
C++

<Directory "/var/www/cgi-bin">
Options All
</Directory>

Here, I assume that you have Web Server up and running successfully and you
are able to run any other CGI program like Perl or Shell etc.

First CGI Program

Consider the following C++ Program content:

#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 command to make file executable. Now if you
click cplusplus.cgi then this produces the following output:

My First CGI program

The above C++ program is a simple program which is writing its output on
STDOUT 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.
284
C++

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 system, such as RDBMS, to exchange information.

HTTP Header

The line Content-type:text/html\r\n\r\n is a part of HTTP header, which is


sent to the browser to understand the content. All the HTTP header will be in the
following form:

HTTP Field Name: Field Content

For Example
Content-type: text/html\r\n\r\n

There are few other important HTTP headers, which you will use frequently in
your CGI Programming.

Header Description

Content-type: A MIME string defining the format of the file being


returned. Example is Content-type:text/html.

Expires: Date The date the information becomes invalid. This should
be used by the browser to decide when a page needs
to be refreshed. A valid date string should be in the
format 01 Jan 1998 12:00:00 GMT.

Location: URL The URL that should be returned instead of the URL
requested. You can use this field to redirect a request
to any file.

Last-modified: Date The date of last modification of the resource.

Content-length: N The length, in bytes, of the data being returned. The


browser uses this value to report the estimated
download time for a file.

Set-Cookie: String Set the cookie passed through the string.

CGI Environment Variables

All the CGI program will have access to the following environment variables.
These variables play an important role while writing any CGI program.

285
C++

Variable Name Description

CONTENT_TYPE The data type of the content, used when the client is
sending attached content to the server. For example
file upload etc.

CONTENT_LENGTH The length of the query information that is available


only for POST requests.

HTTP_COOKIE Returns the set cookies in the form of key & value
pair.

HTTP_USER_AGENT The User-Agent request-header field contains


information about the user agent originating the
request. It is a name of the web browser.

PATH_INFO The path for the CGI script.

QUERY_STRING The URL-encoded information that is sent with GET


method request.

REMOTE_ADDR The IP address of the remote host making the


request. This can be useful for logging or for
authentication purpose.

REMOTE_HOST The fully qualified name of the host making the


request. If this information is not available then
REMOTE_ADDR can be used to get IR address.

REQUEST_METHOD The method used to make the request. The most


common methods are GET and POST.

SCRIPT_FILENAME The full path to the CGI script.

SCRIPT_NAME The name of the CGI script.

SERVER_NAME The server's hostname or IP Address.

SERVER_SOFTWARE The name and version of the software the server is


running.

286
C++

Here is small CGI program to list out all the CGI variables.

#include <iostream>
#include <stdlib.h>
using namespace std;

const string ENV[ 24 ] = {


"COMSPEC", "DOCUMENT_ROOT", "GATEWAY_INTERFACE",
"HTTP_ACCEPT", "HTTP_ACCEPT_ENCODING",
"HTTP_ACCEPT_LANGUAGE", "HTTP_CONNECTION",
"HTTP_HOST", "HTTP_USER_AGENT", "PATH",
"QUERY_STRING", "REMOTE_ADDR", "REMOTE_PORT",
"REQUEST_METHOD", "REQUEST_URI", "SCRIPT_FILENAME",
"SCRIPT_NAME", "SERVER_ADDR", "SERVER_ADMIN",
"SERVER_NAME","SERVER_PORT","SERVER_PROTOCOL",
"SERVER_SIGNATURE","SERVER_SOFTWARE" };

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\">";

for ( int i = 0; i < 24; i++ )


{
cout << "<tr><td>" << ENV[ i ] << "</td><td>";
// attempt to retrieve value of environment variable
char *value = getenv( ENV[ i ].c_str() );

287
C++

if ( value != 0 ){
cout << value;
}else{
cout << "Environment variable does not exist.";
}
cout << "</td></tr>\n";
}
cout << "</table><\n";
cout << "</body>\n";
cout << "</html>\n";

return 0;
}

The output is as follows:

COMSPEC Environment variable does not exist.


DOCUMENT_ROOT /var/www/tutorialspoint
GATEWAY_INTERFACE CGI/1.1
HTTP_ACCEPT text/html, application/xhtml+xml, */*
HTTP_ACCEPT_ENCODING gzip, deflate
HTTP_ACCEPT_LANGUAGE en-US
HTTP_CONNECTION Keep-Alive
HTTP_HOST www.tutorialspoint.com
HTTP_USER_AGENT Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0;
rv:11.0) like Gecko
PATH /sbin:/usr/sbin:/bin:/usr/bin
QUERY_STRING
REMOTE_ADDR 183.82.104.71
REMOTE_PORT 50902
REQUEST_METHOD GET
REQUEST_URI /cgi-bin/cpp_env.cgi
SCRIPT_FILENAME /var/www/cgi-bin/cpp_env.cgi
SCRIPT_NAME /cgi-bin/cpp_env.cgi
SERVER_ADDR 66.135.33.172

288
C++

SERVER_ADMIN webmaster@tutorialspoint.com
SERVER_NAME www.tutorialspoint.com
SERVER_PORT 80
SERVER_PROTOCOL HTTP/1.1
SERVER_SIGNATURE
SERVER_SOFTWARE Apache
<

C++ CGI Library

For real examples, you would need to do many operations by your CGI program.
There is a CGI library written for C++ program which you can download from
ftp://ftp.gnu.org/gnu/cgicc/ and follow the steps to install the library:

$tar xzf cgicc-X.X.X.tar.gz


$cd cgicc-X.X.X/
$./configure --prefix=/usr
$make
$make install

You can check related documentation available at ‘C++ CGI Lib Documentation’.

GET and POST Methods

You must have come across many situations when you need to pass some
information 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 GET Method and POST Method.

Passing Information Using GET Method

The GET method sends the encoded user information appended to the page
request. The page and the encoded information are separated by the ‘?’
character as follows:

http://www.test.com/cgi-bin/cpp.cgi?key1=value1&key2=value2

The GET method is the default method to pass information from browser to web
server and it produces a long string that appears in your browser's Location:box.
Never use the GET method if you have password or other sensitive information
to pass to the server. The GET method has size limitation and you can pass up
to 1024 characters in a request string.

When using GET method, information is passed using QUERY_STRING http


header and will be accessible in your CGI Program through QUERY_STRING
environment variable.
289
C++

You can pass information by simply concatenating key and value pairs along
with any URL or you can use HTML <FORM> tags to pass information using GET
method.

Simple URL Example: Get Method

Here is a simple URL which will pass two values to hello_get.py program using
GET method.

/cgi-bin/cpp_get.cgi?first_name=ZARA&last_name=ALI

Below is a program to generate cpp_get.cgi CGI program to handle input given


by web browser. We are going to use C++ CGI library which makes it very easy
to access passed information:

#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>

using namespace std;


using namespace cgicc;

int main ()
{
Cgicc formData;

cout << "Content-type:text/html\r\n\r\n";


cout << "<html>\n";
cout << "<head>\n";
cout << "<title>Using GET and POST Methods</title>\n";
cout << "</head>\n";
cout << "<body>\n";

290
C++

form_iterator fi = formData.getElement("first_name");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "First name: " << **fi << endl;
}else{
cout << "No text entered for first name" << endl;
}
cout << "<br/>\n";
fi = formData.getElement("last_name");
if( !fi->isEmpty() &&fi != (*formData).end()) {
cout << "Last name: " << **fi << endl;
}else{
cout << "No text entered for last name" << endl;
}
cout << "<br/>\n";

cout << "</body>\n";


cout << "</html>\n";

return 0;
}

Now, compile the above program as follows:

$g++ -o cpp_get.cgi cpp_get.cpp -lcgicc

Generate cpp_get.cgi and put it in your CGI directory and try to access using
following link:

/cgi-bin/cpp_get.cgi?first_name=ZARA&last_name=ALI

This would generate following result:

First name: ZARA


Last name: ALI

Simple FORM Example: GET Method

Here is a simple example which passes two values using HTML FORM and submit
button. We are going to use same CGI script cpp_get.cgi to handle this input.

<form action="/cgi-bin/cpp_get.cgi" method="get">


291
C++

First Name: <input type="text" name="first_name"> <br />

Last Name: <input type="text" name="last_name" />


<input type="submit" value="Submit" />
</form>

Here is the actual output of the above form. You enter First and Last Name and
then click submit button to see the result.

First Name:
Submit
Last Name:

Passing Information Using POST Method

A generally more reliable method of passing information to a CGI program is the


POST method. This packages the information in exactly the same way as GET
methods, but instead of sending it as a text string after a ‘?’ in the URL it sends
it as a separate 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:

<form action="/cgi-bin/cpp_get.cgi" method="post">


First Name: <input type="text" name="first_name"><br />
Last Name: <input type="text" name="last_name" />

<input type="submit" value="Submit" />


</form>

Here is the actual output of the above form. You enter First and Last Name and
then click submit button to see the result.

First Name:
Submit
Last Name:

Passing Checkbox Data to CGI Program

Checkboxes are used when more than one option is required to be selected.
292
C++

Here is example HTML code for a form with two checkboxes:

<form action="/cgi-bin/cpp_checkbox.cgi"
method="POST"
target="_blank">
<input type="checkbox" name="maths" value="on" /> Maths
<input type="checkbox" name="physics" value="on" /> Physics
<input type="submit" value="Select Subject" />
</form>

The result of this code is the following form:

Select Subject
Maths Physics

Below is C++ program, which will generate cpp_checkbox.cgi script to handle


input given by web browser through checkbox button.

#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <stdlib.h>

#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>

using namespace std;


using namespace cgicc;

int main ()
{
Cgicc formData;
bool maths_flag, physics_flag;

cout << "Content-type:text/html\r\n\r\n";


cout << "<html>\n";
293
C++

cout << "<head>\n";


cout << "<title>Checkbox Data to CGI</title>\n";
cout << "</head>\n";
cout << "<body>\n";

maths_flag = formData.queryCheckbox("maths");
if( maths_flag ) {
cout << "Maths Flag: ON " << endl;
}else{
cout << "Maths Flag: OFF " << endl;
}
cout << "<br/>\n";

physics_flag = formData.queryCheckbox("physics");
if( physics_flag ) {
cout << "Physics Flag: ON " << endl;
}else{
cout << "Physics Flag: OFF " << endl;
}
cout << "<br/>\n";
cout << "</body>\n";
cout << "</html>\n";

return 0;
}

Passing Radio Button Data to CGI Program

Radio Buttons are used when only one option is required to be selected.

Here is example HTML code for a form with two radio button:

<form action="/cgi-bin/cpp_radiobutton.cgi"
method="post"
target="_blank">
<input type="radio" name="subject" value="maths"
checked="checked"/> Maths
294
C++

<input type="radio" name="subject" value="physics" /> Physics


<input type="submit" value="Select Subject" />
</form>

The result of this code is the following form:

Select Subject
Maths Physics

Below is C++ program, which will generate cpp_radiobutton.cgi script to handle


input given by web browser through radio buttons.

#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>

using namespace std;


using namespace cgicc;

int main ()
{
Cgicc formData;

cout << "Content-type:text/html\r\n\r\n";


cout << "<html>\n";
cout << "<head>\n";
cout << "<title>Radio Button Data to CGI</title>\n";
cout << "</head>\n";
cout << "<body>\n";

form_iterator fi = formData.getElement("subject");
295
C++

if( !fi->isEmpty() && fi != (*formData).end()) {


cout << "Radio box selected: " << **fi << endl;
}

cout << "<br/>\n";


cout << "</body>\n";
cout << "</html>\n";

return 0;
}

Passing Text Area Data to CGI Program

TEXTAREA element is used when multiline text has to be passed to the CGI
Program.

Here is example HTML code for a form with a TEXTAREA box:

<form action="/cgi-bin/cpp_textarea.cgi"
method="post"
target="_blank">
<textarea name="textcontent" cols="40" rows="4">
Type your text here...
</textarea>
<input type="submit" value="Submit" />
</form>

The result of this code is the following form:

Submit

Below is C++ program, which will generate cpp_textarea.cgi script to handle


input given by web browser through text area.

#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>

296
C++

#include <stdlib.h>

#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>

using namespace std;


using namespace cgicc;

int main ()
{
Cgicc formData;

cout << "Content-type:text/html\r\n\r\n";


cout << "<html>\n";
cout << "<head>\n";
cout << "<title>Text Area Data to CGI</title>\n";
cout << "</head>\n";
cout << "<body>\n";

form_iterator fi = formData.getElement("textcontent");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "Text Content: " << **fi << endl;
}else{
cout << "No text entered" << endl;
}

cout << "<br/>\n";


cout << "</body>\n";
cout << "</html>\n";

return 0;
}

297
C++

Passing Dropdown Box Data to CGI Program

Dropdown 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 dropdown box:

<form action="/cgi-bin/cpp_dropdown.cgi"
method="post" target="_blank">
<select name="dropdown">
<option value="Maths" selected>Maths</option>
<option value="Physics">Physics</option>
</select>
<input type="submit" value="Submit"/>
</form>

The result of this code is the following form:

Maths Submit

Below is C++ program, which will generate cpp_dropdown.cgi script to handle


input given by web browser through drop down box.

#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>

using namespace std;


using namespace cgicc;

int main ()
{
Cgicc formData;
298
C++

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;
}

cout << "<br/>\n";


cout << "</body>\n";
cout << "</html>\n";

return 0;
}

Using Cookies in CGI

HTTP protocol is a stateless protocol. But for a commercial website it is required


to maintain session information among different pages. For example one user
registration ends after completing many pages. But how to maintain user's
session information across all the web pages.

In many situations, using cookies is the most efficient method of remembering


and tracking preferences, purchases, commissions, and other information
required for better visitor experience or site statistics.

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.

Cookies are a plain text data record of 5 variable-length fields:

 Expires: This showsthe date the cookie will expire. If this is blank, the
cookie will expire when the visitor quits the browser.
299
C++

 Domain: This is the domain name of your site.

 Path: This is the path to the directory or web page that sets the cookie.
This may be blank if you want to retrieve the cookie from any directory or
page.

 Secure: If this field contains the word "secure" then the cookie may only
be retrieved with a secure server. If this field is blank, no such restriction
exists.

 Name=Value: Cookies are set and retrieved in the form of key and value
pairs.

Setting up Cookies

It is very easy to send cookies to browser. These cookies will be sent along with
HTTP Header before the Content-type filed. Assuming you want to set UserID
and Password as cookies. So cookies setting will be done as follows:

#include <iostream>
using namespace std;

int main ()
{

cout << "Set-Cookie:UserID=XYZ;\r\n";


cout << "Set-Cookie:Password=XYZ123;\r\n";
cout << "Set-Cookie:Domain=www.tutorialspoint.com;\r\n";
cout << "Set-Cookie:Path=/perl;\n";
cout << "Content-type:text/html\r\n\r\n";

cout << "<html>\n";


cout << "<head>\n";
cout << "<title>Cookies in CGI</title>\n";
cout << "</head>\n";
cout << "<body>\n";

cout << "Setting cookies" << endl;

cout << "<br/>\n";


cout << "</body>\n";

300
C++

cout << "</html>\n";

return 0;
}

From this example, you must have understood how to set cookies. We use Set-
Cookie HTTP header to set cookies.

Here, it is optional to set cookies attributes like Expires, Domain, and Path. It is
notable that cookies are set before sending magic line "Content-
type:text/html\r\n\r\n.

Compile above program to produce setcookies.cgi, and try to set cookies using
following link. It will set four cookies at your computer:

/cgi-bin/setcookies.cgi

Retrieving Cookies

It is easy to retrieve all the set cookies. Cookies are stored in CGI environment
variable HTTP_COOKIE and they will have following form.

key1=value1;key2=value2;key3=value3....

Here is an example of how to retrieve cookies.

#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <stdlib.h>

#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>

using namespace std;


using namespace cgicc;

int main ()
{

301
C++

Cgicc cgi;
const_cookie_iterator cci;

cout << "Content-type:text/html\r\n\r\n";


cout << "<html>\n";
cout << "<head>\n";
cout << "<title>Cookies in CGI</title>\n";
cout << "</head>\n";
cout << "<body>\n";
cout << "<table border = \"0\" cellspacing = \"2\">";

// get environment variables


const CgiEnvironment& env = cgi.getEnvironment();

for( cci = env.getCookieList().begin();


cci != env.getCookieList().end();
++cci )
{
cout << "<tr><td>" << cci->getName() << "</td><td>";
cout << cci->getValue();
cout << "</td></tr>\n";
}
cout << "</table><\n";

cout << "<br/>\n";


cout << "</body>\n";
cout << "</html>\n";

return 0;
}

Now, compile above program to produce getcookies.cgi, and try to get a list of
all the cookies available at your computer:

/cgi-bin/getcookies.cgi

302
C++

This will produce a list of all the four cookies set in previous section and all other
cookies set in your computer:

UserID XYZ
Password XYZ123
Domain www.tutorialspoint.com
Path /perl

File Upload Example

To upload a file the HTML form must have the enctype attribute set
to multipart/form-data. The input tag with the file type will create a "Browse"
button.

<html>
<body>
<form enctype="multipart/form-data"
action="/cgi-bin/cpp_uploadfile.cgi"
method="post">
<p>File: <input type="file" name="userfile" /></p>
<p><input type="submit" value="Upload" /></p>
</form>
</body>
</html>

The result of this code is the following form:

File:

Upload

Note: Above example has been disabled intentionally to stop people uploading
files on our server. But you can try above code with your server.

Here is the script cpp_uploadfile.cpp to handle file upload:

#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <stdlib.h>

303
C++

#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>

using namespace std;


using namespace cgicc;

int main ()
{
Cgicc cgi;

cout << "Content-type:text/html\r\n\r\n";


cout << "<html>\n";
cout << "<head>\n";
cout << "<title>File Upload in CGI</title>\n";
cout << "</head>\n";
cout << "<body>\n";

// get list of files to be uploaded


const_file_iterator file = cgi.getFile("userfile");
if(file != cgi.getFiles().end()) {
// send data type at cout.
cout << HTTPContentHeader(file->getDataType());
// write content at cout.
file->writeToStream(cout);
}
cout << "<File uploaded successfully>\n";
cout << "</body>\n";
cout << "</html>\n";

return 0;
}

304
C++

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.

305
C++

39. STL TUTORIAL

Hope you have already understood the concept of C++ Template which we have
discussed earlier. The C++ STL (Standard Template Library) is a powerful set of
C++ template classes to provide general-purpose classes and functions with
templates that implement many popular and commonly used algorithms and
data structures like vectors, lists, queues, and stacks.

At the core of the C++ Standard Template Library are following three well-
structured components:

Component Description

Containers Containers are used to manage collections of objects


of a certain kind. There are several different types of
containers like deque, list, vector, map etc.

Algorithms Algorithms act on containers. They provide the means


by which you will perform initialization, sorting,
searching, and transforming of the contents of
containers.

Iterators Iterators are used to step through the elements of


collections of objects. These collections may be
containers or subsets of containers.

We will discuss about all the three C++ STL components in next chapter while
discussing C++ Standard Library. For now, keep in mind that all the three
components have a rich set of pre-defined functions which help us in doing
complicated tasks in very easy fashion.

Let us take the following program that demonstrates the vector container (a
C++ Standard Template) which is similar to an array with an exception that it
automatically handles its own storage requirements in case it grows:

#include <iostream>
#include <vector>
using namespace std;

int main()
{

306
C++

// create a vector to store int


vector<int> vec;
int i;

// display the original size of vec


cout << "vector size = " << vec.size() << endl;

// push 5 values into the vector


for(i = 0; i < 5; i++){
vec.push_back(i);
}

// display extended size of vec


cout << "extended vector size = " << vec.size() << endl;

// access 5 values from the vector


for(i = 0; i < 5; i++){
cout << "value of vec [" << i << "] = " << vec[i] << endl;
}

// use iterator to access the values


vector<int>::iterator v = vec.begin();
while( v != vec.end()) {
cout << "value of v = " << *v << endl;
v++;
}

return 0;
}

When the above code is compiled and executed, it produces the following result:

vector size = 0
extended vector size = 5
value of vec [0] = 0

307
C++

value of vec [1] = 1


value of vec [2] = 2
value of vec [3] = 3
value of vec [4] = 4
value of v = 0
value of v = 1
value of v = 2
value of v = 3
value of v = 4

Here are following points to be noted related to various functions we used in the
above example:

 The push_back( ) member function inserts value at the end of the vector,
expanding its size as needed.

 The size( ) function displays the size of the vector.

 The function begin( ) returns an iterator to the start of the vector.

 The function end( ) returns an iterator to the end of the vector.

308
C++

40. STANDARD LIBRARY

The C++ Standard Library can be categorized into two parts:

 The Standard Function Library: This library consists of general-


purpose, stand-alone functions that are not part of any class. The function
library is inherited from C.

 The Object Oriented Class Library: This is a collection of classes and


associated functions.

Standard C++ Library incorporates all the Standard C libraries also, with small
additions and changes to support type safety.

The Standard Function Library

The standard function library is divided into the following categories:

 I/O,

 String and character handling,

 Mathematical,

 Time, date, and localization,

 Dynamic allocation,

 Miscellaneous,

 Wide-character functions

The Object Oriented Class Library

Standard C++ Object Oriented Library defines an extensive set of classes that
provide support for a number of common activities, including I/O, strings, and
numeric processing. This library includes the following:

 The Standard C++ I/O Classes

 The String Class

 The Numeric Classes

 The STL Container Classes

 The STL Algorithms

 The STL Function Objects

 The STL Iterators

 The STL Allocators

309
C++

 The Localization library

 Exception Handling Classes

 Miscellaneous Support Library

310

You might also like