0% found this document useful (0 votes)
71 views151 pages

1041 File

This document provides an introduction to object-oriented programming concepts using C++. It discusses the key concepts of OOP like objects, classes, methods, encapsulation, inheritance, polymorphism and more. It also outlines the advantages of OOP like reusability, extensibility and maintainability. Popular OOP languages like C++, Smalltalk, Java and Charm++ are also briefly introduced. The overall aim is to explain the basic foundations of OOP to readers.

Uploaded by

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

1041 File

This document provides an introduction to object-oriented programming concepts using C++. It discusses the key concepts of OOP like objects, classes, methods, encapsulation, inheritance, polymorphism and more. It also outlines the advantages of OOP like reusability, extensibility and maintainability. Popular OOP languages like C++, Smalltalk, Java and Charm++ are also briefly introduced. The overall aim is to explain the basic foundations of OOP to readers.

Uploaded by

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

Unit I

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

1.0 Aim and objectives

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

C++ is an object oriented programming language. Initially it was named


as ‘C with Classes’. It was developed by Bjarne Stroustrup at AT & T bell
laboratories. C++ is an extension of C with addition of class construct. It is a
superset of C. It has three most important facilities called classes, function
overloading and operator overloading. The above features allow to create
abstract data types, inherits properties from existing data types and supports
polymorphism. These features make C++ a object oriented programming
language. The Object oriented features allows the programmers to build large
programs with clarity, extensibility and ease of maintenance.

1.2 Key concepts of Object Oriented Programming

There are several fundamental or key concepts in object–oriented


programming. Some of these are shown below.
C++

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.

red yellow blue

orange green violet

reddish yellowish bluish


brown brown brown

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.

1.3 Advantages of Object Oriented Programming

Object oriented programming provides many advantages to the


programmer and the user. This technology solves many problems related to
software development, provides improved quality, and low cost software. Oop
has the following advantages:
(1) Can be comfortably upgraded.
(2) Using inheritance, redundant program codes can be eliminated and the
use of previously defined classes may be continued.
(3) The technology of data hiding facilitates the programmer to design and
develop safe programs that do not disturb code in other parts of the
program.
(4) The encapsulation feature provided by oop languages allows programmer
to define the class with many functions and characteristics and only few
functions are exposed to the user.
(5) All oop languages can create extended and reusable parts of programs.
(6) OOP enhances the thought process of a programmer leading to rapid
development to new software in short span of time

1.4 Object oriented languages

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.

Charm++ : is also an oop. It is portative. The language provides features such


inheritance, strict type checking, overloading and reusability. It is designed in
order to work efficiently with different parallel system, together with shared
memory systems and networking.
Java : Java was developed by Patrick naughton, James gosling, Chris warth,
mike Sheridan and Ed Frank at Sun Microsystems. Java is an oop language
and supports maximum oop characteristics. Its statement structure is like C
and C++, but it is easier than C++. Java excludes few confusing and unsafe
features of C and C++. For example pointers.
Java allows client/server programming and is used for internet
programming. The Java programs are downloaded by the client machines and
executed on different types of hardware. This portability is achieved by
translation of Java program to machine code using compiler and interpreter.
The Java compiler converts the source program to JVM(Java Virtual
Machine). The JVM is a dummy CPU. The compiler java program is known as
byte code. The java interpreter translates byte code into object code. Compiler
and interpreter do the conversion of Java program to object code.

1.5 Input and Output in C++

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.

1.6 Structure of a C++ program

A C++ program contains four sections. They are as follows.

Include function

Class declarations

Class function definitions

Main function program

Some sample programs


Example-1
// printing a string
include<iostream.h>
main()

7
{
cout << “welcome”;
}
Example 2
// input a number and display it
include<iostream.h>
main()
{
int a,b;
cin>>a>>b;
cout << a<<b;
}

1.7 Tokens and Expressions

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

2.0 Aim and objectives

This lesson concentrates on the various data types used in C++.

2.1 Basic Data Types

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

Size of C++ basic data types.


Type size in bytes
char 1
unsigned char 1
signed char 1
int 2
unsigned int 2
signed int 2
short int 2
unsigned short int 2
signed short int 2
long int 4
signed long int 4
unsigned long int 4
float 4
double 8
long double 10

2.2 User defined data types

Structures and class

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.

Union can be declared as


union item
{
int m;
float x;
char c;
} code;
This declares a variable code of type union item. The compiler allocates a piece
of storage that is large enough to hold the largest variable type in the union.
The union member for the above e.g. can be accessed as
code.m = 300;

2.3 Enumerated data type

An enumerated data type is another user defined type which provides a


way for attaching names to numbers. The enum keyword automatically
enumerates a list of words by assigning them values 0,1,2, and so on.
E.g. enum shape {circle, square, triangle};
From this, new variable can be declared.
E.g. shape ellipse;
The values for the above variable by default is 0 for circle, 1 for square and so on.

2.4 Derived data types

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

C++ allows multidimensional arrays. The syntax is

Type array-name[s1][s2][s3]……[sm];

Here s1, s2, s3 are size of each dimensions.


Function is a small unit of code. The advantage of using function is that
it is possible to reduce the size of the program by calling and using them at
different places in the program. Function is a basic building block of C++
program.
Pointer is a variable that contain an address which is a location of
another variable in the memory. Since pointer is a variable, its value is also
stored in the memory in another location.
E.g. int a = 150;
p = &a;
variable value address
a 150 5000
p 5000 5058
2.5 Symbolic constants

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;

2.7 Operators in C++

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.

Syntax ::variable name

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

Memory dereferencing operator


C++ permits us to define a class containing various types of data and
functions as members and it allows us to access the class members through
pointers. There are three types of pointer-to-member operators. They are
Operator meaning
::* to declare a pointer to a member of a class
* to access a member using object name and a pointer to that
member
-> to access a member using a pointer to the object and a pointer to
that Member
Memory management operators
C++ supports malloc() and calloc() and also uses free() functions. It also
defines two unary operators new and delete for allocating and freeing the
memory in a easier way. As these operators manipulate memory on the free
store they are known as free store operators.
An object can be created by using ‘new’ operator and can be destroyed by
using ‘delete’ operator. A data object created inside a block with new will remain
in existence until it is explicitly destroyed by using delete.
The new operator can be used to create objects of any type.

Syntax
pointer_variable = new data-type;

Here pointer-variable is a pointer of type data-type.


New - allocates sufficient memory to hold a data object of type data-type and
returns the address of the object.
Data type – any valid 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.

Syntax delete pointer-variable;


E.g. delete p;
Manipulators
These are operators that are used to format the data display. The
commonly used manipulators are endl and setw. The endl manipulator causes
a linefeed to be inserted. It has the same affect as using the newline character.
E.g. cout<<m<<endl;
Here one line is left after the value of m;
Normally the numbers are right justified. We can specify a common field
width for all numbers. The setw manipulator is used for setting the width.
cout<<setw(5)<<sum;
the sum value is set to width of 5.

2.7 Sum up

This lesson concentrates on the various data types, constants, variables,


operators and expressions.

2.8 References

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.

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

3.0 Aim and objectives

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

The flow of the execution of the statements should be easy so that it


helps in proper review and maintenance of the program. To achieve this control
structures are used. Different types of control structures are

Sequence structure entry

Action 1

Action 2

Action 3

Exit

Selection Structur entry

True condition False

Action 1 Action 2

Exit
Action 3

18
Loop structure

Loop

condition True Action 1

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.

3.2 Selection structure statements

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

if(expression is true) if(expression is true)


{ {
action1; action1;
} }
else
{
action2;
}

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

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

The for statement


This loop is used when an action is to be repeated for a predetermined
number of times.
Syntax

for(initial value ; test condition; increment)


{
action1;
}

3.5 Sum up

From this lesson


• One can understand the c++ structure
• One should be able to know about data types
• One should be familiar with the operators
• Know about the looping and control structures in c++

3.6 References

1. “Object oriented programming with C++”, E. Balagurusamy,TMH 1998


2. “Object oriented programming with C++”, D.Ravichandran , 2nd ed,TMH

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

4.0 Aim and objectives

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.

4.2 Function Prototyping

The prototype describes the function interface to the complier by giving


details such as the number of arguments and the type of arguments and also
their return types. A function is always declared and defined using a template.
When a function is called, the compiler uses the template to ensure that the
proper arguments are passed, and the return value is treated correctly.
Declaration statements in the calling program is of the following form
Type function-name(argument-list);
E.g. float test(int x, float y, float z);

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

Here the variables a, b and c are called as actual arguments.

4.3 Call by reference

There are two ways of calling a function they are


Call by value
Call by reference
The above function prototype is called as call by value. Normally, value is
passed as arguments from the calling function to the called function. But when
we call by reference, the formal arguments in the called function becomes
aliases to the actual arguments in the calling function. i.e. the function is
working with its own arguments or original data.

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

4.4 Inline function

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.

4.5 Function overloading

Function overloading means the same function name is used to create


many functions with the same name but different argument lists. This function
performs different operations depending on the argument list.

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

1. “Object oriented programming with C++”, E. Balagurusamy, TMH 1998


2. “Object oriented programming with C++”, D. Ravichandran , 2nd ed, TMH

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

5.0 Aim and objectives

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.

5.2 Classes and objects

A class has two parts.


1. Class declaration
2. Class functions definitions
Class declaration describes the type and scope of its members. The class
function definitions describes how the class functions are implemented
class class-name
{
private:
variable declarations;
function declarations;
public:
variable declarations;

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

DATA HIDING IN CLASSES


A simple C++ program using classes
#include<iostream.h>
class student
{
int studno;
char studname[10];
public:
void getdata();

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

5.3 Creating Objects

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

Member functions can be defined in two places


Outside the class definition
Inside the class definition

Outside the class definition


Member functions that are declared inside a class have to be defined
separately outside the class.
The general form is
return-type class-name :: function-name(argument
declaration)
{
function body
}
The operator :: is called as scope resolution operator and it tells that the
function name belongs to the particular class.
Inside the class definition
Another method of defining a member function is to replace the function
declaration by the actual function definition inside the class.
Example
class sample
{
int num;
float cost;
public:
void getdata(int a, float b); // function declaration

void putdata(void) /*function declaration


{ with function definition */
cout<<num<<”\n”;
cout<<cost;
}

33
};

Private member functions


The private member function can be called only by another function that
is a member of its class. Even an object cannot invoke a private function using
the dot operator.
E.g.
class sample
{
int m;
void read(void); //private member function
public:
void update(void);
};
if an object called ‘s’ is created then
s.read(); this is an illegal access.
The function read() can be accessed as follows
void sample :: update(void)
{
read();
}
Arrays within a class
The arrays can be used as member variable in a class
E.g.
const int size = 10;
class arr
{
int a[size];
public:
void setval(void);
void display(void);
};

34
The array variable a[] can be used in the member like other variables. Any
operations can be performed on them.

Member allocation for objects


Memory space for objects is allocated when they are declared. Since all
the objects belonging to that class use the same member functions, no separate
space is allocated for member functions, when the objects are created – only
space for member variables is allocated separately for each object.
Static data members
A data member of a class can be qualified as static. A static member
variable has certain characteristics. They are
• It is initialized to zero when the first object of its class is created.
• Only one copy of that member is created for the entire class and is
shared by all the objects of that class
• It is visible only within the class, but its lifetime is the entire program.
• As the static member are associated with the class itself rather than with
any class objects, they are also known as class variables.
Note: The type and scope of each static member variable must be defined
outside the class definition because the static data members are stored
separately rather than as a part of an object.
E.g.
#include<iostream.h>
class item
{
static int count;
int number;
public:
void getdata(int a)
{
number = a ;
count++;
}
void getcount(void)
{

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

5.5 Static member functions

A member function which is declared as static has the following


properties. A static function can have access to only other static members
(function or variable) declared in the same class. A static member function can
be called using the class name as follows
class-name : : function-name;
Example
#include<iostream.h>
class test
{
int code;
static int count;
public:
void setcode(void)

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

5.6 Array of Objects

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

5.7 Objects as function arguments

An object may be used as function arguments. This can be done in two


ways. A copy of the entire object is passed to the function this is called as pass
by value. Only the address of the object is transferred to the function this is
called as pass by reference.
Pass by value :- any changes made to the object inside the function will not
affect the object used to call the function.
Pass by reference :- The called function works directly on the actual object used
in the call. Any changes made to the object inside the function will reflect in
actual object.

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

1. “Object oriented programming with C++”, E. Balagurusamy, TMH 1998


2. “ Object oriented programming with c++”, D.Ravichandran, 2nd ed, TMH

41
Lesson VI

FRIEND FUNCTIONS

6.0 Aim and objectives


6.1 Friend functions introduction
6.2 Characteristics of friend function
6.3 Overloading member functions
6.4 Returning objects
6.5 Sum up
6.6 References

6.0 Aim and objectives

In this lesson we have discussed about the friend function its


characteristics, how to overload member function and how objects are returned.

6.1 Friend function introduction

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.

6.2 Characteristics of friend function

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

6. 3 Overloading member functions

Member function of one class can be friend functions of another class. In


that case they are defined using the scope resolution operator.
Example
class x
{
……..
……..

int fun1(); //member function of x


……..

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

6.4 Returning objects

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;

c3.y = c1.y + c2.y;


return c3; //returns object c3
}
void complex :: show(complex c)
{
cout<<c.x << “+j”<<c.y<<”\n”;
}
main()
{
complex A,B,C;
A.input(3.1,5.65);
B.input(2.75,1.2);
C = sum(A, B); //C = A + B
cout<<A.show(A);
cout<<B.show(B);
cout<<C.show(C);
}

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

1. “Object oriented programming with C++”, E. Balagurusamy,TMH 1998


2. “Object oriented programming with C++”, D.Ravichandran , 2nd ed,TMH

47
Lesson VII

CONSTRUCTOR AND DESTRUCTOR


7.0 Aim and objectives
7.1 Constructors
7.2 Characteristics of constructor
7.3 Parameterized constructors
7.4 Multiple constructors in a class
7.5 Constructor with default arguments
7.6 Dynamic constructors
7.7 Destructors
7.8 Sum up
7.9 References

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

It is a special member function whose task is to initialize the objects of


its class. It is special because its name is the same as the class name. It is
invoked whenever an object of its associated class is created. It is called
constructor because it constructs the values of data members of the class.
Declaration and definition of a constructor
class sample
{
int m, n;
public:
sample(void); //constructor declared
…..
……..
};
sample :: sample(void) // constructor defined
{
m = 0;
n = 0;
}
A constructor that accepts no parameter is called the default parameter.

7.2 Characteristics of constructor

• They should be declared in the public section.


• They are invoked automatically when the objects are created.
• They do not have return types, not even void and so they cannot return
values.
• They cannot be inherited, though a derived class can call the base class
constructor.
• They can have default arguments.
• Constructors cannot be virtual.
• Their addresses cannot be referred.

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.

7.3 Parameterized constructors

Data elements of different objects may be initialized with different values


when they are created. Arguments can be passed to the constructor function
when the objects are created. The constructor that can take arguments are
called parameterized constructor.
Example
class sample
{
int m,n;
public:
sample(int x, int y);
……..
……..
};
sample ::sample(int x, int y)
{
m = x;
n = y;
}
we must pass the initial values as arguments to the constructor to the
constructor function when an object is declared. This can be done in two ways
by calling the constructor explicitly.
Example
sample int1 = sample(10,20); //explicit call by calling the constructor
implicitly
Example
sample int1(10,20);
Example
#include<iostream.h>
class sample
{

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.

7.4 Multiple constructors in a class

There can be multiple constructors in a class


Example
class sample
{
int m,n;
public:
sample() //constructor1 with no arguments
{
m = 0; n = 0;
}
sample(int a, int b) // constructor2 with no arguments
{
m = a; n = b;
}

To invoke the above constructor the following declarations are used.


sample s1; invokes the first constructor
sample s2(10,20) invokes the second constructor with two arguments

52
7.5 Constructor with default arguments

It is possible to define constructors with default arguments


Example
sample(int x, int y=0);
Here the value zero is assigned to y.
Suppose the statement sample s2(3,5) is assigned then the actual argument 5
will override the default value.

7.6 Dynamic constructors

Constructors are used to allocate memory while creating objects. This


will allocate the right amount of memory for each object when the objects are
not of the same size, resulting in saving of memory. Allocation of memory to
objects at the time of their construction is known as dynamic construction of
objects. This is done with the help of new operator.

7.7 Destructors

It is used to destroy the objects that have been created by a constructor.


Like constructor, the destructor is a member function whose name is similar to
the class name, but preceded by a tilde(~);

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

After reading this lesson one would know to


Use constructors
Its characteristics
Use multiple constructors
Dynamic constructors
Destructors

53
7.9 References

1. “Object oriented programming with C++”, E. Balagurusamy,TMH 1998


2. “Object oriented programming with C++”, D.Ravichandran , 2nd ed,TMH

Unit III

LESSON VIII

Operator Overloading and Type Conversions


8.0 Aim and objectives
8.1 Defining operator overloading
8.2 Steps of overloading

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

8.0 Aim and objectives

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

This mechanism of giving special meanings to an operator is known as


operator overloading. This is flexible for giving new definitions for most of the
C++ operators. The operators those which cannot be overloaded is
class member access operators (.,.*)
scope resolution operator(::)
size operator(size of)
conditional operator(?:)

8.1 Defining operator overloading

To define an additional task to an operator, we must specify what it


means in relation to the class to which the operator is applied. This is done
with a special function called operator function.
General form
return type class name :: operator op(arg_list)
{
function body //task defined
}

return type type of value returned by specified operation


op operator being overloaded
operator keyword
operator op function name
The operator functions must be either member functions or friend
functions. Friend function will have only one argument for unary operators and

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.

8.2 Steps of overloading

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.

overloaded operator functions can be invoked by expressions such as


op x or x op
for unary operators
x op y for binary operators
op x (or x op) would be interpreted as
operator op(x) for friend functions.
Similarly, the expression x op y would be interpreted as either
x .operator op (y)
In case of member function or
operator op(x,y) for friend function

8.3 Overloading unary operator

Unary minus changes the sign of an operand when applied to a basic


data item when applied to an object, it should change the sign of each of its
data item.
Eg :

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

void space ::getdata (int a , int b , int c)


{
x = a;
y= b;
z = c;
}
void space :: display (void)
{
cout<<x;
cout<<y;
cout<<z;
}
void space ::operator –()
{
x = -x;
y = -y;
z=-z;
}
main()
{

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

8.4 Overloading binary operators

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

complex operator +(complex);


void display(void)
};

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

Note: c3 = c1+c2 is similar to c3= c1.operator + (c2);


temp this is an object to hold the result.
complex operator +(complex) since it is a member function
One argument will be the object will be the object itself.

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.

8.5 Overloading friend functions

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

#include <string .h>


#include <iostream.h>
class string
{
char *p;
int len;

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

friend string operator + (const string &s , const string &t);


friend int operator <= (const string &s, const string &t);
friend void show(const string s);
};
string ::string (constr char *s)
{
len = strlen(s);
p = new char[len + 1];
strcpy (p,s);
}
string :: string (const string &s)
{
len = s.len;
p= new char[len+1];
strcpy(p,s.p);
}
//overloading + operator
string operator + ( const string &s, const string &t)
{
string temp;
temp.len = s.len + t.len;
temp.p = new char[temp.len + 1];
strcpy(temp.p,s.p);
strcat(temp.p,t.p);
return (temp);

61
}
//overloading <= operator
int operator <= ( const string &s, const string &t)
{
int m = strlen (s.p);

int n = strlen (t.p);


if (m<=n)
return (1);
else
return (0);
}
void show (const string s)
{
cout <<s.p;
}
main()
{
string s1 = “new”;
string s2 = “york”;
string s3 = “delhi”;
string t1,t2,t3.t4;
t1= s1;
t2=s2;
t3 = s1 + s2;
t4 = s1+s3;
cout << show(t1);
cout << show(t2);
cout << show(t3);
cout << show(t4);
if ( t3 <= t4)
{

62
show(t3);
cout<< “smaller than “;
show ( t4);
}
else
{
show (t4);
cout<<”smaller than”;
show(t3);
}
}

Rules for overloading operators


1. Only existing operators can be overloaded. New operators can be created.
2. The overloaded operators must have at least one operand that is of user –
defined type.
3. We cannot change the basic meaning of an operator.
4. Overloaded operators follow the syntax rules of the original operators
5. There are some operators that cannot be overloaded . They are size of
,.,.*,::,?:
6. In addition to above operators the friend function cannot overload
=,(),[],and ---
7. Unary operators, overloaded by means of a member function, take no
explicit arguments and return no explicit values. But those overloaded by
means of a friend function take one reference argument
8. Binary operators overloaded through a member function take one explicit
argument and those overloaded through a friend function take two explicit
arguments.
9. When using binary operators overloaded through a member function, the
left hand operand must be an object of the relevant class.
10. Binary operators such as +,-,* and / must explicitly return a value

8.6 Type conversion

When constants and variables of different types are mixed automatic


type conversion is done. The assignment operator is used for this purpose.
Eg : int m;

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.

1. basic to class type


The conversion from basic type to class type is easy. Consider an
constructor as an example
string :: string (char * a)
{
length = strlen(a);
p = new char [length + 1];
strcpy (p,a);
}
This constructor builds a string type objects from a char * type variable
‘a’. The variables length and p are data members of the class string. Once this
constructor has defined in the string class it can be used for conversion from
char * type to string type.
Eg: string s1,s2;
char * name1 = “ibm pc”;
char * name 2 = “apple computers”
s1 = string (name1);
s2 = name2;
The statement
s1 = string (name1);

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
…….
}

This function converts a class type data to type name.


E.g. The operator double() converts a class object to type double, operator int()
converts a class type object to type int and so on.

vector :: operator double()


{
double sume = 0;
for(int i=0;i<size ; i++)
sum = sum + v[i]* v[i];
return sqrt(sum);
}

This function converts a vector to the corresponding scalar magnitude.


The double() can be used as follows:
double length = double (v1);
(or)
double length = v1

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

1. “Object oriented programming with C++”, E. Balagurusamy, TMH 1998


2. “Object oriented programming with C++”, D. Ravichandran , 2nd ed, TMH

66
LESSON IX

INHERITANCE

9.0 Aim and objectives


9.1 Introduction of inheritance : extending classes
9.2 Types of inheritance
9.3 Virtual base classes
9.4 Abstract classes
9.5 Sum up
9.6 References

9.0 Aim and objectives

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.

9.1 Introduction of Inheritance : extending 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

single inheritance multiple inheritance hierarchical inheritance

A A

B B C

C D

multilevel inheritance hybrid inheritance

Defining derived classes


A derived class is defined by specifying its relationship with base class in
addition to its own details.

General form

class derived class name : visibility mode base class name


{
…….
……… //members of derived class
……
}

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.

9.2 Types of inheritance

Single inheritance - public derivation


#include <iostream.h>
class B
{
int a; //private ; not inheritable

public :
int b ; //public ; ready for inheritance
void get_ab();
int get_a(void);
void show_a(void);
};

class D: public B // public derivation


{
int c;

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.

Visibility of inherited members

Base class derived class


Public private
Private not inherited not inherited
Protected protected private
Public public private

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

Base class A grandfather

Intermediate base class B father

Derived class C child

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 .

E.g. : test results of a batch of students are stored in 3 different classes


class student stores roll no
class test stores marks obtained in 2 subjects
class result stores total marks obtained in the test.
The class result can inherit the details of the other 2 classes through
multilevel inheritance.
#include <iostream.h>
class student
{
protected:
int roll_number;
public :
void get_number(int);
void put_number(void);
};
void student :: get_number(int a)
{
roll_number = a;
}
void student :: put_number()
{
cout<< roll_number;.
}

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

The syntax of a derived class with multiple base classes is as follows

class D : visibility B1,visibility B2…………….


{
.
.
.
. (body of D)
};

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

arts engineering medical

mechanical electrical civil

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

sports class might look like

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

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

9.3 Virtual base classes

This supports all the three kinds of inheritance they are multilevel,
multiple and hierarchical inheritance.

E.g. : grand parent

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

{
…..
…..
};

class B2 : public virtual A //parent 2


{
……
……
};
class C : public B1, public b2 //child
{
…… //only one copy of A will be inherited
……
};

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

class sports: public virtual student


{
protected:
float score;
public:
void get_score (float s)
{
score = s;}
void put_score(void)
{
cout<<score;
};
class result : public test, public sports

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

9.4 Abstract classes

It is not used to create objects. It is designed only to act as a base class(


to be inherited by other classes). It is a design concept in program development
and provides a base upon which other classes are built. In the above (eg) the
student class is an abstract class which does not create any object.
Member classes: Nesting of classes.
A class can contain objects of other classes as its members.
E.g.:
class alpha {…..}
class beta {……}

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

1. “Object oriented programming with C++”, E. Balagurusamy,TMH 1998


2. “Object oriented programming with C++”, D.Ravichandran , 2nd ed,TMH

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

10.0 Aim and objectives

The aim of this lesson is to get familiar with pointers its derived classes
and its base class.

10.1 INTRODUCTION TO POINTERS

Polymorphism means one name multiple forms. The overloaded member


functions are selected for invoking by matching arguments, both type and
number. This information is known to the compiler at the compile time and so
the compiler is able to select the right function for the cal at compile time itself.
This is called early binding or static binding or static linking or compile time
polymorphism. Early binding means that an object is bound to its function call
at compile time.
(e.g.) If a function name and prototype is same in both the base and derived
classes.
(i.e) class A
{
int x;
public :
void show(){…}
};

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

compile time run time

Function Operator Virtual


overloading overloading function

10.2 Pointers to objects

A pointer can point to an object created by a class.


E.g. :
item x ; -------- item is a class and x is an object defined to be of type item
item *it_ptr --------is a pointer of type item
Object pointers are useful in creating objects at runtime, an object pointer can
be used to access the public members of an object.
E.g. :
class item
{
int code;
float price;
public:
void getdata(int a, float b)
{
code =a ;
price =b;}
void show(void)

89
{
cout << code;
cout << price;

}
};

Let us declare an item variable x and a pointer ptr as


item x;
item *ptr = &x; the pointer ptr is initialized with the address of x

The member function of item can be referred in 2 ways


1. using dot operator and object
x.getdata(100,75.50);
x.show();
2. using the arrow operator and object pointer
ptr->getdata (100,75.50)
ptr->show( )
ptr is an alias of x, it can also be used as *(ptr).show();
The parenthesis are necessary because the dot operator has higher precedence
than the operator *.
Objects can be created using pointer & new operator as
item *ptr = new item;
It allows enough memory space to the data members in the object structure and
assigns the memory space to ptr. Then ptr can be used to refer to the
members as
ptr-> show( );
An array of objects using pointers can also be created as item
item *ptr = new item[10] //array of 10 objects
It creates memory space for an array of 10 objects of item. For the class item
the code is as follows

const int SIZE = 2;


main()

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

10.3 This pointer

C++ uses a unique keyword called this to represent an object that


invokes a member function . This is a pointer that points to the object for which
this function was called
A.max ( ) will set the pointer this to the address of object A.

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.

E.g.: person &person :: greater (person &x)


{
if (x. age > age)

return x; //argument object


else
return * this ; //invoking object
}
This function is invoked by the call
max = a.greater (b);
The function return the object B if the age of the person B is greater than
that of A, otherwise it will return the object A, using the this pointer. The
dereference operator * produces the contents at the address contained in the
pointer.

92
10.4 Pointers to derived classes

Pointers can be used to the objects of derived classes. Pointers to objects


of a base class can be used as pointers to the objects of a derived class.
Therefore a single pointer variable can be made to point to objects belonging to
different classes

Eg : if B is a base class & D is a derived class from B, then a pointer declared


as a pointer to B can also be a pointer to D.
Eg: b *cptr; //pointer to class B type variable
B b; //base object
D d; //derived
cptr = & b; //cptr points to objects b
cptr = & d; //cptr points to object d
cptr can access only those members inherited from B & not the members that
originally belong to D. Suppose a member of D has the same name as one of the
members of B then any reference by cptr will always access the base class
member.

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

1. “Object oriented programming with C++”, E. Balagurusamy, TMH 1998.


2. “Object oriented programming with C++”, D. Ravichandran , 2nd ed, TMH.

Lesson XI

93
ARRAYS

11.0 Aim and objectives


11.1 Introduction
11.2 Array declaration and initialization
11.3 Characteristics
11.4 Array of classes
11.5 Sum up
11.6 References

11.0 Aim and objectives

This lesson concentrates on arrays its characteristics and array of


classes. After reading this lesson one would be familiar with arrays its
characteristics and programming on arrays.

11.1 Introduction

Arrays is a collection of elements of similar data types in which each


element is unique and location in separate memory locations

11.2 Array declaration and initialization

Declaration of an array is shown below:


Declaration
E.g. int a[5];
It tells to the compiler that ‘a’ is an integer type of array and it must store
five integers. The compiler reserves two bytes of memory for each integer array
element. In the same way array of different data types are declared as below:
Array declaration
char ch[10];
float real [10];
long num [5];
The array initialization is done as given below:
Array initialization
int a[5] = { 1,2,3,4,5};

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

11.3 Characteristics of arrays

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.

11.4 Arrays of classes

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

1. “Object oriented programming with C++”, E. Balagurusamy, TMH 1998.


2. “Object oriented programming with C++”, D.Ravichandran , 2nd ed, TMH.

97
Lesson XII

MEMORY MODELS AND VIRTUAL FUNCTIONS

12.0 Aim and objectives


12.1 Introduction
12.2 Memory models
12.3 New and delete operators
12.4 Dynamic objects
12.5 Virtual functions
12.6 Sum up
12.7 References

12.0 Aim and objectives

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

Memory is one of the critical resources of a computer system. One must


be conscious about the memory modules while an application is being
developed.

12.2 Memory models

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.

(7) segment and offset address


Every address has two parts, segment and offset. We can separate these
address parts using following two macros defined in dos.h header file.
FP_SEG() - his macro is used to obtain segment address of the given pointer
variable.
FP_OFF() - his macro is used to obtain offset address of the given pointer
variable.
The following program illustrates working of both these macros.
#include<dos.h>
#include<iostream.h>
#include<constream.h>
void main()
{
clrscr();
int ch;
cout<<”\n complete addresss of ch:”<<&ch;
cout<<”\n segment address :”<<hex<<fp_seg(&ch);
cout<<”\n offset address :”<<hex<<fp_off(&ch);
}

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.

Program to declare far, near and huge pointers


#include <iostream.h>
#inlcude<constream.h>
void main()
{
clrscr();
char far *f; //far pointer declaration
char near *n //near pointer declaration
char huge *h; //huge pointer declaration
cout<<”\n size of far pointer :”<<sizeof(f);
cout<<”\n size of near pointer :”<<sizeof(n);
cout<<”\n size of huge pointer:”<<sizeof(h);
}

Output
size of far pointer :4
size of near pointer :2
size of huge pointer : 4

12.3 New and delete operators

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

Program using new and delete


#include<iostream.h>
#include<conio.h>
int main()
{
clrscr();
int i,*p;
p=&i;
p=new int [3];
*p =2; //first element

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

12.4 Dynamic objects

C++ supports dynamic memory allocation. C++ allocates memory and


initializes the member variables. An object can be created at runtime. Such
object is called as dynamic object. The construction and destruction of dynamic
object is explicitly done by the programmer. The operator new and delete are
used to allocate and deallocate memory to such objects. A dynamic object can
be created using delete operator as follows
delete ptr;
It destroys the object pointed by pointer ptr. It also invokes the
destructor of a class. The following program explains creation and deletion of
dynamic object.
#include<iostream.h>
#include<constream.h>
class data
{
int x,y;
public:
data()
{
cout<<”\n constructor”;
x = 10;

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

12.5 Virtual function

A base pointer, when it is made to contain the address of a derived class


always executes the function in the base class. The compiler simply ignores the
contents of the pointer & chooses the member functions that matches the type
of the pointer. But polymorphism can be achieved using virtual function.

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

1. “Object oriented programming with C++”, E. Balagurusamy, TMH 1998.


2. “Object oriented programming with C++”, D.Ravichandran, 2nd ed, TMH.

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

13.0 Aim and objectives

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

A file is as collection of related data stored in a particular area on the


disk. Programs can be designed to perform the read & write operations on these
files
DATA FILES

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

13.2 Classes for file stream operations

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

IFSTREAM FSTREAM OFSTREAM FILEBUF

FSTREAMBASE

Details of file stream classes


Class contents
file buf its purpose is to set the buffers to read & write
It contains open() and close() as members
fstreambase provides operations common to the file streams and
serves as a base for fstream, ifstream and ofstream
classes. It contains open() and close functions
ifstream provides input operations. Contains open() with
default input mode. Inherits the functions get(),
getline(), read(), seekg() and tellg() functions from
istream.
ofstream provides output operations. Contains open() with
default output mode. Inherits put(), seekp(), tellp()
and write functions from ostream.
fstream provides support for simultaneous input and output
operations. Contains open() with default input mode.
Inherits all the functions from istream and ostream
classes through iostream.

13.3 Opening and closing a file

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.

13.4 Opening files using constructor

A filename is used to initialize the filestream object. It involves the


following steps
* create a file stream object to manage the stream using the appropriate class.
(i.e.) ofstream is used to create output stream and ifstream is used to create
input stream.
* initialize the file object with the derived filename.
E.g. : ofstream outfile(“results”); //results is a file name
The above statement creates outfile as an ofstream object that manages
the output stream. This also opens the file results and attaches it to the output
stream outfile.
Similarly the statement declares infile as an ifstream object and attaches it to
the file data for reading(input)
ifstream infile(“data”);
Single file streams working on separate files disk

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 program statements for the above is as follows


Prg1
….
ofstream outfile(“salary”);
……
……
Prg2
…….
……
ifstream infile(“salary”);

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.

Program to read & write data using a single file


#include<fstream.h.
main()
{
ofstream outf(“item”);
cout<<”enter item name:”;
char name[30];
cin>>name;
outf<<name<<”\n”; //write to file item
cout<<”enter item cost “;
float cost;
cin >>cost;
outf<<cost<<”\n”; //write to file item
outf.close(); //disconnect item file from outf
ifstream inf(“item”); //connect it to inf

inf>>name; //read name from file item


inf>>cost; //read cost from file item
cout<<name;
cout<<cost;
inf.close();
}
Opening files using open()
Open() function is used to open multiple files using the same stream
object

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

13.5 Detecting end of file

It is used to prevent any further attempt to read data from the file

statement while (fin)


an ifstream object, such as fin returns 0 if any errors occurs in the file
operation including the eof condition.
Another method is
if (fin.eof() != 0)
{ exit (1) ;}

eof() is a member function of ios class. It returns a non zero value if eof
condition is encountered otherwise a zero.

13.6 More about open() file modes

114
The open mode can take two arguments, the second argument is used to
specify the file mode

Syntax stream_object.open(“file name”,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

File pointers and their manipulations


Each file has 2 pointer called file pointers. They are
1. Input pointer(get pointer)  used for reading the contents of a given file

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

Function for manipulation of file pointers


The file stream classes support the following function to move the file
pointer wherever necessary they are
seekg  moves get pointer(input) to a specified location
seekp  moves put pointer (output) to a specified location
tellg()  gives the current position of the get pointer
tellp()  gives the current position of the put pointer
(e.g.) infile.seekg(10)
This moves the file pointer to the byte number 10. The bytes in a file are
numbered from zero. So the pointer will point to the 11th byte in the file.
e.g.) ofstream fileout;
fileout.open(“hello”,ios::app);

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

1. “Object oriented programming with C++”, E. Balagurusamy,TMH 1998


2. “Object oriented programming with C++”, D.Ravichandran , 2nd ed,TMH

117
LESSON XIV

FILE OPERATION

14.0 Aim and objectives


14.1 Introduction
14.2 Sequential input and output operations
14.3 Put( ) and get( ) functions
14.4 Binary and ASCII
14.5 Read and write function

118
14.6 Reading and writing class objects
14.7 Random access operation
14.8 Sum up
14.9 References

14.0 Aim and objectives

In this lesson sequential operations input and output operations of a file


are discussed.

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.

14.3 put() and get() functions.

put() - writes a single character to the associated streams


get() - reads a single character from the associated streams
(e.g.) a program for i/o operations on characters
# include <fstream.h>
# include <string.h>
main( )
{
clrscr();
char text[50];
cout<<”\n enter a text :”;
cin.getlinle(text,50);
int l = 0;
fstream io;
io.open(“data”,ios::in | ios::out);
while(l[text]!=’\0’)
io.put(text[l++]);
io.seekg(0);

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

14.4 Binary and ASCII files

The insertion and extraction operators, known as stream operator,


handles formatted data. The programmer needs to format data in order to
represent it in a suitable fashion. ASCII codes are used by the IO devices to
share or pass data to the computer system, but Central Processing Unit(CPU)
manipulates the data using binary numbers i.e. 0 and 1. For this reason, it is
essential to convert the data while accepting data from input devices and
displaying the data on output devices. Consider the following statements.
cout<<k; //displays value of k on screen
cin>>k; //reads value of k from keyboard
Here, k is an integer variable. The operator << converts value of integer
variable k into stream of ASCII characters. In the same fashion, the >> operator
converts the ASCII characters entered by the user to binary. The data is entered
through the keyboard, a standard input device. For example, you enter 21, the
stream operator >> gets ASCII codes of the individual digits of the entered
number 22 i.e ., 50 and 49. ASCII code of 2 and 1 are 50 and 49 respectively.
The stream operator >> converts the ASCII value to equivalent binary
format and assigns it to the variable k. The stream operator << converts the
value of k(21) that is stored in binary format into equivalent ASCII codes i.e., 50
and 49.
Eg:
#include <fstream.h>
#include<constream.h>
int main()
{
clrscr();

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

14.5 Write() and read() functions.

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

00001010 00100010 binary format

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 .

infile.read((char * ) &v, sizeof(v));


outfile.write((char *) &v,size of (v));
The first is the address of the variable V and the second is the length of that
variable in bytes.
E.g.:

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

14.6 Reading and Writing class objects

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

14.7 Random access operation

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

void menu ( void);


out.open(“boys.doc”,ios::in|ios::out|ios::noreplace);
menu();
}
void menu(void)
{
void get(void);
void put(void);
void update(void);
int x;
clrscr();
cout<<”\n use up arrow key for selection”;
char ch= ‘ ‘;
gotoxy(1,3);
printf(“ADD ( )”);
gotoxy(1,4);
printf(“ALTER ()”);
gotoxy(1,5);
printf(“EXIT ()”);
x=3;
gotoxy(7,x);
printf(”*”);
while (ch!=13)
{
ch = getch();
if ( ch = = 72)
{
if(x>4)
{
gotoxy(7,x);

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

Enter following information:


Name : jemimah
Age :5
Height : 2.8
Name : hozana
Age : 3
Height : 2.2

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

1. “Object oriented programming with C++”, E. Balagurusamy,TMH 1998


2. “Object oriented programming with C++”, D.Ravichandran , 2nd ed,TMH

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.0 Aim and objectives

This lesson concentrates on templates its needs, function templates,


class templates and other uses with templates. After reading this lesson one
would be able to differentiate between macro and templates.

15.1 Introduction

Templates is one of the most useful characteristics of C++. Few old


compilers do not allow template mechanism. templates are part of ANSI C++
standard. All major compilers support templates in their new versions.
Instantiation is the activity of creating particular type using templates. The
specific classes are known as instance of the template. The template provides
generic programming by defining generic classes. In templates, generic data
types are used as arguments and they can handle a variety of data types. A
function that works for all C++ data types is called as generic function.
Templates help the programmer to declare group of functions or classes. When
used with function they are called function templates. For example, we can
create a template for function square(). It helps us to calculate square of a
number of any data type including int, float, long and double. The templates
associated with classes are called as class templates. A template is almost same
as macro and it is type secured.

15.2 Need of template

Template is a technique that allows using a single function or class to


work with different data types. Using template we can create a single function
that can process any type of data. They can accept data of any type such as int,

131
float, long etc. thus a single function can be used to accept values of different
data types.

15.3 Definition of class template

To declare a class of template type, following syntax is used.


template declaration
template class<t>
class name_of_ class
{
//class data member and function
}
The first statement template class <t> tells the compiler that the following class
declaration can use the template data type. T is a variable of template type that
can be used in the class of define variable of template type. Both template and
class are keywords. The <> is used to declare variables of template type that
can be used inside the class to define variables of template type. One or more
variables can be declared separated by comma. Templates cannot be declared
inside classes or functions. They must be global and should not be local.
E.g. :
#include<iostream .h>
#inlcude<conio.h>
template <class T>
void show(T x)
{
cout<<”\n x = “<<x;
}
void main()
{
clrscr();
char c = ‘a’;
int i=65;
double d = 65.254;
show (c );
show(i)
show(d);

132
}
Output
x=a
x = 65
x = 65.254

15.4 Guidelines for templates

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

template <class T, class S>


void max(t & k)
{
S p;
}
The template variable S is not used. Therefore, Compile time error is generated.

15.5 Difference between templates and macros

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

#define max(a) a + ++a


void main()
{

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

1. “Object oriented programming with C++”, E. Balagurusamy,TMH 1998

135
2. “Object oriented programming with C++”, D.Ravichandran , 2nd ed,TMH

136
LESSON XVI

EXCEPTION HANDLING

16.0 Aim and objectives


16.1 Introduction
16.2 The keywords try, throw and catch
16.3 Multiple catch statements
16.4 Catching multiple exceptions
16.5 Rethrowing exception
16.6 Guidelines for exception handling
16.7 Sum up
16.8 References

16.0 Aim and objectives

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

While writing large programs, a programmer makes many mistakes. Due


to this, bugs occur even in the released software. Developing an error free
program is the objective and intention of the programmer. Programmers have to
take care to prevent errors. Errors can be trapped using exception handling
features.
Like errors, exceptions are also of two types. They are as follows:
(a) synchronous exception
(b) asynchronous exceptions

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.

16.2 The keywords try , throw and catch

Exception handling techniques passes control of program from a location


of exception in a program to an exception handler routine linked with the try
block. An exception handler routine can only be called by throw statement.

(1) The keyword try


The try keyword is followed by a series of statements enclosed in curly braces.
Syntax of try statement
try
{
statement 1;
statement 2;
}

(2) The keyword throw


The function of throw statement is to send the exception found. The
declaration of throw statement is as given below:
Syntax of throw statement
throw (excep);
throw excep;
throw //rethrowing of an exception
The argument excep is allowed in any type and it may be a constant. The
catch block associated with try block catches the exception thrown. The control
is transferred from try block to catch block. The throw statement can be placed

138
in function or in nested loop but it should be in try block. After throwing
exception, control passes to the catch statement.

(3) The keyword catch


Like try block, catch block also contains a series of statements enclosed in curly
braces. It also contains an argument of exception type in parenthesis.
Syntax of catch statement
try
{
statement 1;
statement 2;
}
catch(argument)
{
statement 3; //action to be taken
}
When exception is found the catch block is executed. The catch()
statement contains an argument of exception type and it is optional. When
argument is declared it can be used in the catch block. After execution of the
catch block, the statements inside the blocks are executed. In case no exception
is caught, the catch block is ignored and if mismatch is found the program
terminates.

16.3 Multiple catch statements

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.

16.4 Catching multiple exceptions

It is also possible to define single or default catch() block from one or


more exceptions of different types. In such a situation a single catch block is
used for catch exceptions thrown by multiple throw statements.
catch()
{
//statements for handling
//all exceptions
}

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

16.5 Rethrowing exception

It is also possible to pass again the exception received to another


exception handler i.e. an exception is thrown from catch() block and this is
known as rethrowing of exception. The following statement accomplishes this:
throw;
The above throw statement is used without any argument. This statement
throws the exception caught to the next try catch statements.

16.6 Guidelines for exception handling

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

1. “Object oriented programming with C++”, E. Balagurusamy,TMH 1998.


2. “Object oriented programming with C++”, D.Ravichandran , 2nd ed,TMH.

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

17.0 Aim and objectives

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

17.2 String constructors

Some commonly used string constructors are


1. string(); - used for creating an empty string
2. string(const char *str); - used for creating a string object from a null
terminated string
3. string(const string & str); - used for creating a string object from other
string object.

17.3 String functions

Some important functions supported by the string class are


1. append() - appends a part of string to another string
2. assign() - Assigns a partial string
3. at() - obtains the character stored at a specified location
4. begin() - returns a reference to the start of the string
5. capacity() - gives the total elements that can be stored
6. compare() - compares string against the invoking string
7. empty() - returns true if the string is empty, otherwise returns false
8. end() - returns a reference to the end of the string
9. erase() - removes characters as specified
10. find() - searches for the occurrence of a specified string

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

17.4 Creating string objects

String objects can be created in a number of ways.


string s1; // using constructor with no argument
string s2(“abc”); // using one argument constructor
s1 = s2; // Assigning string objects
s3 = “xyz” + s2; // concatenating strings
cin >> s1; // reading through keyboard(one word)
getline(cin, s1); // reading through keyboard a line of text

Example Program for creating objects


#include<iostream.h>
#include<string.h>
int main()
{ //creating string objects
string s1;
string s2(“hello”);
string s3(“world”);
//assigning values to string objects
s1 = s2;
cout << “s1 = “ << s1 << “\n”;

//using another object


string s4(s1);
cout << “s4 = “ << s4 << “\n”;

145
//concatenating strings
s1 = s2 + s3;
cout << “now s1 contains : “<<s1<<”\n”;

return 0;
}
output
s1 = hello
s4 = hello
now s1 contains : hello world

17. 5 Manipulating string objects

Contents of string objects can be modified in several ways, using the


member functions such as insert(), replace(), erase and append().
Example
#include<iostream.h>
#include<string.h>
int main()
{
string s1(“12345”);
string s2(“abcde”);

//inserting a string into another


s1.insert(4,s2);
cout << “after insertion s1 = “<< s1 <<”\n”;

//removing characters in a string


cout << “remove 2 characters from s1”;
s1.erase(4,2);
cout<<”now s1 = “<< s1<<”\n”;

//replacing characters in a string

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

removing 2 characters from s1 now s1 = 1234cde5


replacing middle 3 characters in s2 with s1 now s2 = a12345e;

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

status after assigning value:


size = 5
length = 5
capacity = 31 //capacity 26 is default with the size 5
empty = no
Accessing characters in a strings
We can access substrings and individual characters of a string in several
ways. Some of the functions supported are
at() - for accessing individual characters
substr() - for retrieving a substring
find() - for finding a specified substring
find_first_of() - for finding the location of first occurrence of the given character
find_last_of() - for finding the location of last occurrence of the given character

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

17.6 Comparing and swapping

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

17.7 Miscellaneous functions

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

1. “Object oriented programming with C++”, E. Balagurusamy,TMH 1998


2. “Object oriented programming with C++”, D.Ravichandran , 2nd ed,TMH

151

You might also like