Object Oriented Programming
Object Oriented Programming
Syllabus
OBJECT ORIENTED PROGRAMMING C++
1. Introduction :
Output using cout. Directives. Input with cin. Type bool. The setw
manipulator. Type conversions.
3. Functions :
6. Operator overloading :
7. Inheritance :
8. Pointer :
9. Virtual Function :
Streams classes, Stream Errors, Disk File I/O with streams, file
pointers, error handling in file I/O with member function, overloading
the extraction and insertion operators, memory as a stream object,
command line arguments, and printer output.
1. Function Blocks
4
1
FUNDAMENTALS OF C++
Unit Structure
1.1 Introduction of C++
1.2 Object-Oriented Programming
1.3 Encapsulation
1.4 Polymorphism
1.5 Inheritance
1.6 The Need for C++
1.7 Characteristics of OOPs
1.8 C++ and C
1.3 ENCAPSULATION
1.4 POLYMORPHISM
turning the steering wheel left causes the car to go left no matter
what type of steering is used. The benefit of the uniform interface
is, of course, that once you know how to operate the steering
wheel, you can drive any type of car.
1.5 INHERITANCE
OOP offers several benefits to both the program designer and the
user. The principal advantages are.
1) Emphasis is on data rather than procedure.
2) Programs are divided into what are known as objects.
3) Data structures are designed such that they characterize the
objects.
4) Functions that operate on the data of an object are tied together
in the data structure.
5) Data is hidden and cannot be accessed by external functions.
6) Objects may communicate with each other through functions.
7) New data and functions can be easily added wherever
necessary.
8) Follows bottom up approach in program design.
9) Through inheritance, we can eliminate redundant code and
extend the use of existing classes
10) We can build program from the standard working module that
communicate with one another, rather than having to start
writing the code from scratch. This leads to saving of
development time and higher productivity.
11) The principal of data hiding helps the programmer to build
secure programs that cannot be invaded by code in other part
of the program.
12) It is possible to have multiple instance of an object to co-exist
without any interference
13) It is easy to partition the work in a project, based on objects.
14) Object oriented systems can be easily upgraded from small to
large systems.
15) Message passing techniques for communication between
objects makes the interface description with external systems
much simpler.
16) Software complexity can be easily managed.
10
2
C++ PROGRAMMING BASICS
Unit Structure
2.1 Some of the important concepts in oops are
2.2 Basic Data Types in C++
2.3 Variables in C++
2.4 Operators in C++
1) Objects
2) Classes
3) Data abstraction & Encapsulation.
4) Inheritance
5) Polymorphism
6) Dynamic binding.
7) Message passing.
2.1.1 Object:-
Ex. If there are two objects “customer” and “account”, then the
customer object may send a message to the account object
requesting for the bank balance. Thus each object contains data,
and code to manipulate the data.
11
2.1.2 Classes
i) The entire set of data and code of an object can be made a user-
defined data type with the help of a class. Objects are actually
variable of the type class.
ii) Once a class has been defined, we can create any number of
objects belonging to that class. Thus a class is collection of
objects of similar type.
iii) Classes are user defined data types and behaves like the built in
type of a programming language.
iv) The syntax for defining class is class class-name
{
----------------
----------------
}
2.1.5 Polymorphism
i) Polymorphism is important oops concept. It means ability to take
more than one form.
12
# include<iostream.h>
int main()
{
cout<<.Hello World.;
return 0;
}
Syntax:- cin>>variable;
Syntax:- cout<<string;
Structure Array
Union Function
Class Pointer
Enumeration reference
Built-in-type
1) Integral type : – The data types in this type are int and char.
The modifiers signed, unsigned, long & short may be applied to
character & integer basic data type. The size of int is 2 bytes and
char is 1 byte.
Ex - Void * ptr1;
Char * ptr2;
ptr2 = ptr1;
is allowed in c but not in c++
3) Floating type:
The data types in this are float & double. The size of the float
is 4 byte and double is 8 byte. The modifier long can be applied to
double & the size of long double is 10 byte.
User-defined type:
i) The user-defined data type structure and union are same as
that of C.
ii) Classes – Class is a user defined data type which can be used
just like any other basic data type once declared. The class
variables are known as objects.
iii) Enumeration
a) An enumerated data type is another user defined type which
provides a way of attaching names to numbers to increase
simplicity of the code.
c) Syntax:-
enum shape {
circle,
square,
triangle
}
EX . shape oval;
16
EX enum colour {red, blue, pink = 3}; //it will assign red to o, blue
to 1, & pink to 3 or enum colour {red = 5, blue, green}; //it will
assign red to 5, blue to 6 & green to 7.
1) Arrays
An array in c++ is similar to that in c, the only difference is
the way character arrays are initialized. In c++, the size should be
one larger than the number of character in the string where in c, it is
exact same as the length of string constant.
2) Functions
Functions in c++ are different than in c there is lots of
modification in functions in c++ due to object orientated concepts in
c++.
3) Pointers
Pointers are declared & initialized as in c.
Declaration of variables.
This declares three variables (a, b and c), all of them of type
int, and has exactly the same meaning as: int a;
int b;
int c;
The integer data types char, short, long and int can be
either signed or unsigned depending on the range of numbers
needed to be represented. Signed types can represent both
positive and negative values, whereas unsigned types can only
represent positive values (and zero). This can be specified by using
either the specifier signed or the specifier unsigned before the type
name.
Scope of variables:
Ex int m = 10;
Reference variables
ii) Example:-
If we make the variable sum a reference to the
variable total, then sum & total can be used
interchangeably to represent that variable.
Introduction to strings:
Strings can also perform all the other basic operations that
fundamental data types can, like being declared without an initial
value and being assigned values during execution.
+ addition
- subtraction
* multiplication
/ division
% modulo
2.4.3 Compound assignment (+=, -=, *=, /=, %=, >>=, <<=,
&=, ^=, |=)
expression is equivalent to
Example1 Example 2
B=3; B=3;
A=++B; A=B++;
2.4.5 Relational and equality operators ( ==, !=, >, <, >=, <= ):
Operators Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
24
For example:
!(5 == 5) // evaluates to false because the expression at its right
(5 == 5) is true.
!(6 <= 4) // evaluates to true because (6 <= 4) would be false.
!true // evaluates to false
!false // evaluates to true.
&& OPERATOR
a b a && b
true true true
true false false
false true false
false false false
|| OPERATOR
a b a || b
true true true
true false true
false true true
false false falseFor example:
( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false ).
( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false ).
2.4.9 sizeof()
two unary operators new and delete that perform the task of
allocating & freeing the memory.
EX p = new int.
4) New can be used to create a memory space for any data type
including user defined type such all array, classes etc.
Manipulators:
Manipulators are operators that are used to format the data
display. There are two important manipulators.
1) endl
2) stew
1) endl : -
This manipulator is used to insert a linefeed into an output. It
has same effect as using .\n. for newline.
The output is
a = 2568
n = 34
p = 275
2) Setw : -
With the stew, we can specify a common field width for all
the numbers and force them to print with right alignment.
3 5 6
Ex avg = sum/float(i)
30
3
CONTROL STATEMENTS
Unit Structure
3.1 Introduction :
3.2 if – else Statement
3.3 Nested ifs :
3.4 The switch Statement
3.5 The for Loop
3.6 The while Loop
3.7 The do-while Loop
3.8 Using break to Exit a Loop
3.9 Using the goto Statement
3.1 INTRODUCTION :
if(expression)
{
statement sequence
}
else
{
statement sequence
}
#include<iostream>
#include<cstdlib>
int main()
{
int magic;// magic number
int guess;// users guess
magic = rand(); // get a random number
cout << “Enter your guess”
cin >> guess;
if (guess == magic) cout << “Right”;
else cout<< “ sorry , your are wrong”;
return 0;
}
if(expression)
{
statement sequence
if(expression)
{
statement sequence
}
else
{
statement sequence
}
}
else
{
statement sequence
}
Here is an example
if(i)
{
if(j) result =1;
if(k) result =2;
else result = 3;
}
else result = 4;
The final else is not associated with if(j) (even though it is the
closest if without an else), because it is not in the same block.
Rather, the final else is associated with if(i). The inner else is
associated with if(k) because that is the nearest if. You can use a
nested if to add a further improvement to the Magic Number
program. This addition provides the player with feedback about a
wrong guess.
{ case constant 1 :
Statement sequence
Break;
case constant 2 :
Statement sequence
Break;
case constant 3 :
Statement sequence
Break;
.
.
.
Default:
Statement sequence
}
The switch differs from the if in that switch can test only for
equality (that is, for matches between the switch expression and
the case constants), whereas the if conditional expression can be
of any type.
#include <iostream>
using namespace std;
int main()
{
int num;
cout<< “Enter a number from 1 to 3”;
cin >>num;
switch(num)
{
case 1:
cout << “ A rolling stone gathers no moss.\n”;
break;
case 2:
cout<< “ A bird in hand is worth two in the bush.\n”;
break;
case 3:
cout<< “ A full and his money soon parted.\n”;
break;
default :
cout<< “ you must enter 1 , 2 or 3.\n”;
break;
}
return 0;
}
You have been using a simple form of the for loop since
Module 1. You might be surprised at just how powerful and flexible
the for loop is. Let’s begin by reviewing the basics, starting with the
most traditional forms of the for.
The general form of the for loop for repeating a single statement is
for(initialization; expression; increment) statement;
For repeating a block, the general form is
for(initialization; expression; increment)
{
statement sequence
}
#include <iostream>
#inclume<cmath>
int main()
{
int num;
double sq_root;
for(num=1;num<100;num++)
{
sq_root=sqrt((double)num);
cout<<num<<””<<sq_root<<’\n’;
}
return 0;
}
36
Another loop is the while. The general form of the while loop
is while(expression) statement; where statement may be a single
statement or a block of statements. The expression defines the
condition that controls the loop, and it can be any valid expression.
The statement is performed while the condition is true. When the
condition becomes false, program control passes to the line
immediately following the loop.
#include<iostream>
using namespace std;
int main()
{
int len;
cout<<”Enter length(1 to 79)”;
cin>>len;
while(len>0 $$ len<80)
{
cout<<’.’;
len--;
}
return 0;
}
If len is out of range, then the while loop will not execute
even once. Otherwise, the loop executes until len reaches zero.
There need not be any statements at all in the body of the while
loop. Here is an example: while(rand() != 100) ; This loop iterates
until the random number generated by rand( ) equals 100.
37
#include<iostream>
using namespace std;
int main()
{
int num;
do
{
cout << “Enter a number (100 to stop):”;
cin>> num;
}
while(num!=100);
return 0;
}
int main()
{
int t;
38
for(t=0;t<100;t++)
{
if(t==10) break;
cout<<t<< ‘ ’;
}
return 0;
}
Using continue
#include<iostream>
using namespace std;
int main()
{
int x;
for(x=0;x<100;x++)
{
if(x%2) continue;
cout<<x<< ‘ ’;
}
return 0;
}
One good use for the goto is to exit from a deeply nested routine.
For example, consider the following code fragment:
for(…){
for(…){
while(…){
if(…)goto stop
.
.
.
}
}
}
stop:
cout<<”Enter in program.\n”;
Eliminating the goto would force a number of additional tests
to be performed. A simple break statement would not work here,
because it would only cause the program to exit from the innermost
loop.
40
4
FUNCTIONS
Unit Structure
4.1 Introduction :
4.2 Function
4.3 Arguments passed by value and by reference.
4.4 Default values in parameters
4.5 Overloaded functions
4.6 inline functions
4.7 Recursivity
4.1 INTRODUCTION :
4.2 FUNCTION
where:
type is the data type specifier of the data returned by the
function.
name is the identifier by which it will be possible to call the
function.
parameters (as many as needed): Each parameter consists
of a data type specifier followed by an identifier, like any
regular variable declaration (for example: int x) and which
acts within the function as a regular local variable. They
allow to pass arguments to the function when it is called. The
different parameters are separated by commas.
statements is the function's body. It is a block of statements
surrounded by braces { }.
41
// function example
#include <iostream>
using namespace std;
int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
return 0;
}
The result is 8
int main ()
{
int x=1, y=3, z=7;
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y << ", z=" << z;
return 0;
}
The first thing that should call your attention is that in the
declaration of duplicate the type of each parameter was followed by
an ampersand sign (&). This ampersand is what specifies that their
corresponding arguments are to be passed by reference instead of
by value.
int main ()
{
int x=100, y, z;
prevnext (x, y, z);
cout << "Previous=" << y << ", Next=" << z;
return 0;
}
For example:
// default values in functions
#include <iostream>
using namespace std;
int main ()
{
cout << divide (12);
46
The output is : 6
5
As we can see in the body of the program there are two calls
to function divide. In the first one:
divide (12)
divide (20,4)
there are two parameters, so the default value for b (int b=2)
is ignored and b takes the value passed as argument, that is 4,
making the result returned equal to 5 (20/4).
For example:
// overloaded function
#include <iostream>
using namespace std;
{
return (a/b);
}
int main ()
{
int x=5,y=2;
float n=5.0,m=2.0;
cout << operate (x,y);
cout << "\n";
cout << operate (n,m);
cout << "\n";
return 0;
}
The output is : 10
2.5
and the call is just like the call to any other function. You do not
have to include the inline keyword when calling the function, only in
its declaration.
4.7 RECURSIVITY
5! = 5 * 4 * 3 * 2 * 1 = 120
// factorial calculator
#include <iostream>
using namespace std;
int main ()
49
{
long number;
cout << "Please type a number: ";
cin >> number;
cout << number << "! = " << factorial (number);
return 0;
}
50
5
OBJECT AND CLASSES
Unit Structure
5.1 Introduction to Classes
5.2 Class Definition
5.3 Classes and Objects
5.4 Access specifis- Private Public and Protected members
5.5 Member Functions of a Class
5.6 Passing and Returning Objects
5.7 Creating and Using a Copy Constructor
Class is a user defined data type just like structures, but with
a difference. It also has three sections namely private, public and
protected. Using these, access to member variables of a class can
be strictly controlled.
class class_name
{
permission_label_1:
member1;
permission_label_2:
member2;
...
} object_name;
51
example:-
class tag_name
{
public : // Must
type member_variable_name;
:
type member_function_name();
:
private: // Optional
type member_variable_name;
:
type member_function_name();
:
};
e.g.
class tag_name
{
type member_variable_name; // private
:
type member_function_name(); // private
:
public : // Must
type member_variable_name;
:
type member_function_name();
:
};
e.g.
class player
{
public :
void getstats(void);
void showstats(void);
int no_player;
private :
char name[40];
int age;
int runs;
int tests;
float average;
float calcaverage(void);
};
With information hiding one need not know how actually the
data is represented or functions implemented. The program need
not know about the changes in the private data and functions. The
interface(public) functions take care of this. The OOP methodology
is to hide the implementation specific details, thus reducing the
complexities involved.
where Sachin and Dravid are two objects of the class player.
Both the objects have their own set of member variables. Once the
object is declared, its public members can be accessed using the
dot operator with the name of the object. We can also use the
variable no_player in the public section with a dot operator in
functions other than the functions declared in the public section of
the class.
e.g.
Sachin.getstats();
Dravid.showstats();
Mohan.no_player = 10;
e.g.
void player :: getstats (void)
{
:
:
}
int main ()
{
CRectangle rect, rectb;
rect.set_values (3,4);
rectb.set_values (5,6);
The output is :
rect area: 12
rectb area: 30
e.g.
class check
{
public :
check add(check);
void get()
{
56
cin >> a;
}
void put()
{
cout << a;
}
private :
int a;
};
void main()
{
check c1,c2,c3;
c1.get();
c2.get();
c3 = c1.add(c2);
c3.put();
}
check check :: add ( check c2)
{
check temp;
temp.a = a + c2.a;
return ( temp);
}
You can also notice that in the class add() the variable of the
object c1 is just referred as ‘a’ where as the member of the object
passed .i.e. c2 is referred as ‘c2.a’ . This is because the member
function will be pointed by the pointer named this in the compiler
where as what we pass should be accessed by the extraction
operator ‘.’. we may pass more than one object and also normal
variable. we can return an object or a normal variable from the
function. We have made use of a temporary object in the function
add() in order to facilitate return of the object.
57
MyClass x;
MyClass y; x = y; // copy constructor not used here.
#include <iostream>
using namespace std;
class Myclass
{
int val;
int copynumber;
public:
//Normal constructor
Myclass(int i)
{
59
val=i;
copynumber = 0;
cout<< “Inside normal constructor\n”;
}
//Copy constructor
~Myclass()
{
if (copynumber==0)
cout<< “Destructing original \n”;
else
cout<< “Destructing Copy”<< copynumber <<
“\n”;
}
int getval()
{
return val;
}
};
void display(Myclass ob)
{
cout<< ob.getval()<< “\n”;
}
int main()
{
Myclass a(10);
display a;
return 0;
}
60
61
6
STRUCTURES AND UNION
Unit Structure
6.1 Structures
6.2 Pointers to structures
6.3 Nesting structures
6.4 User Defined Data Types
6.5 Unions
6.6 Enumerations (enum)
6.1 STRUCTURES
struct model_name
{
type1 element1;
type2 element2;
type3 element3;
.
.
} object_name;
struct products
{
char name [30];
float price;
};
products apple;
products orange, melon;
struct products {
char name [30];
float price;
} apple, orange, melon;
apple.name
apple.price
orange.name
orange.price
melon.name
melon.price
#include <iostream.h>
#include <string.h>
#include <stdlib.h>
struct movies_t {
char title [50];
int year;
} mine, yours;
mine.year = 1968;
cout << "Enter title: ";
cin.getline (yours.title,50);
cout << "Enter year: ";
cin.getline (buffer,50);
yours.year = atoi (buffer);
64
Output :
Enter title: Alien
Enter year: 1979
My favourite movie is:
2001 A Space Odyssey (1968)
And yours:
Alien (1979)
// array of structures
#include <iostream.h>
#include <stdlib.h>
#define N_MOVIES 5
65
struct movies_t
{
char title [50];
int year;
} films [N_MOVIES];
pmovie = &amovie;
// pointers to structures
#include <iostream.h>
67
#include <stdlib.h>
struct movies_t
{
char title [50];
int year;
};
int main ()
{
char buffer[50];
movies_t amovie;
movies_t * pmovie;
pmovie = & amovie;
pmovie->title
that could be translated to:
(*pmovie).title
*pmovie.title
that is equivalent to
*(pmovie.title)
and that would serve to evaluate the value pointed by element title
of structure movies, that in this case (where title is not a pointer) it
would not make much sense.
struct movies_t
{
char title [50];
int year;
}
struct friends_t
{
char name [50];
char email [50];
movies_t favourite_movie;
} charlie, maria;
charlie.name
maria.favourite_movie.title
charlie.favourite_movie.year
pfriends->favourite_movie.year
Typedef
For example:
typedef char C;
typedef unsigned int WORD;
typedef char * string_t;
typedef char field [50];
6.5 UNIONS
For example:
union mytypes_t
{
char c;
int i;
float f;
} mytypes;
defines three elements:
mytypes.c mytypes.i
mytypes.f
71
each one of a different data type. Since all of them are referring to a
same location in memory, the modification of one of the elements
will afect the value of all of them.
union mix_t
{
long l;
struct
{
short hi;
short lo;
} s;
char c[4];
} mix;
Anonymous unions
In C++ we have the option that unions be anonymous. If we
include a union in a structure without any object name (the one that
goes after the curly brackets { }) the union will be anonymous and
we will be able to access the elements directly by its name. For
example, look at the difference between these two declarations:
Union
struct
{
char title[50];
char author[50];
union
{
float dollars;
int yens;
};
} book;
72
anonymous union
struct
{
char title[50];
char author[50];
union
{
float dollars;
int yens;
} price;
} book;
book.price.dollars
book.price.yens
book.dollars
book.yens
enum model_name
{
value1,
value2,
value3,
.
.
} object_name;
73
colors_t mycolor;
mycolor = blue;
if (mycolor == green) mycolor = red;
enum months_t
{
january=1, february, march, april,
may, june, july, august,
september, october, november, December
} y2k;
74
7
ARRAYS
Unit Structure
7.1 Arrays
7.2 One-dimensional arrays
7.3 Two-Dimensional Arrays
7.4 Arrays of Strings
7.5 Arrays of Objects
7.6 Introduction to strings class
7.1 ARRAYS
The array that you will probably use most often is the
character array, because it is used to hold a character string. The
C++ language does not define a built-in string data type. Instead,
strings are implemented as arrays of characters. This approach to
strings allows greater power and flexibility than are available in
languages that use a distinct string type.
type name[size];
Here, type declares the base type of the array. The base
type determines the data type of each element that makes up the
array. The number of elements the array can hold is specified by
size. For example, the following declares an integer array named
sample that is ten elements long:
int sample[10];
For example, the following program loads sample with the numbers
0 through 9:
#include <iostream>
using namespace std;
int main();
{
int sample[10]; // this reserves 10 integer
elements
int t;
return 0;
}
76
This is sample[0]: 0
This is sample[1]: 1
This is sample[2]: 2
This is sample[3]: 3
This is sample[4]: 4
This is sample[5]: 5
This is sample[6]: 6
This is sample[7]: 7
This is sample[8]: 8
This is sample[9]: 9
#include <iostream>
using namespace std;
int main()
{
int i, avg, min_val, max_val;
int nums[10];
num[0]=10;
num[1]=18;
num[2]=75;
num[3]=0;
num[4]=1;
77
num[5]=56;
num[6]=100;
num[7]=12;
num[8]=-19;
num[9]=88;
return 0;
}
78
Average is 34
Minimum value: -19
Maximum value: 100
int twoD[10][20];
#include<iostream>
using namespace std;
int main()
{
int t,i, nums[3][4];
for(t=0;t<3;++t)
{
for(i=0;i<4;++i)
{
79
nums[t][i]=(t*4)+i+1;
cout<<nums[t][i]<< ‘ ’ ;
}
cout<< ‘\n’;
}
return 0;
}
0 1 2 3
0 1 2 3 4
1 5 6 7 8
num[1][2]
2 9 10 11 12
char str_array[30][80];
gets(str_array[2]);
80
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
int i;
char str[80];
char numbers[10][80]= { “Tom”=, “555-3322”,
“Mary”, “555-8976”,
“Jon”, “555-1037”,
“Rachel”, “555-1400”
};
cout<< “Enter name:”;
cin>> str;
for(i=0;i<10;i+=2)
{
if(!strcmp(str,numbers[i]))
{
cout<< “Number is ” <<numbers[i+1] << “\n”;
break;
}
if(i==10)
{
cout<< “Not found\n”;
}
}
return 0;
}
Notice how the for loop increments its loop control variable, i,
by 2 each time through the loop. This is necessary because names
and numbers alternate in the array.
You can create arrays of objects in the same way that you
create arrays of any other data type. For example, the following
program creates an array of MyClass objects. The objects that
comprise the elements of the array are accessed using the normal
array-indexing syntax.
#include<iostream>
using namespace std;
class MyClass
{
int x;
public:
void set_x(int i) {x=i;}
int get_x() {return x;}
};
int main()
{
MyClass obs[4];
int i;
for(i=0;i<4;i++)
{obs[i].set_x(i);}
for(i=0;i<4;i++)
{
cout<< “obs[ “<<i<<”].get_x():
”<<obs[i].get_x()<< “\n”;
}
return 0;
}
obs[0].get_x(): 0
obs[1].get_x(): 1
obs[2].get_x(): 2
obs[3].get_x(): 3
82
// my first string
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystring = "This is a string";
cout << mystring;
return 0;
}
The output is :
This is a string
Strings can also perform all the other basic operations that
fundamental data types can, like being declared without an initial
value and being assigned values during execution:
// my first string
#include <iostream>
#include <string>
using namespace std;
83
int main ()
{
string mystring;
mystring = "This is the initial string content";
cout << mystring << endl;
mystring = "This is a different string content";
cout << mystring << endl;
return 0;
}
The output is :
84
8
OPERATOR OVERLOADING
Unit Structure
8.1 Operator Overloading
8.2 Defining operator overloading
8.3 Unary Operator over loading -
8.4 Binary Operator overloading
Example:-
The input/output operators << and >> are good examples of
operator overloading
although the built in definition of the << operator is for shifting of
bits. It is also used
for displaying the values of various data types.
iii) Example .
Vector operator . ( ) ; // unary minus
Vector operator + (vector); // vector addition
Friend vector operator + (vector, vector) // vector
addition
Friend vector operator . (vector); // unary minus
Vector operator . (vector & a); // subtraction
Int operator == (vector); // comparision
Friend int operator == (vector,vector) //comparision
Op x or x op
x op y
# include <iostream.h>
class unary
{
int x, y, z;
public:
void getdata (int a, int , intc);
void display (void);
void operator . (); // overload unary minus.
};
void unary :: getdata (int a, int b, int c)
{
x = a;
y = b;
z = c;
}
void unary : : display (void)
{
cout << x << . . << y << . . << z << .\n.;
}
void unary ::operator .()
{
87
x = -x ;
y = -y ;
z = -z ;
}
main ( )
{
unary u;
u.getdata(20, -30, 40);
cout << . u : . ;
u. display ( ) ;
-u;
cout << . u : . ;
u. display ( ) ;
}
# include<iostream.h>
class complex
{
float x, y;
public :
complex ( );
complex (float real, float imag)
{
x = real;
y = imag;
}
complex operator +(complex);
void display(void);
};
complex complex:: operator+(complex c)
{
complex temp;
temp.x = x + c.z;
temp.y = y + c.y;
return (temp);
}
void complex : : display (void)
{
cout << z << . + j .<< y << . \n .;
}
main ( )
{
complex c1,c2,c3;
c1 = complex (2.5, 3.5);
c2 = complex (1.6, 2.7);
c3 = c1 + c2;
cout << .c1 = .; c1.display( ) ;
cout << .c2 = .; c2.display( ) ;
cout << .c3 = .; c3.display( ) ;
}
Type Casting
Implicit conversion
short a=2000;
int b;
b=a;
Here, the value of a has been promoted from short to int and
we have not had to specify any type-casting operator. This is
known as a standard conversion. Standard conversions affect
fundamental data types, and allow conversions such as the
conversions between numerical types (short to int, int to float,
double to int...), to or from bool, and some pointer conversions.
Some of these conversions may imply a loss of precision, which the
compiler can signal with a warning. This can be avoided with an
explicit conversion.
For example:
class A {};
class B { public: B (A a) {} };
A a;
B b=a;
Explicit conversion
short a=2000;
int b;
b = (int) a; // c-like cast notation
b = int (a); // functional notation
// class type-casting
#include <iostream>
using namespace std;
class CDummy
{
float i,j;
};
class CAddition
{
int x,y;
public:
CAddition (int a, int b)
{
x=a;
y=b;
}
91
int result()
{
return x+y;}
};
int main ()
{
CDummy d;
CAddition * padd;
padd = (CAddition*) &d;
cout << padd->result();
return 0;
}
class Y
{
public:
Y(X); // Convert X to Y
92
};
void f(Y);
int main()
{
X x;
//! f(x); // Error: ambiguous conversion
} ///:~
class A {};
class B {};
class C
{
public:
operator A() const;
operator B() const;
};
// Overloaded h():
void h(A);
void h(B);
int main()
{
C c;
//! h(c); // Error: C -> A or C -> B ???
} ///:~
#include <iostream>
using namespace std;
class MyClass
{
int data;
public:
explicit MyClass(int aData) {
cout << "Constructor invoked" << endl;
data = aData;
}
};
int main ()
{
MyClass obj1(100);
/*
* Object creation by conversion as below reports a compiler error.
* Error E2034 explicit.cpp 15: Cannot convert 'int' to 'MyClass'
* in function main()
*/
// MyClass obj2 = 200;
}
94
9
INHERITANCE
Unit Structure
9.1 Introduction
9.2 Types of Inheritance
9.3 Derived and Base Class
9.4 Public Inheritance
9.5 Private Inheritance
9.1 INTRODUCTION :
Inheritance:
The Inheritance is the mechanism of deriving one class from
the other class. Let us assume that the class def is derived from the
existing base class abc. In that case abc is called as base class
and def is called as derived class. The feature that is facility of the
base class will be inherited to the derived class. The derived class
will have its own features. The features of the derived class will
never be inherited to the base class.
Need of Inheritance:
In object oriented programming there are applications for
which the classes are develop, every classes will have its own
features .Consider a situation where we require all the features of a
particular existing class and we also need some additional features.
The above requirement can be satisfied with three different
methods.
95
1) Modify the original existing class by acting new features into it.
The disadvantage of this method is that the users of the original
class will get some extra facility and they can misuse them
2) Rewrite the new class with all the required features i.e. the
features of the existing class plus the new features. The
disadvantage of this method is that it will be consuming more time
and space.
3) Derive the new class from the existing class and only write the
new features in the derived class. The features of the original class
will be inherited to the new class. This method consumes less
space and time. Moreover the original class is not modified. Hence
user of original class will not get extra facilities.
A B
C
96
BASE CLASS A
B C D
BASE CLASS A
B
BINTERMEDIATE BASE CLASS
c
DERIVED CLASS C
B C
D
97
1. Base class: -
A base class can be defined as a normal C++ class,
which may consist of some data and functions.
Ex .
class Base
{
:::::
}
2. Derived Class: -
# include<iostream.h>
class base
{
int no1;
public:
int no2;
void getdata();
int getno1();
void showno1();
};
class derived: public Base // public derivation.
{
int no3;
public:
void add();
void display();
};
void Base :: getdata()
{
no1 = 10;
no2 = 20;
}
int Base :: getno1()
{
return no1;
}
void Base :: showno1()
{
cout <<.Number1 =.<<no1 <<.\n.;
}
void Derived :: add()
{
no3 = no2 + getno1(); // no1 is private
}
void Derived :: display()
{
cout << .Number1 = .<<getno1() <<.\n.;
cout << .Number2 = .<<no2<<\n.;
99
Number1 = 10
Number1 = 10
Number2 = 20
Sum = 30
Number1 = 10
Number2 = 100
Sum = 110
iv) Syntax is .
class ABC: private PQR
{
member of ABC
}
#include <iostream.h>
class base
{
int x;
public :
int y;
void getxy() ;
int get_x(void) ;
void show_x(void) ;
};
void base ::getxy(void)
{
cout<<.Enter Values for x and y : . ;
cin >> x >> y ;
}
int base : : get_x()
{
return x;
}
void base :: show_x()
{
cout <<.x = . << x << .\n.;
}
void Derived : : mul( )
{
getxy();
z = y * get_x ( ) ;
}
void Derived ::display()
101
{
show_x ( ) ;
cout <<.y = . <<y<<.\n.;
cout<<.z = . <<z<<.\n.;
}
main ( )
{
Derived d;
d. mul();
d.display() ;
//d.y = 4a; won.t work y has become
private.
d.mul();
d.display();
}
derived-constructor(arg-list) : base-cons(arg-list);
{
body of derived constructor
}
102
#include<iostream>
#include<cstring>
using namespace std;
//accessor functions
double getWidth() {return width;}
double getHeight(){return height;}
void setWidth(double w)P{width=w;}
void setHeight(double h){height=h;}
};
103
double area()
{
return getWidth() *getHeight()/2;
}
void showStyle()
{
cout<<”Triangle is”<<style<<”\n”;
}
};
int main()
{
Triangle t1(“isosceles”,4.0,4.0);
Triangle t2(“right”,8.0, 12.0);
cout<<”Info for t1:\n”;
t1.showStyle();
t1.showDim();
cout<<”Area is” << t1.area()<<”\n”;
cout<<”\n”;
cout<<”Info for t2:\n”;
t2.shwoStyle();
t2.showDim();
cout<<”Area is”<<t2.area()<<”\n”;
return0;
}
104
Summary of derivations
106
10
POINTERS
Unit Structure
10.1 Introduction :
10.2 Pointer
10.3 The Pointer Operators
10.4 The Base Type of a Pointer
10.5 Assigning Values through a Pointer
10.6 Pointers and Arrays
10.7 Arrays of Pointers
10.8 Function Pointer
10.9 Assign an Address to a Function Pointer
10.10 Calling a Function using a Function Pointer
10.11 Pass a Function Pointer as an Argument
10.12 Return a Function Pointer
10.13 Pointers to Objects
10.14 Operators new and new[]
10.15 Operator delete and delete[]
10.1 INTRODUCTION :
10.2 POINTER
int *ip;
There are two special operators that are used with pointers:
* and &. The & is a unary operator that returns the memory address
of its operand. (Recall that a unary operator requires only one
operand.)
This puts into ptr the memory address of the variable total.
This address is the location of total in the computer’s internal
memory. It has nothing to do with the value of total. The operation
of & can be remembered as returning “the address of” the variable
it precedes. Therefore, the preceding assignment statement could
be verbalized as “ptr receives the address of total.” To better
understand this assignment, assume that the variable total is
located at address 100. Then, after the assignment takes place, ptr
has the value 100.
val = *ptr;
will place the value of total into val. For example, if total
originally had the value 3,200, then val will have the value 3,200,
because that is the value stored at location 100, the memory
address that was assigned to ptr. The operation of * can be
remembered as “at address.” In this case, then, the statement
could be read as “val receives the value at address ptr.”
#include <iostream>
using namespace std;
int main()
{
int total;
int *ptr;
int val;
total = 3200; // assign 3,200 to total
ptr = &total; // get address of total
val = *ptr; // get value at that address
cout << "Total is: " << val << '\n';
return 0;
}
the type of data upon which the pointer operates. In this case,
because ptr is an int pointer, four bytes of information are copied
into val (assuming a 32-bit int) from the address pointed to by ptr.
However, if ptr had been a double pointer, for example, then eight
bytes would have been copied.
#include<iostream>
using namespace std;
int main()
{
double x, y;
110
int *p;
x=123.23;
p=(int *);
y=*p; // This statement wont yield the
desire result
cout<<y;
return 0;
}
1.37439e+009
You can verbalize this assignment like this: “At the location
pointed to by p, assign the value 101.” To increment or decrement
the value at the location pointed to by a pointer, you can use a
statement like this:
(*p)++;
#include<iostream>
using namespace std;
int main()
{
int *p, num;
P=#
111
*p=100;
cout<<num<< ‘ ’\n;
(*p)++;
cout<<num<< ‘ ’\n;
(*p)--;
cout<<num<< ‘ ’\n;
return 0;
}
100
101
100
p1 = str;
str[4] or
*(p1+4)
int main()
{
int i;
char str[80] = "This Is A Test";
cout << "Original string: " << str << "\n";
for(i = 0; str[i]; i++)
{
if(isupper(str[i])) str[i] = tolower(str[i]);
else if(islower(str[i])) str[i] = toupper(str[i]);
}
cout << "Inverted-case string: " << str;
return 0
}
checked and changed. The loop iterates until the null terminating
str is indexed. Since a null is zero (false), the loop stops.
int *pi[10];
int var;
pi[2] = &var;
#include<iostream>
#include<cstring>
using namespace std
int main()
{
char *dictionary[ ][2]={“pencil”, “ A writing instrument”,
“keyboard”, “ An input device.”,
“rifle”, “A shoulder-fired
firearm”,
“airplane”, “A fixed-wing
aircraft.”,
“network”, “An interconnected
group of computers.”,
“ ”, “ ”
};
char word[80];
int I;
cout<< “Enter word:”;
cin>>word;
for(i=0; *dictionary[i][0];i++)
114
{
if(!strcmp(dictionary[i][0], word);
{
cout<<dictionary[i][1]<< “\n”;
break;
}
}
if(!*dictionary[i][0]
cout<<word<< “not found. \n”
return 0;
}
Notice that dictionary ends with two null strings. These mark
the end of the array. Recall that a null string contains only the
terminating null character. The for loop runs until the first character
in a string is null. This condition is tested with this expression:
*dictionary[i][0]
Note: You may have got to use the complete name of the member
function including class-name and scope-operator (::). Also you
have got to ensure, that you are allowed to access the function right
in scope where your assignment stands.
class TMyClass
{
public:
int DoIt (float a, char b, char c)
{ cout << "TMyClass::DoIt" << endl; return
a+b+c; };
int DoMore(float a, char b, char c)
116
{
cout << "TMyClass::DoMore" << endl;
return a-b+c;
};
/* more of TMyClass */
};
Example :
int result1 = pt2Function (12, ’a’, ’b’); // C short way
int result2 = (*pt2Function) (12, ’a’, ’b’); // C
TMyClass instance;
int result3 = (instance.*pt2Member)(12, ’a’, ’b’); // C++
int result4 = (*this.*pt2Member)(12, ’a’, ’b’); // C++ if
this-pointer can be used
void Pass_A_Function_Pointer()
{
cout << endl << "Executing
’Pass_A_Function_Pointer’" << endl;
PassPtr(&DoIt);
}
You can access an object either directly (as has been the
case in all preceding examples), or by using a pointer to that object.
To access a specific element of an object when using a pointer to
the object, you must use the arrow operator: –>. It is formed by
using the minus sign followed by a greater-than sign.
#include<iostream>
using namespace std;
class P_example
{
int num;
public:
void set_num(int val) {Num=val;}”
void show_num(){cout<<num<< “\n”;
};
int main()
{
P_example ob, *p;
return 0;
}
int * bobby;
bobby = new int [5];
int * bobby;
bobby = new (nothrow) int [5];
if (bobby == 0)
{
// error assigning memory. Take measures.
};
121
#include <iostream>
using namespace std;
int main ()
{
int i,n;
int * p;
cout << "How many numbers would you like to
type? ";
cin >> i;
p= new (nothrow) int[i];
if (p == 0)
cout << "Error: memory could not be allocated";
else
{
for (n=0; n<i; n++)
{
cout << "Enter number: ";
cin >> p[n];
}
122
But the user could have entered a value for i so big that our
system could not handle it. For example, when I tried to give a
value of 1 billion to the "How many numbers" question, my system
could not allocate that much memory for the program and I got the
text message we prepared for this case (Error: memory could not
be allocated). Remember that in the case that we tried to allocate
the memory without specifying the nothrow parameter in the new
expression, an exception would be thrown, which if it's not handled
terminates the program.
123
11
VIRTUAL FUNCTION
Unit Structure
11.1 Virtual Base Classes
11.2 Abstract Classes
11.3 Virtual Functions
11.4 Pure Virtual Functions
class base
{
:
:
};
Abstract classes are the classes, which are written just to act
as base classes. Consider the following classes.
class base
{
:
};
class Aclass : public base
{
:
:
};
class Bclass : public base
{
:
};
class Cclass : public base
{
:
:
};
void main()
{
Aclass objA;
Bclass objB;
Cclass objC;
:
:
}
function of the base class can be declared with the keyword virtual.
The program with this change and its output is given below.
class Shape
{
public :
virtual void print()
{
cout << “ I am a Shape “ << endl;
}
};
class Triangle : public Shape
{
public :
void print()
{
cout << “ I am a Triangle “ << endl;
}
};
class Circle : public Shape
{
public :
void print()
{
cout << “ I am a Circle “ << endl;
}
};
void main()
{
Shape S;
Triangle T;
Circle C;
S.print();
T.print();
C.print();
Shape *ptr;
ptr = &S;
ptr -> print();
ptr = &T;
ptr -> print();
ptr = &C;
ptr -> print();
}
126
I am a Shape
I am a Triangle
I am a Circle
I am a Shape
I am a Triangle
I am a Circle
{
Shape S;
Triangle T;
Circle C;
Shape *ptr;
ptr = &T;
ptr -> print();
ptr = &C;
ptr -> print();
}
I am a Triangle
I am a Circle
EXAMPLE:-
// virtual members
#include <iostream.h>
class CPolygon
{
protected:
int width, height;
public:
void set_values (int a, int b)
{
width=a; height=b;
}
virtual int area (void)
{
return (0);
}
};
class CRectangle: public CPolygon
128
{
public:
int area (void)
{
return (width * height);
}
};
int main ()
{
CRectangle rect;
CTriangle trgl;
CPolygon poly;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
ppoly3->set_values (4,5);
130
12
STREAMS AND FILES
Unit Structure
12.1 Input Output With Files
12.2 Methods of Input and Output Classes
12.3 Text mode files
12.4 State flags
12.5 get and put stream pointers
12.6 Binary files
12.8 I/O Manipulators
The techniques for file input and output, i/o, in C++ are
virtually identical to those
introduced in earlier lessons for writing and reading to the standard
output devices, the screen and keyboard. To perform file input and
output the include file fstream must be used.
#include <fstream>
C++ has support both for input and output with files through the
following classes:
Open a file
ofstream file;
file.open ("example.bin", ios::out | ios::app | ios::binary);
member function and has the same parameters as this. This way,
we could also have declared the previous object and conducted the
same opening operation just by writing:
that returns a bool type value indicating true in case that indeed
the object has been correctly associated with an open file or false
otherwise.
Closing a file
2) get()
This form of get extracts a single character from the input
stream, that is, from the standard input, a file or a buffer. It does not
skip white space. It returns type int.
3) get(char &ch)
This form of get also extracts a single character from the
input stream, but it stores the value in the character variable
passed in as an argument.
5) Getline
There are several useful forms of getline.
6) peek()
This method returns the next character from the input
stream, but does not remove it. It is useful to look ahead at what
the next character read will be.
7) putback(char &ch)
This method puts ch onto the input stream. The character in
ch will then be the next character read from the input stream.
8) unget()
This method puts the last read character back into the input
stream.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int blank_count = 0;
int char_count = 0;
int sentence_count = 0;
char ch;
ifstream iFile("c:/lesson12.txt");
if (! iFile)
{
cout << "Error opening input file" << endl;
return -1;
}
while (iFile.get(ch))
{
switch (ch)
{
case ' ':
blank_count++;
break;
case '\n':
case '\t':
break;
case '.':
sentence_count++;
break;
default:
char_count++;
break;
}
135
}
cout << "There are " << blank_count << " blanks" <<
endl;
cout << "There are " << char_count << " characters"
<< endl;
cout << "There are " << sentence_count << "
sentences" << endl;
return 0;
}
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
char ch;
string iFileName;
string oFileName;
cout << "Enter the source file name: ";
cin >> iFileName;
cout << "Enter the destination file name: ";
cin >> oFileName;
ofstream oFile(oFileName.c_str());
ifstream iFile(iFileName.c_str());
//Error checking on file opens omitted for brevity.
while (iFile.get(ch))
{
oFile.put(ch);
}
return 0;
}
Data input from file can also be performed in the same way that we
did with cin:
This last example reads a text file and prints out its content on the
screen. Notice how
137
2) fail() : Returns true in the same cases as bad() plus in case that
a format error happens, as trying to read an integer number and
an alphabetical character is received.
3) eof() : Returns true if a file opened for reading has reached the
end.
The values of both stream pointers get and put are counted
in different ways for text files than for binary files, since in text mode
files some modifications to the appearance of some special
characters can occur. For that reason it is advisable to use only the
first prototype of seekg and seekp with files opened in text mode
and always use nonmodified values returned by tellg or tellp. With
binary files, you can freely use all the implementations for these
functions. They should not have any unexpected behavior.
int main ()
{
long l,m;
ifstream file (filename, ios::in|ios::binary);
l = file.tellg();
139
int main ()
{
char * buffer;
long size;
ifstream file (filename,
ios::in|ios::binary|ios::ate);
size = file.tellg();
file.seekg (0, ios::beg);
buffer = new char [size];
140
When the file is closed: before closing a file all buffers that have
not yet been completely written or read are synchronized.
When the buffer is full: Buffers have a certain size. When the
buffer is full it is automatically synchronized.
Manipulator Use
Boolalpha Causes bool variables to be output as true or
false.
Noboolalhpa Causes bool variables to be displayed as 0 or 1
(default)
Dec (default) Specifies that integers are displayed in base 10.
Hex Specifies that integers are displayed in
hexadecimal.
Oct Specified that integers are displayed in octal.
Left Causes text to be left justified in the output field.
Right Causes text to be right justified in the output field.
Internal Causes the sign of a number to be left justified
and the value to be right justified.
Noshowbase Turns off displaying a prefix indicating the base of
(default) a number.
Showbase Turns on displaying a prefix indicating the base of
a number.
Noshowpoint Displays decimal point only if a fractional part
(default) exists.
Showpoint Displays decimal point always.
noshowpos No "+" prefixing a positive number.
(default)
Showpos Displays a "+" prefixing a positive number.
Skipws (default) Causes white space (blanks, tabs, newlines) to be
skipped by the input operator, >>.
Noskipws White space not skipped by the extraction
operator, >>.
Fixed (default) Causes floating point numbers to be displayed in
fixed notation.
142
Setting Precision
setprecision(n) - sets the display of floating point numbers at
precision n. This does not
effect the way floating point numbers are handled during
calculations in your program.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int intValue = 15;
cout << "Integer Number" << endl;
cout << "Default: " << intValue << endl;
cout << "Octal: " << oct << intValue << endl;
143
cout << "Hex: " << hex << intValue << endl;
cout << "Turning showbase on" << showbase <<
endl;
cout << "Dec: " << dec << intValue << endl;
cout << "Octal: " << oct << intValue << endl;
cout << "Hex: " << hex << intValue << endl;
cout << "Turning showbase off" << noshowbase <<
endl;
cout << endl;
double doubleVal = 12.345678;
cout << "Floating Point Number" << endl;
cout << "Default: " << doubleVal << endl;
cout << setprecision(10);
cout << "Precision of 10: " << doubleVal << endl;
cout << scientific << "Scientific Notation: " <<
doubleVal << endl;
cout << uppercase;
cout << "Uppercase: " << doubleVal << endl;
cout << endl;
bool theBool = true;
cout << "Boolean" << endl;
cout << "Default: " << theBool << endl;
cout << boolalpha << "BoolAlpha set: " << theBool <<
endl;
cout << endl;
string myName = "John";
cout << "Strings" << endl;
cout << "Default: " << myName << endl;
cout << setw(35) << right << "With setw(35) and right:
"<< myName << endl;
cout.width(20);
cout << "With width(20): " << myName << endl;
cout << endl;
return 0;
}
144
13
TEMPLATES
Unit Structure :
13.1 Function templates
13.2 Class templates
The format for declaring function templates with type parameters is:
template <class identifier> function_declaration;
template <typename identifier> function_declaration;
To use this function template we use the following format for the
function call:
function_name <type> (parameters);
// function template
#include <iostream>
using namespace std;
int main ()
{
int i=5, j=6, k;
long l=10, m=5, n;
k=GetMax<int>(i,j);
n=GetMax<long>(l,m);
cout << k << endl;
cout << n << endl;
return 0;
}
T result;
Since both i and j are of type int, and the compiler can
automatically find out that the template parameter can only be int.
This implicit method produces exactly the same result:
// function template II
#include <iostream>
using namespace std;
The output is :
6
10
Notice how in this case, we called our function template
GetMax() without explicitly specifying the type between angle-
brackets <>. The compiler automatically determines what type is
needed on each call.
int i;
long l;
k = GetMax (i,l);
int i,j;
long l;
i = GetMin<int,long> (j,l);
or simply:
i = GetMin (j,l);
148
even though j and l have different types, since the compiler can
determine the appropriate instantiation anyway.
this same class would also be used to create an object to store any
other type:
// class templates
#include <iostream>
using namespace std;
a=first;
b=second;
}
T getmax ();
};
int main ()
{
mypair <int> myobject (100, 75);
cout << myobject.getmax();
return 0;
}
150
14
EXCEPTIONS
Unit Structure:
14.1 Exceptions
14.2 Exception specifications
14.1 EXCEPTIONS
int main ()
{
try
{
throw 20;
}
catch (int e)
{
cout << "An exception occurred. Exception Nr.
" << e << endl;
}
return 0;
}
151
The output is :
An exception occurred. Exception Nr. 20
throw 20;
try
{
// code here
}
catch (int param)
{
cout << "int exception";
}
catch (char param)
{
cout << "char exception";
}
catch (...)
{
cout << "default exception";
}
152
catch (...)
{
cout << "Exception occurred";
}
Example
// standard exceptions
#include <iostream>
#include <exception>
using namespace std;
int main ()
{
try
{
throw myex;
}
catch (exception& e)
{
cout << e.what() << endl;
}
return 0;
}
The output is :
My exception happened.
Exception Description
For example, if we use the operator new and the memory cannot
be allocated, an exception of type bad_alloc is thrown:
try
{
int * myarray= new int[1000];
}
catch (bad_alloc&)
{
cout << "Error allocating memory." << endl;
}
#include <exception>
using namespace std;
155
int main ()
{
try
{
int* myarray= new int[1000];
}
catch (exception& e)
{
cout << "Standard exception: " << e.what() <<
endl;
}
return 0;
}
156
15
Unit Structure :
15.1 Introduction
15.2 Standard Templates
15.3 Stacks
15.4 Older Stacks
15.5 Queues
15.6 Older Queues
15.7 Lists
15.8 Vectors
15.9 Iterators and Containers
15.10 Algorithms
15.1 INTRODUCTION
Library Description
<vector> A dynamic array [ $Vectors ]
<list> A randomly changing sequence of items
A sequence of items with pop and push
<stack>
at one end only
A Sequence of items with pop and
<queue>
push at opposite ends
Double Ended Queue with pop and
<deque>
push at both ends
A subset of of a fixed and small set of
<bitset>
items
<set> An unordered collection of items
An collection of pairs of items indexed
<map>
by the first one
15.3 STACKS
#include <stack>
Example :
15.5 QUEUES
#include <queue>
queue<T> q;
Example of putting three items into a queue and then taking them
off the queue.
#include <iostream.h>
#include <list>
#include <queue>
int main()
{
160
queue<char> q;
q.push('a');
q.push('b');
q.push('c');
cout << q.front();
q.pop();
cout << q.front();
q.pop();
cout << q.front();
q.pop();
}
Example on putting three items into a queue and then taking them
off the queue.
#include <iostream.h>
#include <list>
#include <queue>
int main()
{
queue< list <char> >q;
q.push('a');
q.push('b');
q.push('c');
cout << q.front();
q.pop();
cout << q.front();
q.pop();
cout << q.front();
q.pop();
}
. . . . . . . . . ( end of section Queues) <<Contents | End>>
15.7 LISTS
#include <list>
Suppose that T is any type or class - say an int, a float, a struct, or
a class, then
l.empty()
l.size()
15.8 VECTORS
#include <vector>
Containers:
Iterators:
Items in Containers are referred to be special objects called:
iterators. They are generalization of C's pointers. With an iterator
class Iter you can process each item in a vector or a list by similar
code:
If you change your choice from a vector to a list then the code is
almost identical. This makes your code easier to modify.
#include <iostream.h>
#include <list>
void print(list <char> );// elsewhere
main()
{
list <char> l;
list <char>::iterator p;
l.push_back('o');
l.push_back('a');
l.push_back('t');
p=l.begin();
166
Ranges:
A pair of iterators describes a range of items in their container.
The items in the range start with the first iterator in the pair. The
range has all the following items up to just before the item referred
to by the last iterator of the pair.
Suppose that first and last form a range and it is an iterator then:
for( it=first; it != last; it++)
15.10 ALGORITHMS
These always form a range of all the items in v from the front up to
and including the back. You can sort a vector v simply by writing:
sort(c.begin(), c.end());
#include <iostream.h>
#include <vector>
#include <algorithm>
void print( vector<int> ) ;//utility function outputs a $container
int main()
{
vector<int> a;
// Place 9,8,7,6,5,4,3,2,1 into the vector
for(int i=0; i<9;++i)
a.push_back(9-i);// put new element after all the others
print(a); // elements of a are (9,8,7,6,5,4,3,2,1)
sort( a.begin(), a.end() ); //in the STL <algorithm> library
print(a); // elements are nor in order.
}
void print( vector<int> a)
{
for(vector<int>::iterator ai=a.begin(); ai!=a.end(); ++ai)
cout << *ai << " ";
cout << endl;
cout << "----------------"<<endl;
}
. . . . . . . . . ( end of section Iterators) <<Contents | End>>
Summary
Templat Commo
push/pop items Extras
e n
empty(),
stack pop(),push(T) top() -
size()
empty(), front(),back(
queue pop(),push(T) -
size() )
Note:
You must always #include headers if you use the words: vector,
list,string,queue, or stack in your program or in a header file.
If the standard <list> and <vector> is not found then you are using
an older C++ compiler.
before including the list or vector rather in the reverse order! Older
string library appear to define some special versions of vector and
list operators and the older compilers can not make up its mind
which to use.
169
EXERCISE
Exercise : 1
1. It has been said that C++ sits at the center of the modern
programming universe. Explain this statement.
5. What is a header?
7. What is a namespace?
8. What is a variable?
11. Show the general form of the if statement. Show the general
form of the for loop.
14. A year on Jupiter (the time it takes for Jupiter to make one full
circuit around the Sun) takes about 12 Earth years. Write a
program that converts Jovian years to Earth years. Have the user
specify the number of Jovian years. Allow fractional years.
16. Write a program that averages the absolute value of five values
entered by the user. Display the result.
Exercise: 2
10. Explain the difference between the prefix and postfix forms of
the increment operator.
a. && b. ## c. || d. $$ e. !
14. Write a program that finds all of the prime numbers between 1
and 100.
Exercise: 3
1. Write a program that reads characters from the keyboard until a
$ is typed. Have the program count the number of periods. Report
the total at the end of the program.
2. In the switch, can the code sequence from one case run into the
next? Explain.
171
4. Show the for statement for a loop that counts from 1000 to 0
by –2.
7. The increment expression in a for loop need not always alter the
loop control variable by a fixed amount. Instead, the loop control
variable can change in any arbitrary way. Using this concept, write
a program that uses a for loop to generate and display the
progression 1, 2, 4, 8, 16, 32, and so on.
Exercise: 4
5. Write a program that prompts the user for two strings and then
compares the strings for
equality, but ignores case differences. Thus, “ok” and “OK” will
compare as equal.
6. When using strcat( ), how large must the recipient array be?
8. Show how to initialize an int array called nums with the values 5,
66, and 88.
Exercise : 5
10. Write a recursive function that prints the numbers 1 through 10.
Demonstrate its use in a program.
Exercise : 6
4. Create a void function called round( ) that rounds the value of its
double argument to the nearest whole value. Have round( ) use a
reference parameter and return the rounded result in this
parameter. You can assume that all values to be rounded are
positive. Demonstrate round( ) in a program. To solve this problem,
you will need to use the modf( ) standard library function, which is
shown here:
The modf( ) function decomposes num into its integer and fractional
parts. It returns the fractional portion and places the integer part in
the variable pointed to by i. It requires the header <cmath>.
print("test", 18); output will indent 18 spaces and then will display
the string “test”. Have the indentation parameter default to 0 so that
when it is not present, no indentation occurs.
Exercise : 7
Exercise : 8
4. Show how to declare a class called Test that contains two private
int variables called count and max.
class sample
{int i;
public:
sample int x {i = x;}
//..
};
8. Create a class called Triangle that stores the length of the base
and height of a right triangle in two private instance variables.
Include a constructor that sets these values. Define two functions.
The first is hypot( ), which returns the length of the hypotenuse. The
second is area( ), which returns the area of the triangle.
Exercise: 9
10. For the Set class developed in Project 9-1, define < and > so
that they determine if one set is a subset or a superset of another
set. Have < return true if the left set is a subset of the set on the
right, and false otherwise. Have > return true if the left set is a
superset of the set on the right, and false otherwise.
11. For the Set class, define the & so that it yields the intersection
of two sets.
12. On your own, try adding other Set operators. For example, try
defining | so that it yields the symmetric difference between two
sets. The symmetric difference consists of those elements that the
two sets do not have in common.
Exercise: 10
11. Explain how the pure virtual function helps implement the “one
interface, multiple methods” aspect of polymorphism.
Exercise : 11
10. When the end of the file is reached, the stream variable will
evaluate as false. True or false?
12. Write a program that copies a file. Allow the user to specify the
name of the input and output file on the command line. Make sure
that your program can copy both text and binary files.
178
13. Write a program that merges two text files. Have the user
specify the names of the two files on the command line in the order
they should appear in the output file. Also, have the user specify
the name of the output file. Thus, if the program is called merge,
then the following command line will merge the files MyFile1.txt and
MyFile2.txt into Target.txt: merge MyFile1.txt MyFile2.txt Target.txt
14. Show how the seekg( ) statement will seek to the 300th byte in
a stream called MyStrm.
Exercise : 12
15. On your own, try putting the Queue class from Project 12-1 in
its own namespace called QueueCode, and into its own file called
Queue.cpp. Then rework the main( ) function so that it uses a using
statement to bring QueueCode into view.