1041 File
1041 File
Lesson I
INTRODUCTION
1.0 Aim and objectives
1.1 Introduction
1.2 Key concepts of Object Oriented Programming
1.3 Advantages of Object Oriented Programming
1.4 Object Oriented Languages
1.5 Input and Output in C++ Program
1.6 Structure of C++ Program
1.7 Tokens and Expression
1.8 Sum up
1.9 References
This lesson concentrates on the key concepts, its advantages, input and
output operations and the basic data types of Object Oriented Programming.
After reading this lesson one should be able to know about all the basic things
its input and output statements and its declarations.
1.1 Introduction
1
Encapsulation data abstraction inheritance polymorphism
delegation genericity
Objects
Object are primary runtime entities. They may stand for a thing that has
specific applications for e.g. a spot, a person, or any data item related to a
program.
Class
A class is grouping of objects having identical properties, common
behavior and shared relationship. A class is the accomplishment of abstract
data type. It defines the nature and methods that act on the data structure and
abstract data type respectively. Specimens are also known as objects. The
entire group of data and code of an object can be built as a user defined data
type using class.
Method
An operation required for an object or entity when coded in a class is
called a method. The operations that are required for an object are to be defined
in a class. All objects in a class perform certain common actions or operations.
Each action needs an object that becomes a function of the class that defines it
and is referred to as a method.
Data abstraction
Abstraction directs to the procedure of representing essential features
without including the background details. Classes use the theory of abstraction
and are defined as a list of abstract properties such as size, cost, height and few
functions to operate on these properties. Data abstraction is the procedure of
identifying properties and methods related to a specific entity as applicable to
the application.
Encapsulation
The packing of data and functions into a single component is known as
encapsulation. C++ supports the features of encapsulation using classes. The
data is not accessible by outside functions. Only those functions that are able
to access the data are defined within the class. These functions prepare the
interface between the object’s data and the program. With encapsulation data
hiding can be accomplished. Data hiding is an important feature. By data
hiding an object can be used by the user without knowing how it works
internally.
Inheritance
Inheritance is the method by which objects of one class get the properties
of objects of another class. In oop inheritance provides the thought of
reusability. The programmer can add new properties to the existing class
without changing it. This can be achieved by deriving a new class from the
existing one. The new class will posses features of both the classes. The actual
power of inheritance is it permits the programmer
2
to reuse a class that is close to what he wants, and to tailor the class in such a
manner that it does not bring any unwanted incidental result into the rest of
the class.
Polymorphism
Polymorphism allows the same function to act differently in different
classes. It is an important feature of oop concept and has the ability to take
more than one form. Polymorphism accomplishes an important part in allowing
objects of different classes to share the same external interface. It is possible to
code a non specific interface to a set of associated actions.
Line
Display()
3
Dotted object single object dash object
Display(dotted) display(single) display(dash)
Dynamic binding
Binding means connecting one program to another program that is to be
executed in reply to the call. Dynamic binding is known as later binding. The
code present in the specified program is unknown till it is executed. It is
analogous to inheritance and polymorphism.
Message passing
OOP includes objects which communicate with each other. Programming
with these objects should be followed in steps shown below:
(1) declaring classes that define objects and their actions
(2) declaring objects from classes
(3) implementing relation between objects
Object . display (argument);
object
communication
operator
message data
Data is transferred from one object to another. A message for an object is
the demand for implementation of the process. Message passing contains
indicating the name of the object, function and required data elements. Objects
can be created, released, and interacted with each other. An object is workable,
as long as it is active. In oop there is a panorama of independent objects that
communicate with each other by swapping messages. Objects invoke member
functions. They also negate if the calling object is not a member of the same
class. Thus a message is a solicitation to an object to call one of its member
functions. A message contains name of the member function and parameters of
the function. Execution of member function is just a response generated due to
receipt of a message. It is possible when the function and the object are of the
same class.
Reusability
Object oriented technology allows reusability of the classes by extending
them to other classes using inheritance. Once a class is defined, the other
programmer can also use it in their programs and add new features to the
derived classes. Once verified the qualities of base classes need not be
redefined. Thus reusability saves time.
Delegation
4
In oop, two classes can be joined either by - inheritance or delegation,
which provide reusability of the class.
In heritance, one class can be derived from other class and relationship
between them is known as kind of relationship. E.g. If class y is derived from
class x, then class y is known as kind of x.
When object of one class is used as data member in other class, such
composition of objects is known as delegation.
Genericity
The software components of a program have more than one version
depending on the data types of arguments. This feature allows declaration of
variables without specifying exact data type. The compiler identifies the data
type at runtime. The programmer can create a function that can be used for
any type of data. The template feature on C++ allows generic programming.
There are many languages which support oop. Following object oriented
languages are widely accepted by the programmer.
• C++
• Smalltalk
• Charm++
• Java
5
Smalltalk : is purely an oop. C++ makes few compromises to ensure quick
performance and small code size. Smalltalk uses runtime binding. Smalltalk
programs are considered to be faster than C++ and needs longer time to learn.
Smalltalk programs are written using Smalltalk browser. Smalltalk uses
dynamic objects and memory is allocated from free store. It also provides
automatic garbage collection and memory is released when object is no longer
in use.
Comment Lines
For single line comments double slash (//) is used. For multi line
comments /* */ is used.
Output operator
The output statement in C++ is
cout << “sample program”;
The string within the quotation marks is displayed on the screen. “cout”
is an predefined object that represents the standard output stream in C++. The
“<<” operator is called the insertion or put to operator. This operator inserts or
sends the contents of the variable on its right to the object on its left.
The iostream.h file
The #include directive uses iostream header file as
#include<iostream.h>
6
This iostream.h contains declarations for the identifier cout and “<<” operator.
This header file should be included at the beginning of all programs that use
input/output statements.
Input operator
The input operator or statements used is
cin>> n1;
This is an input statement, cin is a predefined object that corresponds to
the standard input stream. “>>” operator is an extraction or get from operator.
It extracts or takes the value from the keyboard and assigns it to the variable
on its right.
Cascading of I/O operators
The insertion operator or extraction operator, when it repeatedly appears
in a statement it is called cascading.
E.g. 1 sum = 10;
cout << “sum = “ << sum;
Here the first “sum” will appear on the screen and then the value for the
variable sum is appeared on the screen as
sum = 10;
E.g. 2 cin>>num1>>num2
Here the operation starts from left to right. So the value of num1 is inputted
first then the value of num2 is inputted.
Include function
Class declarations
7
{
cout << “welcome”;
}
Example 2
// input a number and display it
include<iostream.h>
main()
{
int a,b;
cin>>a>>b;
cout << a<<b;
}
Tokens
The smallest individual unit in a program is called tokens. C++ has the
following tokens. Keywords, identifiers, constants, strings and operators.
Keywords
They are reserved identifiers and cannot be used as names for the
program variables or other user defined program elements.
Identifiers
These refer to the names of variables, functions, arrays, classes etc.,
created by the programmer.
Rules for naming the identifier are as follows.
• Only the alphabet characters, digits and underscores are allowed.
• The name cannot start with a digit.
• Uppercase and lowercase letters are distinct.
• A keyword cannot be used as a variable name.
• C++ does not have any limit in the length of naming an identifier.
1.8 Sum up
After reading this lesson one will be familiar with the introduction,
concepts and advantages of oop. This lesson deals with the languages of oops
its input functions and tokens and its structure.
1.9 References
8
1. Ashok N Kamthane, “Object Oriented Programming with ANSI and
TURBO C & C++”, Pearson education publication 2003.
2. E. Balagurusamy, “Object Oriented Programming with C++”, Tata Mc Graw
Hill publication 1998.
LESSON II
DATA TYPES
2.0 Aim and objectives
2.1 Basic data types
2.2 User defined data types
2.3 Enumerated data types
2.4 Derived data types
2.5 Symbolic Constants
2.6 Declaration of Variables
2.7 Operators and in C++
2.8 Sum up
2.9 References
Basic data types of C++ are built-in types and are as follows:
Integer type
Integer are whole numbers. They are classified into three types they are
short int, long int and int with both signed and unsigned form.
Floating type
9
These are real numbers which is of two types float and double. Long
double can also be used for double precision.
Character type
A single character can be defined as a char type data. Characters are
usually stored in 8 bits(one byte) of memory.
Void
The void data type is used to specify the return type of a function when it
is not returning any value and to indicate an empty argument list to a function.
E.g. void sample(void);
10
Structures are collection of data items of different types. It is a
convenient tool for handling a group of logically related data items. Once the
structure has been defined we can create variables of that type using
declaration that are similar to the built-in data type.
Class is a user defined data type which is similar to structure. Since
class is a specially introduced data type in C++ most of the programmers tend
to use the structures for holding only data, and classes to hold both the data
and functions.
Union follow the same syntax as structures. The difference in union and
structure is in terms of storage. In structures, each member has its own
storage location whereas all the members of a union use the same location.
Union can contain members of different data types, but it can handle only one
member at a time.
11
Array is a collection of related data item that share a common name. The
general syntax is
Type variable_name[size];
Type specifies the type of element that will be contained in the array. E.g.
int, float or char. Size indicates the maximum number of elements that will be
stored inside the array.
E.g. int a[10];
Character array tells the number of characters, but here normally the size is
initialized as one size greater than the total string.
E.g. char s[6] = “hello”;
Two dimensional array contain a table of values consisting of rows and
columns.
E.g. int a[3][3];
syntax
Type array-name[row-size][col-size];
Type array-name[s1][s2][s3]……[sm];
12
Constants are just like variables except that their values cannot be
changed. There are two ways for creating symbolic constants. They are
1. Using the qualifier const e.g. const int a = 10;
2. By using enum e.g. enum{x,y,z};
By default this defines x, y, z as integer constants with values 0, 1 and 2
respectively. This is equivalent to
const x = 0; const y = 1; const z = 2;
Values can also be defined explicitly as
enum{ x=10; y=20; z=30};
2.6 Declaration of variables
C++ allows the declaration of a variable anywhere in the scope, i.e. the
variable can be declared just before it is used. This makes the program easier to
write, reduces the error and also easier to understand.
Example
main()
{
float x;
float sum = 0;
for(int i = 0; i<5; i++)
{
cin>>x;
sum = sum + x;
}
float avg;
avg = sum/5;
cout<<avg;
}
Automatic initialization of variables
C++ permits initialization of the variable at runtime. This is referenced to as
dynamic initialization.
E.g. float area = 3.14 * rad * rad;
13
C++ has a rich set of operators. All the operators used in C is also valid
in C++. Already we have discussed about the two special operators insertion
operator << and extraction operator >>. Other operators are
:: scope resolution operator
::* pointer to member declaration
->* pointer to member operator
.* also pointer to member operator
delete memory release operator
endl linefeed operator
new memory allocation operator
setw field width operator
Scope Resolution Operator
In C the global version of a variable cannot be accessed from within the
inner block. C++ solves this problem by introducing a new operator :: called the
scope resolution operator.
E.g.
#include<iostream.h>
int m = 10; //global variable
main()
{
int m = 20 // redeclared local to main function
{
k = m;
int m = 30; //local to inner block
cout<<”inner block”;
cout<<k;
cout<<m;
cout << ::m;
}
cout<<”outer block”;
14
cout<<m;
cout<<::m;
}
output
inner block outer block
20 20
30 10
10
Syntax
pointer_variable = new data-type;
15
Pointer-variable – holds the address of the memory space allocated.
E.g. int *p;
p = new int; or int *p = new int;
Delete
When a data object is not needed then it has to release the memory
space for reuse.
2.7 Sum up
2.8 References
16
Lesson III
CONTROL STRUCTURES
3.0 Aim and objectives
3.1 Introduction
3.2 Selection Structure
3.3 Switch Statements
3.4 Looping Statements
3.5 Sum up
3.6 References
This lesson says about the different control structures in C++. It deals
with decision making statements, looping and jumping. It also deals with switch
statements.
17
3.1 Introduction
Action 1
Action 2
Action 3
Exit
Action 1 Action 2
Exit
Action 3
18
Loop structure
Loop
false
Action 2
exit
It is important to understand that all program processing can be coded
by using only these three logic structure. The approach of using one or more of
these basic control structures in programming is known as structured
programming.
The if statement
The if statement is implemented in two forms.
Simple if statement
If…else statement
Syntax for simple if syntax for if else
3. 3 Switch statement
This is a multiple branching statement based on a condition, the control
is transferred to one of the many possible points.
syntax
19
switch(expression)
{
case 1:
{
action1;}
case 2:
{
action2; }
.
.
case n:
{
action n; }
default:
{
default statements; }
}
do while statement
This is a exit controlled loop. Based on a condition the control is
transferred back to a particular point in the program.
Syntax
do
{
action1;
}while(condition is true);
20
The while statement
This is an entry controlled loop.
Syntax
while(condition is true)
{
action1;
}
3.5 Sum up
3.6 References
21
LESSON IV
FUNCTIONS
4.0 Aim and objectives
4.1 Introduction
4.2 Function prototyping
4.3 Call by reference
4.4 Inline function
4.5 Function overloading
4.6 Sum Up
22
4.7 References
This lesson concentrates on the functions used in C++. It tells about the
inline function, the main function and also deals with one of the important
concept called function overloading. After reading this lesson one should be
familiar in using C++ functions
4.1 Introduction
The use of functions is to reduce the size of the program by calling and
using them at different places in the program. Functions are building blocks of
the program.
The Main function
In C++, the main() function returns a value of type int. C++ therefore
explicitly defines main() as matching one of the following prototypes.
E.g. int main()
int main(int argc, char *argv[]);
The functions that have a return value should use the return statement for
termination.
The function is as follows.
int main()
{
.
.
return(0);
}
As the return type of functions is int by default, the keyword int is optional.
23
In the function declaration, the name of the arguments are dummy
variables and so they are optional. The above example can also be written as
float test(int, float, float);
In the function definition the names are required because the arguments must
be referenced inside the function.
The above examples definition is as follows
float test(int a, float b, float c)
{
float v = a*b*c;
.
.
.
}
Example
swap(&m, &n);
.
.
.
.
void swap(int *a, int *b)
24
{
int t;
t = *a;
*a = *b;
*b = t;
}
Here swap(&m, &n) is the calling function and void swap(int *a, int *b) is the
called function.
Return by reference
A function can also return a reference
Example
int sample(int &x, int &y)
if(x>y)
return x;
else
return y;
}
The objective of using function is to save memory space but the time
taken in executing the function is more. (i.e.) When a function is called the time
taken to jump to the function, to save in the registers, to push the arguments
into the stack and return to the calling function is more. So to solve the above
problem C++ uses a new features called inline function.
An inline function is a function that is expanded in line. (i.e.) the
compiler replaces the function call with the corresponding function code.
Syntax
inline function-header
{
function body
}
25
Example
inline double cube(float a)
{
return a*a*a;
}
The above example can be invoked with the following statements
c = cube(3.0);
All the inline functions must be defined before they are called. The inline
keyword is not a command but a request so sometimes it may be ignored by the
compiler.
Default arguments
C++ allows us to call a function without specifying all its arguments. The
function assigns a default value to the parameter which does not have a
matching arguments in the function. Default values are specified when the
function is declared.
E.g. float simpint(float principal, int period, float rate = 0.15);
The function call for the above function is as follows.
value = simpint(5000,7);
One argument is missing so the default value is taken.
Note : The default value is added from right to left. No middle argument list can
be default.
E.g. float vol(int i, int j = 10, int k = 15); //valid
float vol(int i, int j = 10, int k); //invalid
Const arguments
In C++ a function can be declared as const
E.g. int strlen(const char *p);
This tells the compiler that the function should not modify the argument.
This type of declaration is significant only we pass arguments by reference or
pointers.
26
Example
Functions
int add(int a, int b)
int add(int a, int b, int c)
Function call
add(10,5);
add(5,10,15);
A function call matches the function having the same number and type of
arguments and then executes the function.
Example program
#include<iostream.h>
overload volume; //needed on early system
int volume(int); //prototype declarations
double volume(double, int); //for overloading volume()
long volume(long,int,int);
main()
{
cout<<volume(10)<<”\n”;
cout<<volume(2.5,8)<<”\n”;
cout<<volume(100,75,15);
}
//function definitions
int volume(int s) //cube
{
return (s*s*s);
}
double volume(double r, int h) //cylinder
{
return(3.14519 * r* r*h);
}
long volume(long l, int b, int h) //rectangular box
{
27
return (l*b*h);
}
o/p 1000
157.2595
112500
4.6 Sum Up
After reading this lesson one should be able to know about functions, inline
functions function prototyping and one important concept called function
overloading.
One should be able to program in function overloading with the same name but
different set of parameters and data types.
4.7 References
28
UNIT II
Lesson V
29
CLASSES AND OBJECTS
5.0 Aim and objectives
5.1 Introduction
5.2 Classes and objects
5.3 Creating objects
5.4 Defining member functions
5.5 Static member functions
5.6 Array of objects
5.7 Objects as function arguments
5.8 Sum up
5.9 References
The objective of this lesson is to deal with the classes and objects in
which C++ plays a major role. Here the discussion about declaring a object,
member functions and array of objects is made. One would be familiar with all
the above after reading this lesson.
5.1 Introduction
A class is a way to bind the data and its associated function together. It
allows the data and functions to be hidden if necessary from external use.
30
function declarations;
};
The body of a class is enclosed within braces and terminated by a
semicolon. The class contains declaration of variables and functions. These
variables and functions are collectively called members. The members are
grouped under two sections namely private and public. The private and public
are access specifiers.
The members that have been declared as private can be accessed only
from within the class. Public members can be accessed from outside the class
also. By default the members of a class are private. The variables declared
inside the class are known as data members and the functions are known as
member functions. The binding of data and functions together into a single
class-type variable is called encapsulation.
Data hiding is the important key feature of object oriented programming.
If the access specifier is missing then by default it is considered as private, such
as class is completely hidden from the outside world (other classes).
Private area
no entry to data
private area
X functions
Public area
data
Entry allowed to
functions
public area
31
{
cout<<”enter the number :”<<”\n”;
cin>>studno;
cout<<”enter the name :”<<”\n”;
cin>>studname;
}
void putdata()
{
cout<<”student number is” <<studno;
cout<<”student name is” <<studname;
}
};
main()
{
student s1;
s1.getdata();
s1.putdata();
}
Once a class has been declared, we can create variables of that type by
using the class of the class name.
Example student s1;
The above statement creates a variable s1 of type student. The class variable is
known as objects. Thus s1 is an object of the class student. It is also possible to
create more than one object for the same class.
Example student s1, s2;
Accessing class members
To access the class members the object is used with the dot operator.
Example s1.getdata();
The above invokes the member function getdata() which is present inside the
class student.
32
5.4 Defining member functions
33
};
34
The array variable a[] can be used in the member like other variables. Any
operations can be performed on them.
35
cout<<” count : ”;
cout<<count<<”\n”;
}
};
int item :: count;
main()
{
item a,b,c;
a.getcount();
b.getcount();
c.getcount();
a.getcount(100);
b.getcount(200);
c.getcount(300);
cout<<”after reading data”<<”\n”;
a.getcount();
b.getcount();
c.getcount();
}
36
{
code = ++count;
}
void showcode(void)
{
cout<<”object number :”<<code<<”\n”;
}
static void showcount(void) //static member
function
{
cout<<”count : “<<count<<”\n”;
};
int test :: count;
main()
{
test t1,t2;
t1.setcode();
t2.setcode();
test :: showcount();
test t3;
t3.setcode();
test :: showcount();
t1.showcode();
t2.showcode();
t3.showcode();
}
We can have array of variables that are of the type class. Such variables
are called array of objects.
Example
class emp
{
37
char name[20];
float age;
public:
void getdata(void);
void putdata(void);
Here employee is a user defined data type and can be used to create objects
that relate to different categories of the employees.
E.g. emp manager[3];
emp worker[20];
The array manager contains three objects likewise worker contain 20 objects.
The array can be accessed using the dot operator. Individual element can be
accessed as follows.
manager[i].putdata();
The above statement will display the data of the ith element of the array
manager.
The array of objects is stored inside the memory in the same way as a
multidimensional array. Here the space for data items of the objects is created.
Member functions are stored separately and will be used by all the objects.
Example
#include<iostream.h>
class emp
{
char name[20];
float age;
public:
void getdata(void);
void putdata(void);
};
void emp::getdata(void)
{
cout<<”enter name and age”;
cin>>name;
38
cin>>age;
}
void emp::putdata(void)
{
cout<<”name :”<<name<<”\n”;
cout<<”age:”<<age<<”\n”;
}
const int size = 3;
main()
{
emp manager[size];
for(int i = 0; i<size;i++)
{
cout << i+1;
manager[i].getdata();
}
for(i=0;i<size;i++)
{
cout<<i+1;
manager[i].putdata();
}
}
39
Example
#include<iostream.h>
class time
{
int hours;
int min;
public:
void gettime(int h, int m)
{
hours = h; min = m;
}
void puttime(void)
{
cout<<hours;
cout<<min;
}
void sum(time,time);
};
void time : : sum(time t1, time t2)
{
min = t1.min + t2.min;
hours = min/60;
min = min%60;
hours = hours + t1.hours + t2.hours
}
main()
{
time t1,t2,t3;
t1.gettime(2,45);
t2.gettime(3,30);
t3.sum(t1,t2);
cout<<“t1 : “ ;
40
t1.puttime();
cout<<“t2 : “ ;
t2.puttime();
cout<<“t3 : “ ;
t3.puttime();
}
5.8 Sum up
After reading this lesson one would be able program on classes and objects.
He/she would be able to know about objects in detail, its member functions,
static member variables and functions. One would be able to use array of
objects and program in C++.
5.9 References
41
Lesson VI
FRIEND FUNCTIONS
Normally the private members cannot be accessed from outside the class.
Suppose there is a situation where we would like two classes to share a
particular function for e.g., if there are two classes manager and scientist and if
we would like to use a function income_tax() to operate on the objects of both
the classes then C++ allows the common function to be made friendly with both
42
the classes so that the function can access the private data of these classes.
Such a function need not be a member of any of these classes.
Declaration
To declare the function as a friend of a class is given below.
class ABC
{
…
…
public:
….
….
friend void XYZ(void); //declaration
The function declaration should proceeded by the keyboard friend. The function
definition does not use the keyword friend or the scope operator :: . The
functions that are declared with the keyword friend are known as friend
functions. A friend function although not a member function, has full access
rights to the private members of the class.
• It is not in the scope of the class to which it has been declared as friend.
• Since it is not in the scope of the class, it cannot be called using the
object of that class. It can be invoked like a normal function without the
help of any object.
• Unlike member functions, it cannot access the member names directly
and has to use an object name and dot membership operator with each
member name.
• It can be declared either in the public or the private part of a class
without affecting its meaning.
• Usually it has the objects as arguments
Example
#include<iostream.h>
class sample
{
int a,b;
43
public:
void setvalue()
{
a = 10;
b = 20;
}
friend float mean(sample s);
};
float mean(sample s)
{
return float(s.a+s.b)/2.0;
}
main()
{
sample x;
x.setvalue();
cout<<mean(x);
}
In the above example the class variable a and b are accessed using a dot
operator. The function call mean(x) passes the object x by value to the friend
function.
44
};
class y
{
………..
friend int x :: fun1(); //fun1() of x is friend of y
……….
};
The function fun1() is a member of class x and a friend of class y.
We can also declare all the member functions of one class as the friend
function of another class. In such cases, the class is called friend class.
Example
class z
{
……..
…......
friend class x; //all member functions of x are friend to z.
};
A function can not only receive objects as arguments but also can return
them.
Example
#include<iostream.h>
class complex
{
float x; //real part
float y; // imaginary part
public:
void input(float real, float img)
{
45
x = real; y = img;
}
friend complex sum(complex, complex);
void show(complex);
};
complex sum(complex c1, complex c2)
{
complex c3; //object c3 is created
c3.x = c1.x + c2.x;
6.5 Sum up
After reading this lesson one would be able to program using friend
function. It would be familiar to use member function. As its characteristics
have been discussed one would know the pros and cons of friend function.
46
6.6 References
47
Lesson VII
48
7.0 Aim and objectives
The objectives of this lesson is that one would learn about constructors,
its types and destructor.
7.1 Constructors
49
• An object with a constructor cannot be used as a member of a union.
• They make implicit calls to the operators new and delete when memory
allocation is required.
50
int m,n;
public:
sample(int, int);
void display(void)
{
cout<<m;
cout<<n;
}
};
sample :: sample(int x, int y)
{
m = x;
n = y;
}
main()
{
sample int1(10,20); //implicit call
sample int2 = sample(10,20); //explicit call
cout<<”object1”;
int1.display();
cout<<”object2”;
int2.display();
}
The parameters of a constructor can be of any type except that of the class to
which it belongs.
Example
class A
{
……………..
…………….
public:
51
A(A); //this is not valid
};
A constructor can accept a reference to its own class as a parameter.
class A
{
……………..
…………….
public:
A(&A);
};
This is valid and the constructor is called copy constructor.
52
7.5 Constructor with default arguments
7.7 Destructors
Example
~sample() { }
A destructor never takes any argument nor does it return any value. This
is invoked when the program is exited and is used to clean up the storage that
is no longer accessible. It helps us to release memory space for future use.
Whenever new is used to allocate memory in the constructors, delete is used to
free the memory.
7.8 Sum up
53
7.9 References
Unit III
LESSON VIII
54
8.3 Overloading unary operators
8.4 Overloading binary operators using friend function
8.5 Overloading friend functions
8.6 Type conversion
8.7 Sum up
8.8 References
The objectives of this lesson is that one would learn about special effects
on operators called operator overloading, its rules and its different usages.
Introduction
55
two for binary operators. Member has no arguments for unary operators and
only one for binary operators.
Operator functions are declared in the class as follows
vector operator + (vector); //vector addition
vector operator – (); // unary minus
friend vector operator +(vector , vector); // vector addition
friend vector operator – (vector); //unary minus
vector operator – (vector &a); //subtraction
int operator = = (vector); //comparison
friend int operator = = (vector, vector) //comparison
Here vector is a data type of class.
1. First, create a class that defines the data type that is to be used in the
overloading Operation.
2. Declare the operator function operator op() in the public part of the class.
It may be either a member function or a friend function.
3. Define the operator function to implement the required operations.
56
#include <iostream.h>
class space
{
int x;
int y;
int z;
public :
void getdata(int a,int b,int c);
void display (void);
void operator – (); //overload unary minus
};
57
space s;
s.getdata(10,-20,30);
cout<<”s:”;
s.display();
-s;
cout <<”s:”;
s.display();
}
o/p s: 10 -20 30
s: -10 20 -30
Note: if s1 & s2 are objects then
s2 = -s1 is allowed only if s1 has a return value
The same mechanism which was used for unary operators is used for
binary operators.
Eg : to add 2 complex numbers for x+ij (+operator is used)
#include<iostream.h>
class complex
{
float x;
float y;
public :
complex () { }
complex (float real , float imag)
{
x=real; y=imag;}
58
complex complex :: operator +complex()
{
complex temp;
temp.x= x + c.x;
temp.y = y+c.y;
return (temp);
}
void complex :: display (void)
{
cout<<x<<”+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.display ();
cout<<c2.display ();
cout<<c3.display ();
}
x+c.x, y+c.y since the first object can access the member function directly, x
and y are given. The second function is passed as an argument so it is accessed
using a dot operator.
59
If the above program is rewritten using friend operator function, the
member function declaration within the class should be replaced by the friend
function declaration.
(i.e.) friend complex operator + (complex, complex)
//here 2 objects are sent as arguments
Member functions are invoked using dot operator. Friend function is invoked by
passing objects as argument.
The operator function is
complex operator + (complex a,complex b)
{
return complex ((a.x +b.x),(a.y + b.y));
}
c3 = c1+c2 is equivalent to
c3= operator + (c1,c2);
Comparing member function with friend function
If a binary operator is overloaded to perform its operation on 2 objects
say c=a+b then either member function or friend function can be used. But if
one operand is an object and other is any built in data type say c = a+2, using
member function this will work. But if it is c= 2 + a then the member function
will not work because left hand operand is responsible for invoking member
function. So it should be an object. This problem is resolved if the function is a
friend function because both the operands are passed as argument to the friend
function. so it can be c=a+2 or c=2+a.
Manipulation of strings using operators
In C++ operators can be overloaded to manipulate string directly. Strings
are defined as class objects, with a pointer variable to point to the string array
and new to allocate memory for the string.
So char *p; int len will be two data in all string classes
Program for overloading + and <=using strings
60
public :
string (){
len=0;p=0;} //create null string
string (const char *s); // create string from array s
~ string () {delete p;} //destructor
string (const string &s); //copy constructor
61
}
//overloading <= operator
int operator <= ( const string &s, const string &t)
{
int m = strlen (s.p);
62
show(t3);
cout<< “smaller than “;
show ( t4);
}
else
{
show (t4);
cout<<”smaller than”;
show(t3);
}
}
63
float x=3.14159
m=x;
Here x is converted into int in which the fractional part is truncated. This type
of conversion is possible for built in type only.
In user defined data types. For e.g.
v3 = v1 + v2 here v1,v2 and v3 are class type objects.
Here the two objects are added and the result is stored in v3. If v1, v2 and v3
are of the same class type then the above is done. If suppose one operand is an
object and the other is built in type variable, then automatic type conversion is
possible , so we have to design our own conversions.
Three types of situation may occur they are
1. conversion from built – in type to class type
2. conversion from class type to built – in type
3. conversion from one class type to another class type.
64
First converts name1 from char * type to string type and then assigns the
string type values to the object s1.
The statement
s2 = name2;
The above also does the same job by invoking the constructor implicitly.
2. Class to basic type
C++ allows us to define a overloaded casting operator that could be used
to convert a class type data to basic type. The general form of an overloaded
casting operator function is referred to as conversion function.
operator type name()
{
…….
…….
function statements
…….
}
65
Where v1 is an object of type vector.
The casting operator function should satisfy the following conditions.
It must be a class member
It must not specify a return type
It must not have any arguments
3. One class to another class type
There are situations where we would like to convert one class type data
to another class type data. For this either a constructor or a conversion
function is used. This is depended on where we want the type conversion to be
located either in the source class or in the destination class.
E.g.: obj x = obj y;
obj x is an object of class x and obj y is an object of class y. The class y type
data is converted to the class x type data and the converted value is assigned to
the obj x. since the conversion takes place from class y to class x, y is known as
source class and x is known as destination class.
8.7 Sum up
After reading this lesson one would be familiar with operator overloading ,
unary ,binary operators and overloading friend functions. One will be
knowledgeable in type conversion also.
8.8 References
66
LESSON IX
INHERITANCE
The objective of this lesson is to deal with inheritance. There are various
types of inheritance like single, multiple, multilevel, hierarchical and hybrid
inheritance. One would be able to know about virtual classes and abstract
classes.
This C++ classes can be reused in several ways. New classes can be
created, reusing the properties of the existing classes. The mechanism of
deriving a new class from an old one is called inheritance or derivation. The old
class is called base class and the new class is called derived class. A derived
class inherits some or all properties from base class. A class can also inherit
properties from more than one class. A derived class with only one base class is
called single inheritance & one with several base class is called multiple
inheritance. The properties of one class may be inherited by more than one
class. This process is hierarchical inheritance. The mechanism of deriving a
class from another derived class is called multilevel inheritance
A A B A
67
B C B C D
A A
B B C
C D
General form
The colon(:) indicates that the derived class name is derived from base
class name. The visibility mode is optional & if present is either public or
private. The default mode is private. The visibility mode specifies whether the
features of the base class are privately derived or publicly derived.
Eg: class ABC :private XYZ //private derivation
68
{ members of ABC
};
class ABC : public XYZ //public derivation
{members of ABC
};
class ABC :XYZ //private derivation by default
{ members of ABC
};
When a base class is privately inherited by a derived class, public
members of the base class become private members of the derived class. So
public members of the base class can only be accessed by the member function
of the derived class. When the base class is publicly inherited, public members
of the base class become public members of the derived class and they are
accessible to the objects of the derived class. In both the cases, the private
members are not inherited and so the private members of a base class will
never become the members of its derived class.
public :
int b ; //public ; ready for inheritance
void get_ab();
int get_a(void);
void show_a(void);
};
69
public :
void mul(void)
void display(void);
};
void B ::get_ab(void)
{
a=5; b=10;}
int B ::get_a()
{
return a;
}
void B :: show_a()
{
cout<<a;
}
void D ::mul()
{
c = b * get_a();
}
void D ::display()
{
cout <<get_a();
cout<<b;
cout<<c;
}
main()
{
D d;
d.get_ab();
d.mul();
d.show_a();
d.display();
70
d.b=20;
d.mul();
d.display();
}
The derived class D inherits all the public members of B. The private
members of B cannot be inherited by D. The class D will have more members
now than at the time of declaration.
class D
Private section
C
Public section
B
get_ab()
get_a() inherited from b
show_a()
mul ()
display
In the function mul(), although the data member is private in B and
cannot be inherited, objects of D are able to access it through an inherited
member function of B.
private derivation
class B
{
int a;
public :
int b;
void get_ab();
void get_a();
void show_a();
};
class D : private B // private derivation
{
71
int c;
public :
void mul();
void display();
}
Now the public members of the base class become the private members of
derived class. The objects of D cannot have the direct access to the public
member function of B. The statements
d.get_ab()
d.get_a()
d.show_a()
will not work. But these function can be used inside mul() & display() function
like:
void mul()
{
get_ab();
c= b* get_a();
}
class D
private section
C
B
get_ab() inherited from B
get_a()
show_a()
public section
mul()
display()
Making a private member inheritable
Suppose the private data needs to be inherited by a derived class, a third
visibility modifier protected is used. A member declared as protected is
72
accessible by the member function within its class & any class immediately
derived from it . It cannot be accessed by the function outside these classes.
When a protected member is inherited in public mode, it becomes
protected in the derived class also & therefore is accessible by the member
function of the derived class. It is also ready for further inheritance. A protected
member inherited in private mode becomes private in the derived class. It is not
available for further inheritance.
The various function that can access, the private & protected members of
a class are:
A function that is a friend of the class
A member function of a class that is a friend of the class
A member function of a derived class
The friend function & member functions of a friend class can have direct
access to both the private & protected data, but the member function of a
derived class can directly access only the protected data. But they can access
the private data through the member function of the base class.
Multilevel inheritance
73
The class A servers as a base class for the derived class B which in turn
serves as a base class for the derived class c. the class B is known as
intermediate base class. Since it provides a link for inheritance between A & C.
The chain ABC is the inheritance path. A derived class with multilevel
inheritance is
class A {……..}; //base class
class B :public A {…….}; // B derived from class A
class C :public B { …….}; // C derived from class B
This process can be extended to any number of levels .
74
class test : public student
{
protected :
float sub1;
float sub2;
public :
void get _marks(float , float);
void put_marks (void);
};
void test ::get_ marks (float x, float y)
{
sub1 = x;
sub2 = y;
}
void test ::put_marks()
{
cout <<sub1;
cout<<sub2;
}
class result ::public test
{
float total;
public :
void display(void);
};
void result ::display (void)
{
total = sub1 + sub2;
put_numbers();
put_marks();
cout<<total;
75
}
main()
{
result student1;
student1.get_number(1.71);
student1.get_matks(75.0,59.5);
student1.display();
}
Multiple inheritance
A class inheriting the attributes of 2 or more classes. It is like a child
inheriting the physical features of one parent and the intelligence of another
B1 B2 ……………………………….…. Bn
76
Visibility may be either public or private
E.g.:
#include <iostream.h>
class M
{
protected :
int m;
public :
void get_m(int);
};
class N
{
protected :
int n;
public :
void get_n(int);
};
class P :public M, public N
{
public :
void display (void);
};
void M :: get_m(int x)
{
m=x;
}
void N :: get_n(int y)
{
n=y;
}
void P :: display(void)
77
{
cout<<m;
cout<<n;
cout<<m*n;
}
main()
{
Pp
p.get_m(10);
p.get_n(20);
p.display();
}
Hierarchical inheritance
Another application of inheritance is to use it as a support to the
hierarchical design of a program. (i.e.) certain features of one level are shared
by many others below that level.
students
Here all the students can have certain things in common. The base class
includes all the features that are common to the subclasses. A subclass is
constructed by inheriting the properties of the base class. A subclass can serve
as a base class for the lower level classes.
Hybrid Inheritance
The combination of both multilevel and multiple inheritance is called hybrid
inheritance.
78
student
test sports
result
class sports
{
protected :
float score;
public:
void get_score(float);
void put_score(void);
};
E.g. :
#inlcude<iostream.h>
class student
{
protected :
void get_number(int a )
{
79
roll_number = a;
}
void put_number(void)
{
cout<<roll_number;
}
};
class test :public student
{
protected :
float part1,part2;
public :
void get_marks(float x,flaot y)
{
part1 = x;
part2 = y;
}
void put_marks(void)
{
cout<<part1;
cout<<part2;
}
};
class sports
{
protected:
float score;
public:
void get_score (float s)
{
score = s;}
void put_score(void)
80
{
cout<<score;
};
class result :public test, public sports
{
float total;
public :
void display(void);
};
This supports all the three kinds of inheritance they are multilevel,
multiple and hierarchical inheritance.
81
parent 1 parent 2
child
The child class has 2 direct base classes parent1 and parent2 which themselves
have a common base class called grandparent which is an indirect base class.
All the public protected members of grandparent are inherited into child +
parent1 & parent 2. (i.e.) the child will have duplicate sets of the members
inherited from grandparent. But this should be avoided. It can be avoided by
making the common base class (ancestor class) as virtual base class. While
declaring the direct of intermediate base class as
class A //grand parent
{
……
……
};
class B1 : virtual public A // Parent can be used in any order
{
…..
…..
};
82
student
test sports
result
eg:
#inlcude<iostream.h>
class student
{
protected :
int roll_number;
public:
void get_number(int a )
{
roll_number = a;
}
void put_number(void)
{
cout<<roll_number;
83
}
};
class test :virtual public student
{
protected :
float part1,part2;
public :
void get_marks(float x, float y)
{
part1 = x;
part2 = y;
}
void put_marks(void)
{
cout<<part1;
cout<<part2;
}
};
84
{
float total;
public :
void display(void);
};
void result:: display (void)
{
total = part1 + part2 + score;
put_number();
put_marks();
put_score();
cout<<total;
}
main()
{
result student1;
student1.get_number(1234):
student1.get_marks(27.5,33.0);
student1.get_score(6.0);
student1.display();
}
85
class gamma
{
alpha a; //a is an object of class alpha
beta b; // b is an object of class beta
}
All the objects of gamma will contains objects a and b. It is called as
containership or nesting. An independent object is created by its constructor
which is declared with arguments. A nested object is created in a 2 stages.
The member objects are created using their respective constructors.
The ordinary members are created. (i.e.) constructors of all the member objects
should be called before its own constructor body is executed by using an
initialization list in the constructor of the nested class.
E.g.: class gamma
{
…….
alpha a;
beta b;
public :
gamma (arglist): a(arglist1),b(arglist2)
{
constructor body
}
};
arglist- is the list or arguments that is to be supplied when a gamma object is
defined.
arglist1 – is the argument list for constructor a
arglist2- is the argument list for constructor b.
arglist 1 and 2 may or maynot use the argument from arglist, a (arglist1) & b
(arglist2) are functions calls and so the arguments do not contain the data
types. They are variables or constants.
(e.g.) gamma ( int x, int y, float z)
There can be many member objects for each member object a constructor call is
added in the initialize list.
9.5 SUM UP
86
After reading this lesson one would be able to know about the single,
multiple, multilevel, and hybrid inheritance. One can program using virtual
base class and abstract classes. The inherited property of one class to another
will help program complexity.
9.6 References
UNIT IV
LESSON X
POINTERS
10.0 Aim and objectives
10.1 Introduction to pointers
10.2 Pointers to objects
10.3 This pointer
10.4 Pointer to derived classes
10.5 Sum up
87
10.6 References
The aim of this lesson is to get familiar with pointers its derived classes
and its base class.
class b:public a
{
int y ;
public :
void show()
{….}
};
Since the prototype of show() is same in both the places, the function is
not overloaded and therefore static binding does not apply. The compiler does
not know what to do. If the appropriate member function is selected while the
program is running is would be nice and this is called runtime polymorphism.
This can be achieved using a mechanism known as virtual function. Since the
function is linked with a particular class later after the compilation, the process
88
is called late binding or dynamic binding because the selection of the
appropriate function is done dynamically at runtime. Dynamic binding requires
the use of pointers to objects.
polymorphism
89
{
cout << code;
cout << price;
}
};
90
{
item *p=new item[SIZE];
item *d =p;
int x, i;
float y;
for(i=0;i<SIZE;i++)
{
cout << i+l << “input code and price for item”
cin>>x>>y;
p -> getdata(x,y);
p++;
}
for(i=0;i<SIZE;i++)
{
cout<<”item=”<<i+1;
d->show();
d++;
}
}
91
This unique pointer is automatically passed to a member function. When it is
called the this pointer acts as an implicit argument to all the member
functions.
Eg : class ABC
{
int a;
….
…..
…..
};
The private variable a can be used directly inside a member function as a =
123.
The following statement can also be used as
this a = 123;
When a binary operator is overloaded using a member function, we pass only
one argument to the function. The other argument is implicitly passed using
the this pointer. The this pointer returns the object it points to.
E.g. : return * this;
Inside a member function will return the object that invoked the function. It is
used when we compare two or more objects inside a member function and to
return the invoking object as a result.
92
10.4 Pointers to derived classes
10.5 Sum up
After reading this lesson one would be able to program with pointers and
know about the importance of this pointer.
10.6 References
Lesson XI
93
ARRAYS
11.1 Introduction
Here five elements are stored in an array ‘a’. The array elements are
stored sequentially in separate locations. Then question arises how to call
94
individually to each element from this bunch of integer elements. Reading of
array elements begins from zero.
Array elements are called with array name followed by element numbers. Table
explains the same
Calling array elements
A[0] refers to 1st element i.e. 1
A[1 refers to 2nd element i.e. 2
A[2] refers to 3rd element i.e. 3
A[3] refers to 4th element i.e. 4
A[4] refers to 5th element i.e. 5
1. The declaration int a[5] is nothing but creation of five variables of integer
type in memory. Instead of declaring five variables for five values, the
programmer can define them in an array.
2. All the elements of an array share the same name, and they are
distinguished from one another with the help of element number
3. The element number in an array plays major role in calling each element.
4. Any particular element of an array can be modified separately without
disturbing other elements int a [5] = {1,2,3,4,8};
If the programmer needs to replace 8 with 10, he/she is not required to
change all other numbers except 8. to carry out this task the statement a[4]
= 10 can be used. Here the other three elements are not disturbed.
5. Any element of an array a[] can be assigned to another ordinary variable of
array variable of its type.
We know that array is a collection of similar data types. In the same way,
we can also define array of classes. In such type of array, every element is of
class type. Array of class objects can be declared as shown below:
class stud
{
public:
char name[12]; //class declaration
int rollno;
95
char grade[2];
};
class stud st[3]; //declaration of array of class objects
In the above example, st[3] is an array of three elements containing three
objects of class stud. Each element of st[3] has its own set class member
variables i.e. char name[12], int rollno and char grade[2].
Example
#include<stdio.h>
#include<conio.h>
#include<iostream.h>
void main()
{
int k=0;
class stud
{
public:
char name[12];
int rollno;
char grade[2];
};
class stud st[3];
while (k<3)
{
clrscr();
gotoxy(2,4);
cout<<”name :”;
gotoxy(17,4);
cin>>st[k].name;
gotoxy(2,5);
cout<<”roll no:”;
gotoxy(17,5);
cin>>st[k].rollno;
gotoxy(2,6);
96
cout<<”grade:”;
gotoxy(17,6);
cin>>st[k].grade;
st[k].grade[1]=’\0’;
puts(“press any key….”);
getch();
k++;
}
k=0;
clrscr();
cout<<”\nnane \troll no grade\n”;
while (k<3)
{
cout<<st[k].name<<”\t”<<st[k].rollno<<”\t”<<st[k].grade<<”\n”;
k++;
}
}
Output
Name rollno grade
Chris 50 a
Jemi 51 b
Jerry 55 c
11.5 Sum up
After reading this lesson one would be familiar to program with arrays
and pointers, its characteristics and array of classes.
11.6 References
97
Lesson XII
The objectives of this lesson is to make one familiar with the memory
models, dynamic objects and its calling conventions so that while developing
applications one would be familiar with all its memory activities
12.1 Introduction
The memory model sets the supportable size of code and data areas as
shown below. Before compiling and linking the source code, we need to specify
the appropriate memory model. Using memory models, we can set the size
limits of the data and code. C/C++ programs always use different segments for
code and data. The memory model you opt decides the default method of
memory addressing. The default memory model is small.
Data
Code program
Main memory
Maximum available memory
98
(1) tiny
Use the tiny models when memory is at an absolute premium. All four
segment registers(cs,ds,es,ss) are initialized with same address and all
addressing is accomplished using 16 bits. Total memory capacity in this case is
64k bytes. In short, memory capacity is abbreviated as KB. This means that the
code, data and stack must all fit within the same 64kb segment. Programs are
executed quickly if this model is selected. Near pointers are always used. Tiny
models programs can be converted to .com format.
(2) small
All code should fit in a single 64kb segment and all data should fit in a
second 64kb segment. All pointers are 16bits in length. Execution speed is
same as tiny model. Use this model for average size programs. Near pointers are
always used.
(3) medium
All data should fit in a single 64kb segment. However, the code is allowed
to use multiple segments. All pointers to data are 16bits, but all jumps and
calls require 32 bit addresses. With this access to data is fast. However, slower
program execution is observed with this model. This, model is suitable for big
programs that do not keep a large amount of data in memory. Far pointers are
used for code but not for data.
(4) compact
All code should fit in 634kb segment but the data can use multiple
segments. However, no data item can surpass 64kb. All pointers to data are 32
bits, but jumps and calls can use 16 bit addresses. Slow access to data and
quick code execution will be observed in this setting.
Compact model is preferred if your program is small but you require
pointing large amount of data. The compact model is the opposite of the
medium model. Far pointers are preferred for data but not for code. Code is
limited to 64kb, while data has a 1 MB range. All functions are near by default
and all data pointers are far by default.
(5) large
Both code and data are allowed to use multiple segments. All pointers
are 32 bits in length. However, no single data item can exceed 64kb. Code
execution is slower.
Large model is preferred for very bit programs only. Far pointers are used
for both code and data, specifying both a 1MB range. All functions and data
pointers are far by default.
(6) huge
99
Both code and data are allowed to use multiple segments. Every pointer
is of 32 bits in length. Code execution is the slowest.
Huge model is preferred for very big programs only. Far pointers are used
for both code and data. Turbo C++ usually bounds the size of all data to 64k.
The huge memory model sets aside that limit, permitting data to hold more
than 64k. The huge model permits multiple data segments ( each 64k in size),
up to 1MB for code, and 64k for stack. All functions and data pointers are
supposed to be far.
Output
complete address of ch : 0x8f34fff2
segment addresss :8f34
offset address :fff2
Far pointer : a far pointer is a 32 bit pointer and contains both segment and
offset address parts
100
Huge pointer: a huge pointer is a 32 bits long and contains both segment and
offset address parts
Near pointer: a near pointer is 16bits long and uses the contents of cs or ds
register for segment part. The offset part of the address is stored in 16 bits near
pointer.
Output
size of far pointer :4
size of near pointer :2
size of huge pointer : 4
A small mistake in syntax may cause a critical error and possibly corrupt
memory heap.
Some points
1. The new operator not only creates an object but also allocates memory.
2. The new operator allocates correct amount of memory from the heap that is
also called as a free store.
3. The object created and memory allocated by using new operator should be
deleted by the delete operator otherwise such mismatch operations may
101
corrupt the heap or may crash the system. According to ANSI standard ,
it is a valid outcome for this invalid operation and compiler should have
routines to handle such errors.
4. The delete operator not only destroys object but also releases allocated
memory.
5. The new operator creates an object and it remains in the memory until it is
released using delete operator. Sometimes the object deleted using the delete
operator remains in memory.
6. If we send a null pointer to delete operator it is secure. Using delete to zero
has no result.
7. The statement delete x does not destroy the pointer x. it destroys the object
associated with it.
8. Do not apply c functions such as malloc(), realloc() or free() with new and
delete operators. These functions are unfit to object oriented techniques
9. Do not destroy the pointer repetitively or more than one time. First time the
object is destroyed and memory is released. If for the second time the same
object is deleted, the object is sent to the destructor and no doubt it will
corrupt the heap.
10. If the object created is not deleted, it occupies the memory unnecessarily. It
is good habit to destroy the object and release the system resources.
Difference between new and malloc()
New malloc()
Creates objects allocates memory
Returns pointer of relevant type returns void pointer
It is possible to overload new operator malloc () cannot be overloaded
102
*(p+1) = 3; //second element
*(p+2) = 4; //third element
cout<<”value address”);
for(int x = 0;x<3;x++)
cout<<endl<<*(p+x)<<”\t”<<(unsigned)(p+x);
delete []p;
return 0;
}
Output
Value address
2 3350
3 3352
4 3354
103
y = 50;
}
~data()
{
cout<<”\n destructor”;
}
void display()
{
cout <<”\n x= “<<x;
cout<<”\n y=”<,y;
}
};
void main()
{
clrscr();
data *d; //declaration of object pointer
d= new data; //dynamic object
d-> display();
delete d; //deleting dynamic object
}
Output
Constructor
X=10
Y=50
destructor
104
When the same function name is used in both base & derived classes,
the function in base class is derived as virtual using the keyword virtual
proceeding its normal declaration. When a function is made virtual, C++
determines which function to use at runtime based on the type of object pointed
to by base pointer.
E.g.:
#include<iostream.h.
class base
{
public :
void display()
{
cout<<”display base “;
}
virtual void show()
{
cout<<”show base”;
}
};
class derived :public base
{
public:
void display ()
{
cout<<”display derived”;
}
void show()
{
cout <<”show derived “;
}
};
main()
{
base b ;
105
derived d;
base *b;
cout <<”bptr points to base”;
bptr = &b;
bptr -> display();
bptr -> show();
cout <<”bptr points to derived “;
bptr = &d;
bptr -> display();
bptr -> show();
}
Virtual function can be accessed through the use of a pointer declared as
a pointer to base class.
Rules of virtual function
When virtual function are created for implementing late binding, certain
rules are observed they are
• Virtual functions must be members of some class.
• Cannot be static members
• Accessed by using object pointers
• A virtual function can be a friend of another class.
• A virtual function must be defined in a base class even though it is not
used
• The prototypes of the base class version of a virtual function & all the
derived class versions must be same. If they are of the same name, they
are overloaded
• No virtual constructors but virtual destructors are present
• A pointer to be derived class cannot to be used to access an object of the
base type
• A base pointer pointing to a derived class cannot be increment or
decrement to point to the next object in the derived class
• A virtual function defined in the base class need not be redefined in the
derived class
Pure virtual function
It is a type of function which has only a function declaration & it does
not have a function definition
106
12.6 Sum up
From the above lesson one will be familiar with memory models, new and
delete operators, dynamic object and virtual functions.
12.7 References
107
Unit V
LESSON XIII
FILES
13.0 Aim and objectives
13.1 Introduction
13.2 for file stream opertations
13.3 Opening and closing of a file
13.4 Opening files using constructor
13.5 Detecting end of file
13.6 More about open() file modes
13.7 Sum up
13.8 References
In this lesson files, its stream classes and the different modes has been
discussed. One will be familiar to the file concept by going through this lesson.
13.1 Introduction
108
WRITE DATA
READ DATA
(TO FILES)
(FROM FILES)
INTERNAL MEMORY
PROGRAM + DATA
CONSOLE UNIT
GET DATA SCREEN
FROM KEYBOARD COUT<<
PUT DATA
TOSCREEN
KEYBOARD
The i/o system of C++ uses file streams as an interface between the
program and the files. The stream that supplies data to the program is input
stream that reads data from file & the one that receives data from the program
is output stream (i.e.) writes data to file.
READ DATA I/P STREAM DATA I/P
PROGRAM
DISK FILES
O/P STREAM
WRITE DATA DATA O/P
C++ contains a set of classes that define file handling methods, which
include ifstream, ofstream & fstream which are derived from fstreambase & the
corresponding iostream.h. They are declared in fstream.h & must be included
when files are used.
File operation
IOS
109
ISTREAM STREAMBUF OSTREAM
IOSTREAM
FSTREAMBASE
110
For disk files the following things should be decided
* suitable name for the file * purpose
* data type and structure * opening method
The file name is a string of characters and has two parts
1. Primary name
2. An optional period with extension
For opening a file we must first create a file stream and then link it to the
filename. File steam can be defined using the classes ifstream, ofstream and
fstream that are in fstream.h. A file can be opened in two ways they are
1. using the constructor function of the class.
2. using the member function open() of the class
The first method is useful when we use only one file in the stream. The
second method is used when multiple files are using one stream.
o/p stream
Results file
outfile
program
i/p stream
Data file
111
infile
Both reading & writing data can be used from the same file.
Two single file streams working on one file
program 1
….
outfile put data
Salary
file
Program 2 get
data
…….
infile
The connection with the file is closed automatically when the program is
terminated. Here when program1 terminates salary file is disconnected from
outfile stream.
A single program can do both the operations on a file but two file stream
objects are created as outfile and infile.
E.g. :
…….
112
…..
outfile.close(); //disconnect salary from outfile
ifstream infile(“salary”); //connect to infile
….
….
infile.close(); //disconnect salary from infile.
113
file_stream_class stream_object;
stream_object.open(“filename”);
E.g.:
ofstream outfile; //create stream(for output)
outfile.open(“data1”); //connect stream to data1
…
…..
outfile.close(); //disconnect stream from data1
outfile.open(“data2”); //connect stream from data2
….
…..
outfile.close(); //disconnect stream from data2
It is used to prevent any further attempt to read data from the file
eof() is a member function of ios class. It returns a non zero value if eof
condition is encountered otherwise a zero.
114
The open mode can take two arguments, the second argument is used to
specify the file mode
The default values are used in absence of actual values they are
ios :: in for ifstream functions meaning open for read only
ios :: out for ofstream function meaning open for write only
The filemode parameter can be any one of the following
Parameter meaning
ios :: app append to end of file
ios :: ate go to the end of file on opening
ios :: binary binary file
ios :: in open file for reading only
ios :: nocreate open fails if the file does not exit
ios :: noreplace open fails if the file already exits
ios :: out open file for write only
ios :: trunk delete contents of the file if it exits
location
2. Output pointer(put pointer) used for writing to a given file location
The pointers are used to move through files while reading or writing. Each time
input or output operation takes place, the appropriate pointer is automatically
advanced.
Default actions
There are 3 actions they are
1. File opened in read only mode – the input pointer is set to the beginning so
the file can be read from the start
E.g. H E L L O W O R L D
115
Input pointer of “hello” file
2. File opened in write only mode - the existing contents are deleted and the
output pointer is set at the start.
E.g. “hello” file
Output pointer
3. the file opened using append mode – the output pointer is set to the end of
file.
E.g. “hello” file
H E L L O W O R L D
Output pointer
116
int p = fileout.tellp( );
The o/p pointer is moved to the end of the file “ hello” and the value of p will
represent the number of bytes in file.
Specifying the offset
seek functions seekg( ) and seekp( ) can be used with 2 arguments also
seekg( offset,refposition);
seekp( offset,refposition);
offset number of bytes to be moved from the location by refposition argument
The refposition takes one of the 3 following constants
Ios::beg - start of the file
Ios::cur - current position of the pointer
Ios::end - end of the file.
List of sample pointer offset calls and their actions
seek calls actions
fout.seekg(0,ios::beg); go to the start
fout.seekg(0,ios::cur); stay at the current position
fout.seekg(0,ios::end); go to the end of the file
fout.seekg(m,ios::beg); move to the (m+1)th byte in the file
fout.seekg(m,ios::cur); go forward by m bytes from the current position
fout.seekg(-m,ios::cur); go backward by m bytes from the current position
fout.seekg(-m,ios::end); go backward by m bytes from the end
13.7 Sum up
After reading this lesson one will be familiar with the file stream classes
and the different modes in which a file can be operated.
13.8 References
117
LESSON XIV
FILE OPERATION
118
14.6 Reading and writing class objects
14.7 Random access operation
14.8 Sum up
14.9 References
14.1 Introduction
14.2 Sequential input and output operations
The two functions put() and get() are designed for handling a single
character at a time. The two functions write() and read() are designed to write
and read block of binary date.
119
char c;
cout<,”\n entered text:”;
while(io)
{io.get ( c);
cout<<c;
}
return 0;
}
Output
Enter a text : programming with c++
Entered text : programming with c++
120
char c;
ifstream in(“dat”);
if(!in)
{
cout<<”error in opening file.”;
return 1;
}
while ( in.eof()= =0)
{
cout<<(char)in.get();
}
return 0;
}
Output
Programming in c++
These are used to handle binary form. The valued stored in the disk is in the
same format in which they are stored in the internal memory.
( e.g.) an int value and 2594 is stored in binary and character format as
2 bytes
2 5 9 4 character format
4 bytes
An int takes 2 bytes to store its value in binary form, irrespective to its size. 4
digit int will take 4 bytes to store it in character form. Normally binary format is
more accurate
The binary input and output function takes the following form .
121
#include<fstream.h>
#include<conio.h>
#inlcude<string.h>
int main()
{
clrscr();
int num[] = {100,105,110,120,155,250,255};
ofstream out;
out.open(“01.bin”);
out.write((char * ) &num, sizeof(num));
out.close();
for(int i=0;i<7;i++) num[i] = 0;
ifstream.in;
in.open(“01.bin”);
in.read((char *) & num, sizeof(num));
for(i=0;i<7;i++)
cout<<num[i]<<”\t”;
return 0;
}
Output
100 105 110 120 155 250 255
As the class objects are the control elements of C++, it is possible for
writing to and reading from the disk file objects directly. This is done through
read () and write functions.
(e.g.)
#include < f stream.h>
#include < conio.h>
class boys
122
{
char name[20];
int age;
float height;
public:
void get()
{
cout<<”name :”; cin>>name;
cout<<”age :”; cin>>age;
cout<<”height :”; cin>>height;
}
void show()
{
cout<<”\n”<<name<<”\t”<<age<<”\t”<<height;
} };
int main()
{
clrscr();
boys b[3];
fstream out;
out.open(“boys.doc”,ios::in|ios::out);
cout<<”\n enter following information: \n”;
for(int i=0;i<3;i++)
{
b[i].get();
out.write ((char * ) &b[i],size of (b[i]));
}
out.seekg(0);
cout<<”\n entered information \n”;
cout<<”Name Age Height”;
for(i=0;i<=3;i++)
{
123
out.read((char * ) &b[i], sizeof (b[i]));
b[i].show();
}
out.close();
return 0;
}
Output
Name : George
Age : 67
Height : 5.1
Name : Jerald
Age : 34
Height : 5.7
Name : jemimah
Age : 5
Height : 2.8
Entered information
Name Age Height
George 67 5.1
Jerald 34 5.7
Jemimah 5 2.8
Data files always contain large information and the information always
changes. The changed information should be updated otherwise the data files
are not useful. Thus to update data in the file we need to update the data files
with latest information. To update a particular record of data file it may be
stored anywhere in the file but it is necessary to obtain at which location ( in
terms of byte member) the data object is stored.
124
The sizeof() operator determines the size of object. Consider the following
statements
(a) int size = sizeof(o);
Where o is an object and size is an integer variable. The sizeof() operator returns
the size of object o in bytes and it is stored in the variable size. Here, one object
is equal to one record. The position of nth record or object can be obtained
using the following statement
(b) int p = (n-1 * size);
Here p is the exact byte number of the object that is to be updated, n is the
number of object and size is the size in bytes of an individual object (record)
E.g. :
#include < f stream.h>
#include < conio.h>
class boys
{
char name[20];
int age;
float height;
public:
void input()
{
cout<<”name :”; cin>>name;
cout<<”age :”; cin>>age;
cout<<”height :”; cin>>height;
}
void show(int r )
{
cout<<”\n”<<r <<”\t” <<name<<”\t”<<age<<”\t”<<height;
}
};
boys b [3];
fstream out;
void main()
{
125
clrscr();
126
printf(“ “);
x=2;
}
gotoxy(7,x);
printf(“ ”);
gotoxy(7,++x);
printf(“ * ”);
}
}
switch(x)
{
case 3 : get(); put() ;getche(); break;
case 4 : put() ; update(); put(); getche(); break;
default : exit(1);
}
menu();
}
void get()
{
cout<<”\n\n\n\n enter following information :\n”);
for(int i=0;i<3;i++)
{
b[i].input();
out.write((char * ) &b[i],sizeof (b[i]));
}
void put()
{
out.seekg(0,ios::beg);
cout<<”\n\n\n entered information \n”;
cout<<”sr.no name age height”;
for ((int i=0;i<3;i++)
127
{
out.read((char *) &b[i];
sizeof(b[i]));
b[i].show(i+1);
}
}
void update()
{
int r,s= sizeof(b[0]);
out.seekg(0,ios::beg);
cout<<”\n”<<enter record no. to update :”;
cin>>r;
out.seekg(r,ios::beg);
b[0].input();
out.write((char * ) &b[0],sizeof (b[0]));
put();
}
Output
Use up arrow key for selection
Add(*)
Alter ()
Exit()
Name : evan
128
Age 2
Height : 1.5
Entered information
Sr.no name age height
1 jemimah 5 2.8
2 hozana 3 2.2
3 evan 2 1.5
14.8 Sum up
After reading this lesson one would be able to read and write into a file
and know about binary and ascii files and would be able to program on random
access files.
14.9 References
129
130
LESSON XV
TEMPLATES
15.0 Aim and objectives
15.1 Introduction
15.2 Need of Templates
15.3 Definition of class template
15.4 Guidelines for templates
15.5 Difference between templates and macros
15.6 Sum up
15.7 References
15.1 Introduction
131
float, long etc. thus a single function can be used to accept values of different
data types.
132
}
Output
x=a
x = 65
x = 65.254
(1) Templates are applicable when we want to create type secure class that
can handle different data types with same member functions.
(2) The template classes can also be involved in inheritance. For example
template <class T>
class data : public base <T>
Both data and base are template classes. The class data is derived from
template class base.
(3) The template variables also allow us to assign default values. For example,
template <class T, int x=20>
class data
{
t num [x];
}
(4) The name of the template class is written differently in different situations.
While class declaration, it is declared as follows:
class data{ };
For member function declaration is as follows:
void data <T> ::show (T d) {}
Where show() is a member function
Finally, while declaring objects the class name and specific data is specified
before object name
data <int> i1 //object of class data supports integer values
data <float > f1 //object of class data supports float values
(5) All template arguments declared in template argument list should be
used for definition of formal arguments. If one of the template arguments
is not used, the template will be specious.
Consider the example:
template <class T>
133
T show(void)
{
return x;
}
In the above example, the template argument T is not used as a parameter and
the compiler will report an error.
template <class T>
void show(int y)
{
T tmp;
}
In the above example, template type argument is not an argument. Possibly the
system will crash.
(1) Macros are not type safe i.e. a macro defined for integer operation cannot
accept float data. They are expanded with no type checking
(2) It is difficult to find errors in macros.
(3) In case a variable is post – incremented or decremented, the operation is
carried out twice.
134
int a = 10, c;
c=max(a);
cout<,c;
}
The macro defined in the above macro definition is expanded twice. Hence it is
serious limitation of macros. The limitation of this program can be removed
using templates as shown below:
#include<iostream.h>
#include <constream.h>
template <class T>
T max (T k)
{
++k;
return k;
}
void main()
{
clrscr();
int a = 10 ,c;
c=max(a);
cout<<c;
}
Output
11
15.6 Sum up
After reading this lesson one can creates his own template. A person
would be familiar with macros and templates and would be able to differentiate
them both. One would know to program using templates.
15.7 References
135
2. “Object oriented programming with C++”, D.Ravichandran , 2nd ed,TMH
136
LESSON XVI
EXCEPTION HANDLING
This lesson tells us how to handle the errors while certain exceptions
arise. When mistakes or bugs arises what the program has to do is being
discussed in this lesson.
16.1 Introduction
137
C++ has a well organized object oriented method to control run- time
errors that occur in the program. The goal of exception handling is to create a
routine that detects and sends an exceptional condition in order to execute
suitable action. The routine needs to carry following responsibilities:
(a) detect the problem
(b) warn that an error has come
(c) accept the error message
(d) perform accurate actions without troubling the user.
An exception is an object. It is sent from the part of the program where
an error occurs to that part of the program which is going to control the error.
Exception provides an explicit pathway that contains errors to the code that
controls the errors.
138
in function or in nested loop but it should be in try block. After throwing
exception, control passes to the catch statement.
We can also define multiple catch blocks, in try blocks. Such program
also contains multiple throw statements based on certain conditions. The
format of multiple catch statement is given below:
try
{
//try section
}
catch(object1)
{
//catch section1
}
catch(object 2)
139
{
//catch section 2
}
…..
catch(type n object)
{
//catch section – n
}
As soon as an exception is thrown, the compiler searches for appropriate
by matching catch() block. The matching catch() block is executed and control
passes to the successive statement after the last catch() block. In case no match
is found, the program terminates. In multiple catch() statement, if objects of
many catch statements are similar to type of an exception, in such a situation
the first catch() block the matches is executed.
E.g.:
#include<iostream.h>
void num(int k)
{
try
{
if(k= =0) throw k;
else
if (k>0 ) throw ‘p’;
else
140
if (k<0) throw 0;
cout<<”try block”;
}
catch(…)
{
cout << “\n caught an exception”;
}
}
int main(0
{
num(0);
num(5);
num(-1);
return 0;
}
Output
caught an exception
caught an exception
caught an exception
141
(1) It is not essential for throw statement to appear in the try block in order to
throw an exception. The throw statement can be places in any function. If
the function is to be invoked through the try block.
(2) When an exception not specified is thrown, it is known as unexpected
exception.
(3) In case an exception is thrown before complete execution of constructor,
destructor for that object will not be executed.
(4) As soon as an exception is thrown, the compiler searches nearby handlers.
After finding a match, it will be executed.
(5) Overuse of exception handling increases the program size. So apply if
whenever most necessary. Incorrect use of exception handling is not
consistent and generates bugs in the program. Such bugs are hard to
debug.
16.7 Sum up
After going through this lesson one would be able to handle the bugs on
his own as the program may go wrong. One would program for the above said
using try, throw etc.
16.8 References
142
LESSON XVII
STRINGS
17.0 Aim and objectives
17.1 Introduction
17.2 String constructor
17.3 String functions
17.4 Creating string object
17.5 Manipulating string objects
17.6 Comparing and swapping
17.7 Miscellaneous functions
17.8 Sum up
17.9 References
In this lesson one would know completely about the strings its
manipulations and its usage. One can compare strings and work with it.
17.1 Introduction
143
A string is a sequence of characters. C++ does not support a built in
string type. String can be declared as character arrays. ANSI standard C++
provides a new class called string. The string class is very large and includes
many constructors, member functions and operators which can be used for
Creating string objects
Reading string objects from keyboard
Displaying string objects to the screen
Finding a substring from a string
Modifying string objects
Comparing string objects
Adding string objects
Accessing characters in a string
Obtaining the size of strings
144
11. insert() - inserts character at s specified location
12. length() - gives the number of elements in a string
13. replace() - replaces specified characters with a given string
14. resize() - changes the size of the string as specified
15. size() - gives the number of characters in the string
16. swap() - swaps the given string with the invoking string
145
//concatenating strings
s1 = s2 + s3;
cout << “now s1 contains : “<<s1<<”\n”;
return 0;
}
output
s1 = hello
s4 = hello
now s1 contains : hello world
146
cout << “replacing middle 3 characters in s2 with s1 ”;
s2.replace(1,3,s1);
cout << “now s2 = “ <<s2;
return 0;
}
output
after insertion s1 = 1234abcde5
String characteristics
String class supports many functions that could be used to obtain the
characteristics of strings such as size, length, capacity, etc.
Example program
#include<iostream.h>
#include<string.h>
int main()
{
string s1;
cout << “initial status : \n”;
cout<<”size = “ << s1.size() << “\n”;
cout<<”length = “ << s1.length() << “\n”;
cout<<”capacity = “ << s1.capacity() << “\n”;
cout<<”empty = “ << (s1.empty() ? “yes” : “no”;
string s1(“hello”);
cout << “status after assigning value : \n”;
cout<<”size = “ << s1.size() << “\n”;
cout<<”length = “ << s1.length() << “\n”;
cout<<”capacity = “ << s1.capacity() << “\n”;
147
cout<<”empty = “ << (s1.empty() ? “yes” : “no”;
return 0;
}
Output
Initial status :
size = 0
length = 0
capacity = 0
empty = yes
Example program
#include<iostream.h>
#include<string.h>
int main()
{
string s1(“hello world”);
cout<< “ the first character in string contains : ”;
148
cout<<s1.at(0);
int x = s1.find(“world”);
cout << “\n world is found at :” << x << “\n”;
int x1 = s1.find_first_of(‘l’);
cout << “\n the character ‘l’ is found first at :” << x1 << “\n”;
int x2 = s1.find_last_of(‘l’);
cout << “\n the character ‘l’ is found last at :” << x2 << “\n”;
return(0);
}
output
the first character in string contains : h
world is found at : 6
the character ‘l’ is found first at : 2
the character ‘l’ is found last at : 9
The String supports function for comparing and swapping strings. The
compare() function can be used to compare either two strings or portions of two
strings. The swap() function can be used for swapping the contents of two string
objects.
Example
#include<iostream.h>
#include<string.h>
int main()
{
string s1(“road”);
string s2(“read”);
string s3(“red”);
cout<<”s1 = “<<s1<<”\n”;
cout<<”s2 = “<<s2<<”\n”;
cout<<”s3 = “<<s3<<”\n”;
149
int x = s1.compare(s2);
if(x = = 0)
cout<<”both string are equal” <<”\n”;
else if (x>0)
cout<<”string s1 is greter than s2” <<”\n”;
else
cout<<”string s1 is less than s2” <<”\n”;
cout<<”\n before swap :\n”;
cout<<”s1 = “<<s1<<”\n”;
cout<<”s2 = “<<s2<<”\n”;
s1.swap(s2);
cout<<”\n after swap :\n”;
cout<<”s1 = “<<s1<<”\n”;
cout<<”s2 = “<<s2<<”\n”;
return 0;
}
output
s1 = Road
s2 = Read
s3 = Red
s1>s2
Before swap:
s1 = Road
s2 = Read
After swap:
s1 = Read
s2 = Road
assign()
150
This function is used to assign a string wholly/partly to other string
object. It is used in the following format.
S2.assign(s1)
Here s2 and s1 are two string objects. The contents of string s1 are assigned to
s2.
S2. assign (s1,0,5);
In the above format, element from 0 to 5 are assigned to object s2.
Begin()
This member function returns the reference of the first character of the string.
It is used in the following format:
X = s1. begin();
Here x is a character pointer and s1 is a string object.
17.8 Sum up
From the above lesson one would be able to work with strings and would be
familiar with programming on strings
17.9 References
151