302 Book FOR STUDENTS
302 Book FOR STUDENTS
302 Book FOR STUDENTS
Unit Structure:
Software crisis
Software Evaluation
POP (Procedure Oriented Programming)
OOP (Object Oriented Programming)
Basic concepts of OOP
Objects
Classes
Data Abstraction and Data Encapsulation
Inheritance
Polymorphism
Dynamic Binding
Message Passing
Benefits of OOP
Object Oriented Language
Application of OOP
Introduction of C++
Application of C++
Simple C++ Program
Program Features
Comments
Output Operators
Iostream File
Namespace
Return Type of main ()
More C++ Statements
Variable
Input Operator
Cascading I/O Operator
Example with Class
Structure of C++
Creating Source File
Compiling and Linking
Software Crisis
Developments in software technology continue to be dynamic. New tools and techniques
are announced in quick succession. This has forced the software engineers and industry to
continuously look for new approaches to software design and development, and they are
becoming more and more critical in view of the increasing complexity of software
systems as well as the highly competitive nature of the industry. These rapid advances
appear to have created a situation of crisis within the industry. The following issued need
to be addressed to face the crisis:
How to represent real-life entities of problems in system design?
How to design system with open interfaces?
How to ensure reusability and extensibility of modules?
How to develop modules that are tolerant of any changes in future?
How to improve software productivity and decrease software cost?
How to improve the quality of software?
How to manage time schedules?
Software Evaluation
Ernest Tello, A well known writer in the field of artificial intelligence, compared the
evolution of software technology to the growth of the tree. Like a tree, the software
evolution has had distinct phases “layers” of growth. These layers were building up one
by one over the last five decades as shown in fig. 1.1, with each layer representing and
improvement over the previous one. However, the analogy fails if we consider the life
of these layers. In software system each of the layers continues to be functional,
whereas in the case of trees, only the uppermost layer is functional
1, 0
Machine Language
Assembly Language
Procedure- Oriented
With the advent of languages such as c, structured programming became very popular
and was the main technique of the 1980’s. Structured programming was a powerful tool
that enabled programmers to write moderately complex programs fairly easily. However,
as the programs grew larger, even the structured approach failed to show the desired
result in terms of bug-free, easy-to- maintain, and reusable programs.
Procedure-Oriented Programming
In the procedure oriented approach, the problem is viewed as the sequence of things to
be done such as reading, calculating and printing such as cobol, fortran and c. The
primary focus is on functions. A typical structure for procedural programming is shown
in fig.1.2. The technique of hierarchical decomposition has been used to specify the tasks
to be completed for solving a problem.
Main Program
Function-4
Function-5
In a multi-function program, many important data items are placed as global so that
they may be accessed by all the functions. Each function may have its own local data.
Global data are more vulnerable to an inadvertent change by a function. In a large
program it is very difficult to identify what data is used by which function. In case we
need to revise an external data structure, we also need to revise all functions that access
the data. This provides an opportunity for bugs to creep in.
Another serious drawback with the procedural approach is that we do not model real
world problems very well. This is because functions are action-oriented and do not really
corresponding to the element of the problem.
DATA DATA
Communication
FUNCTION FUNCTION
Object
DATA
FUNCTION
Some of the features of object oriented programming are:
Objects
Objects are the basic run time entities in an object-oriented system. They may represent a
person, a place, a bank account, a table of data or any item that the program has to
handle. They may also represent user-defined data such as vectors, time and lists.
Programming problem is analyzed in term of objects and the nature of communication
between them. Program objects should be chosen such that they match closely with the
real-world objects. Objects take up space in the memory and have an associated address
like a record in Pascal, or a structure in c.
When a program is executed, the objects interact by sending messages to one another.
Foe example, if “customer” and “account” are to object in a program, then the customer
object may send a message to the count object requesting for the bank balance. Each
object contain data, and code to manipulate data. Objects can interact without having to
know details of each other’s data or code. It is a sufficient to know the type of message
accepted, and the type of response returned by the objects. Although different author
represent them differently fig 1.5 shows two notations that are popularly used in object-
oriented analysis and design.
OBJECTS: STUDENT
DATA
Name
Date-of-birth
Marks
FUNCTIONS
Total
Average
Display
………
Classes
We just mentioned that objects contain data, and code to manipulate that data. The entire
set of data and code of an object can be made a user-defined data type with the help of
class. In fact, objects are variables of the type class. Once a class has been defined, we
can create any number of objects belonging to that class. Each object is associated with
the data of type class with which they are created. A class is thus a collection of objects
similar types. For examples, Mango, Apple and orange members of class fruit. Classes
are user-defined that types and behave like the built-in types of a programming language.
The syntax used to create an object is not different then the syntax used to create an
integer object in C. If fruit has been defines as a class, then the statement
Fruit Mango;
Will create an object mango belonging to the class fruit.
The wrapping up of data and function into a single unit (called class) is known as
encapsulation. Data and encapsulation is the most striking feature of a class. The data is
not accessible to the outside world, and only those functions which are wrapped in the
class can access it. These functions provide the interface between the object’s data and
the program. This insulation of the data from direct access by the program is called data
hiding or information hiding.
Abstraction refers to the act of representing essential features without including the
background details or explanation. Classes use the concept of abstraction and are defined
as a list of abstract attributes such as size, wait, and cost, and function operate on these
attributes. They encapsulate all the essential properties of the object that are to be created.
The attributes are some time called data members because they hold information. The
functions that operate on these data are sometimes called methods or member function.
Inheritance
Inheritance is the process by which objects of one class acquired the properties of objects
of another classes. It supports the concept of hierarchical classification. For example,
the bird, ‘robin’ is a part of class ‘flying bird’ which is again a part of the class ‘bird’.
The principal behind this sort of division is that each derived class shares common
characteristics with the class from which it is derived as illustrated in fig 1.6.
In OOP, the concept of inheritance provides the idea of reusability. This means that we
can add additional features to an existing class without modifying it. This is possible by
deriving a new class from the existing one. The new class will have the combined feature
of both the classes. The real appeal and power of the inheritance mechanism is that it
Fig. 1.6 Property inheritances
BRD
Attributes
Features
Lay Eggs
Attributes Attributes
………… ………..
………... ………..
Polymorphism
Fig. 1.7 illustrates that a single function name can be used to handle different number
and different types of argument. This is something similar to a particular word having
several different meanings depending upon the context. Using a single function name to
perform different type of task is known as function overloading.
Shape
Draw
Binding refers to the linking of a procedure call to the code to be executed in response to
the call. Dynamic binding means that the code associated with a given procedure call is
not known until the time of the call at run time. It is associated with polymorphism and
inheritance. A function call associated with a polymorphic reference depends on the
dynamic type of that reference.
Consider the procedure “draw” in fig. 1.7. by inheritance, every object will have this
procedure. Its algorithm is, however, unique to each object and so the draw procedure
will be redefined in each class that defines the object. At run-time, the code matching the
object under current reference will be called.
Message Passing
An object-oriented program consists of a set of objects that communicate with each other.
The process of programming in an object-oriented language, involves the following basic
steps:
1. Creating classes that define object and their behavior,
2. Creating objects from class definitions, and
3. Establishing communication among objects.
Objects communicate with one another by sending and receiving information much the
same way as people pass messages to one another. The concept of message passing
makes it easier to talk about building systems that directly model or simulate their real-
world counterparts.
A Message for an object is a request for execution of a procedure, and therefore will
invoke a function (procedure) in the receiving object that generates the desired results.
Message passing involves specifying the name of object, the name of the function
(message) and the information to be sent. Example:
Object
Information
Message
Object has a life cycle. They can be created and destroyed. Communication with an
object is feasible as long as it is alive.
Benefits of OOP
OOP offers several benefits to both the program designer and the user. Object-
Orientation contributes to the solution of many problems associated with the
development and quality of software products. The new technology promises greater
programmer productivity, better quality of software and lesser maintenance cost. The
principal advantages are:
Through inheritance, we can eliminate redundant code extend the use of existing
Classes.
We can build programs from the standard working modules that communicate
with one another, rather than having to start writing the code from scratch. This
leads to saving of development time and higher productivity.
The principle of data hiding helps the programmer to build secure program that
can not be invaded by code in other parts of a programs.
It is possible to have multiple instances of an object to co-exist without any
interference.
It is possible to map object in the problem domain to those in the program.
It is easy to partition the work in a project based on objects.
The data-centered design approach enables us to capture more detail of a model
can implemental form.
Object-oriented system can be easily upgraded from small to large system.
Message passing techniques for communication between objects makes to
interface descriptions with external systems much simpler.
Software complexity can be easily managed.
Application of OOP
OOP has become one of the programming buzzwords today. There appears to be a great
deal of excitement and interest among software engineers in using OOP. Applications of
OOP are beginning to gain importance in many areas. The most popular application of
object-oriented programming, up to now, has been in the area of user interface design
such as window. Hundreds of windowing systems have been developed, using the OOP
techniques.
Real-business system are often much more complex and contain many more objects
with complicated attributes and method. OOP is useful in these types of application
because it can simplify a complex problem. The promising areas of application of OOP
include:
Real-time system
Simulation and modeling
Object-oriented data bases
Hypertext, Hypermedia, and expertext
AI and expert systems
Neural networks and parallel programming
Decision support and office automation systems
CIM/CAM/CAD systems
The object-oriented paradigm sprang from the language, has matured into design, and has
recently moved into analysis. It is believed that the richness of OOP environment will
enable the software industry to improve not only the quality of software system but also
its productivity. Object-oriented technology is certainly going to change the way the
software engineers think, analyze, design and implement future system.
Introduction of C++
C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup
at AT&T Bell Laboratories in Murray Hill, New Jersey, USA, in the early 1980’s.
Stroustrup, an admirer of Simula67 and a strong supporter of C, wanted to combine the
best of both the languages and create a more powerful language that could support object-
oriented programming features and still retain the power and elegance of C. The result
was C++. Therefore, C++ is an extension of C with a major addition of the class
construct feature of Simula67. Since the class was a major addition to the original C
language, Stroustrup initially called the new language ‘C with classes’. However, later in
1983, the name was changed to C++. The idea of C++ comes from the C increment
operator ++, thereby suggesting that C++ is an augmented version of C.
C+ + is a superset of C. Almost all c programs are also C++ programs. However, there
are a few minor differences that will prevent a c program to run under C++ complier. We
shall see these differences later as and when they are encountered.
The most important facilities that C++ adds on to C care classes, inheritance, function
overloading and operator overloading. These features enable creating of abstract data
types, inherit properties from existing data types and support polymorphism, thereby
making C++ a truly object-oriented language.
Application of C++
C++ is a versatile language for handling very large programs; it is suitable for virtually
any programming task including development of editors, compilers, databases,
communication systems and any complex real life applications systems.
Since C++ allow us to create hierarchy related objects, we can build special
object-oriented libraries which can be used later by many programmers.
While C++ is able to map the real-world problem properly, the C part of C++
gives the language the ability to get closed to the machine-level details.
C++ programs are easily maintainable and expandable. When a new feature needs
to be implemented, it is very easy to add to the existing structure of an object.
It is expected that C++ will replace C as a general-purpose language in the near
future.
Program 1.10.1
This simple program demonstrates several C++ features.
Program feature
Like C, the C++ program is a collection of function. The above example contain only one
function main(). As usual execution begins at main(). Every C++ program must have a
main(). C++ is a free form language. With a few exception, the compiler ignore carriage
return and white spaces. Like C, the C++ statements terminate with semicolons.
Comments
C++ introduces a new comment symbol // (double slash). Comment start with a double
slash symbol and terminate at the end of the line. A comment may start anywhere in the
line, and whatever follows till the end of the line is ignored. Note that there is no closing
symbol.
The double slash comment is basically a single line comment. Multiline comments can
be written as follows:
// This is an example of
// C++ program to illustrate
// some of its features
The C comment symbols /*,*/ are still valid and are more suitable for multiline
comments. The following comment is allowed:
/* This is an example of
C++ program to illustrate
some of its features
*/
Output operator
Causes the string in quotation marks to be displayed on the screen. This statement
introduces two new C++ features, cout and <<. The identifier cout(pronounced as C out)
is a predefined object that represents the standard output stream in C++. Here, the
standard output stream represents the screen. It is also possible to redirect the output to
other output devices. The operator << is called the insertion or put to operator.
#include <iostream>
The #include directive instructs the compiler to include the contents of the file enclosed
within angular brackets into the source file. The header file iostream.h should be
included at the beginning of all programs that use input/output statements.
Namespace
Namespace is a new concept introduced by the ANSI C++ standards committee. This
defines a scope for the identifiers that are used in a program. For using the identifier
defined in the namespace scope we must include the using directive, like
Here, std is the namespace where ANSI C++ standard class libraries are defined. All
ANSI C++ programs must include this directive. This will bring all the identifiers defined
in std to the current global scope. Using and namespace are the new keyword of C++.
In C++, main () returns an integer value to the operating system. Therefore, every main ()
in C++ should end with a return (0) statement; otherwise a warning an error might occur.
Since main () returns an integer type for main () is explicitly specified as int. Note that
the default return type for all function in C++ is int. The following main without type and
return will run with a warning:
main ()
{
…………..
………….
}
More C++ Statements
Let us consider a slightly more complex C++ program. Assume that we should like to
read two numbers from the keyboard and display their average on the screen. C++
statements to accomplish this is shown in program 1.11.1
Int main()
Return 0;
} //end of example
Program 1.11.1
Variables
The program uses four variables number1, number2, sum and average. They are declared
as type float by the statement.
All variable must be declared before they are used in the program.
Input Operator
The statement
cin >> number1;
Is an input statement and causes the program to wait for the user to type in a number. The
number keyed in is placed in the variable number1. The identifier cin (pronounced ‘C in’)
is a predefined object in C++ that corresponds to the standard input stream. Here, this
stream represents the keyboard.
The operator >> is known as extraction or get from operator. It extracts (or takes) the
value from the keyboard and assigns it to the variable on its right fig 1.8. This
corresponds to a familiar scanf() operation. Like <<, the operator >> can also be
overloaded.
Cin >>
45.5
Keyboard
Fig
We have used the insertion operator << repeatedly in the last two statements for printing
results.
The statement
First sends the string “Sum = “ to cout and then sends the value of sum. Finally, it sends
the newline character so that the next output will be in the new line. The multiple use of
<< in one statement is called cascading. When cascading an output operator, we should
ensure necessary blank spaces between different items. Using the cascading technique,
the last two statements can be combined as follows:
The values are assigned from left to right. That is, if we key in two values, say, 10 and
20, then 10 will be assigned to munber1 and 20 to number2.
USE OF CLASS
char name[30];
Int age;
public:
void getdata(void);
void display(void);
};
void person :: getdata(void)
{
cout << “Enter name: “;
cin >> name;
cout << “Enter age: “;
cin >> age;
}
Void person : : display(void)
{
cout << “\nNameame: “ << name;
cout << “\nAge: “ << age;
}
Int main()
{
person p;
p.getdata();
p.display();
Return 0;
} //end of example
PROGRAM 1.12.1
The program define person as a new data of type class. The class person includes two
basic data type items and two function to operate on that data. These functions are called
member function. The main program uses person to declare variables of its type. As
pointed out earlier, class variables are known as objects. Here, p is an object of type
person. Class object are used to invoke the function defined in that class.
Class declaration
This approach is based on the concept of client-server model as shown in fig. 1.10. The
class definition including the member functions constitute the server that provides
services to the main program known as client. The client uses the server through the
public interface of the class.
Fig. 1.10 The client-server model
Member Function
Server
Class Definition
Client
Main function Program
Some systems such as Turboc C++ provide an integrated environment for developing
and editing programs
The file name should have a proper file extension to indicate that it is a C++
implementations use extensions such as .c,.C, .cc, .cpp and .cxx. Turboc C++ and
Borland C++ use .c for C programs and .cpp(C plus plus) for C++ programs. Zortech
C++ system use .cxx while UNIX AT&T version uses .C (capital C) and .cc. The
operating system manuals should be consulted to determine the proper file name
extension to be used.
CC example.C
At the UNIX prompt would compile the C++ program source code contained in the file
example.C. The compiler would produce an object file example.o and then automatically
link with the library functions to produce an executable file. The default executable
filename is a. out.
CC file1.C file2.o
The statement compiles only the file file1.C and links it with the previously compiled
file2.o file. This is useful when only one of the files needs to be modified. The files that
are not modified need not be compiled again.
Turbo C++ and Borland C++ provide an integrated program development environment
under MS DOS. They provide a built-in editor and a menu bar includes options such as
File, Edit, Compile and Run.
We can create and save the source files under the File option, and edit them under the
Edit option. We can then compile the program under the compile option and execute it
under the Run option. The Run option can be used without compiling the source code.
Summary
Software technology has evolved through a series of phases during the last five
decades.
POP follows top-down approach where problem is viewed as sequence of task to
be performed and functions are written for implementing these tasks.
POP has two major drawbacks:
Data can move freely around the program.
It does not model very well the real-world problems.
OOP was inventing to overcome the drawbacks of POP. It follows down -up
approach.
In OOP, problem is considered as a collection of objects and objects are instance
of classes.
Data abstraction refers to putting together essential features without including
background details.
Inheritance is the process by which objects of one class acquire properties of
objects of another class.
Polymorphism means one name, multiple forms. It allows us to have more than
one function with the same name in a program.
Dynamic binding means that the code associated with a given procedure is not
known until the time of the run time.
Message passing involves specifying the name of the object, the name of the
function and the information to be sent.
C++ is a superset of C language.
C++ ads a number of features such as objects, inheritance, function overloading
and operator overloading to C.
C++ supports interactive input and output features and introduces anew comment
symbol // that can be used for single line comment.
Like C programs, execution of all C++ program begins at main() function.
Keywords:
Questions
1. What are the major issues facing the software industry today?
2. What is POP? Discuss its features.
3. Describe how data are shared by functions in procedure-oriented programs?
4. What is OOP? What are the difference between POP and OOP?
5. How are data and functions organized in an object-oriented program?
6. What are the unique advantages of an object-oriented programming paradigm?
7. Distinguish between the following terms:
(a) Object and classes
(b) Data abstraction and data encapsulation
(c) Inheritance and polymorphism
(d) Dynamic binding and message passing
8. Describe inheritance as applied to OOP.
9. What do you mean by dynamic binding? How it is useful in OOP?
10. What is the use of preprocessor directive #include<iostream>?
11. How does a main () function in c++ differ from main () in c?
12. Describe the major parts of a c++ program.
13. Write a program to read two numbers from the keyboard and display the larger
value on the screen.
14. Write a program to input an integer value from keyboard and display on screen
“WELL DONE” that many times.
References:
1. Object –Oriented –Programming in C++ by E Balagurusamy.
2. Object –Oriented –Programming with ANSI & Turbo C++ by Ashok N. Kamthane.
3. OO Programming in C++ by Robert Lafore, Galgotia Publications Pvt. Ltd.
4. Mastering C++ By K R Venugopal, Rajkumar Buyya, T Ravishankar.
5. Object Oriented Programming and C++ By R. Rajaram.
6. Object –Oriented –Programming in C++ by Robert Lafore.
Subject: Object Oriented Programming using C++
Paper Code: 302
Arguments to a Function
Default Arguments
Constant Arguments
Calling Functions
Inline Functions
Scope Rules of Functions and Variables
Definition and Declaration of a Class
Summary
Keywords
Review Questions
Further Readings
INTRODUCTION
Functions are the building blocks of C++ programs where all the program activity
occurs. Function is a collection of declarations and statements.
#include<iostream.h>
include<conio.h>
void main()
{
void disp(); //function prototype
}
//function definition
void disp()
}
PROGRAM 4.1
In this Unit, we will also discuss Class, as important Data Structure of C++. A
Class is the backbone of Object-Oriented Computing. It is an abstract data type.
We can declare and define data as well as functions in a class. An object is a
replica of the class to the exception that it has its own name. A class is a data
type and an object is a variable of that type. Classes and objects are the most
important features of C++. The class implements OOP features and ties them together.
In C++, a function must be defined prior to it’s use in the program. The function definition
contains the code for the function. The function definition for display_message () in program 6.1
is given below the main () function. The general syntax of a function definition in C++ is shown
below:
Here, the type specifies the type of the value to be returned by the function. It may be
any valid C++ data type. When no type is given, then the compiler returns an integer value from
the function.
Argument list is a comma separated list of variables of a function through which the
function may receive data or send data when called from other function. When no parameters,
the argument list is empty as you have already seen in program 6.1. The following function
illustrates the concept of function definition :
void add()
int a,b,sum;
cin>>a>>b;
sum=a+b;
The above function add ( ) can also be coded with the help of arguments of
parameters as shown below:
int sum;
sum=a+b;
ARGUMENTS TO A FUNCTION
Arguments(s) of a function is (are) the data that the function receives when
called/invoked from another function.
void main ()
int N;
formal parameters
Semicolon here
return type
………………………….
………………………….
result = SUMFUN(X,N); //function declaration
}
//function SUMFUN() definition
No semicolon here
………………………….
………………………….
No semicolon here
DEFAULT ARGUMENTS
int calc(int U)
If (U % 2 = = 0)
return U+10;
Else
return U+2
cout<calc(CNT) <<M;
cout<<endl;
Void main ()
Pattern(‘*’);
Pattern (‘#’,4)’
Pattern (;@;,3);
CONSTANT ARGUMENTS
A C++ function may have constant arguments(s). These arguments(s) is/are treated
as constant(s). These values cannot be modified by the function.
For making the arguments(s) constant to a function, we should use the keyword const
as given below in the function prototype :
CALLING FUNCTIONS
(a) Value
(b) Reference
Call by Value: - In this method the values of the actual parameters (appearing in the
function call) are copied into the formal parameters (appearing in the function definition), i.e., the
function creates its own copy of argument values and operates on them. The following program
illustrates this concept :
//calculation of compound interest using a function
#include<iostream.h>
#include<conio.h>
#include<math.h> //for pow()function
Void main()
{
Float principal, rate, time; //local variables
Cout<<”\nPrincipal:”;
Cin>>principal;
Cout<<”\nRate of interest:”;
Cin>>rate;
Cin>>time;
Interest = p* (pow((1+r/100.0),t))-p;
It is useful when you want to change the original variables in the calling function by the called
function.
#include<iostream.h>
#include<conio.h>
void main()
clrscr();
int num1,num2;
cin>>num1>>num2;
cout<<endl<<”num2: “<<num2;
swap(num1,num2); //function call
cout<<endl<<”num2: “<<num2;
getch();
Int temp=a;
a=b;
b=temp;
INLINE FUNCTIONS
These are the functions designed to speed up program execution. An inline function is
expanded (i.e. the function code is replaced when a call to the inline function is made) in the line
where it is invoked. You are familiar with the fact that in case of normal functions, the compiler
have to jump to another location for the execution of the function and then the control is
returned back to the instruction immediately after the function call statement. So execution time
taken is more in case of normal functions. There is a memory penalty in the case of an inline
function.
inline function_header
{
body of the function
}
For example,
}
Void main()
cin>>num1>>num2;
An inline function definition must be defined before being invoked as shown in the above
example. Here min ( ) being inline will not be called during execution, but its code would be
inserted into main ( ) as shown and then it would be compiled.
If the size of the inline function is large then heavy memory pentaly makes it not so
useful and in that case normal function use is more useful.
1. Local Scope
2. Function Scope
3. File Scope
4. Class Scope
Local Scope:- A block in C++ is enclosed by a pair of curly braces i.e., ‘{‘ and ‘}’. The
variables declared within the body of the block are called local variables and can be used only
within the block. These come into existence when the control enters the block and get destroyed
when the control leaves the closing brace. You should note the variable(s) is/are available to all
the enclosed blocks within a block.
For example,
int x=100;
{ cout<<x<<endl;
Int x=200;
cout<<x<<endl;
int x=300;
cout<<x<<endl;
cout<<x<<endl;
}
Function Scope : It pertains to the labels declared in a function i.e., a label can be used
inside the function in which it is declared. So we can use the same name labels in different
functions.
For example,
int sum = 0;
sum = x+y+z;
cout<<sum;
sum = x+y+z;
cout<<sum;
Here the labels x, y, z and sum in two different functions add1 ( ) and add2 ( ) are
declared and used locally.
File Scope : If the declaration of an identifier appears outside all functions, it is available to all
the functions in the program and its scope becomes file scope. For Example,
int x;
cout<<n*n;
void main ()
int num;
…………...........
cout<<x<<endl;
cin>>num;
squaer(num);
…………...........
Here the declarations of variable x and function square ( ) are outside all the functions
so these can be accessed from any place inside the program. Such variables/functions are
called global.
Class Scope : In C++, every class maintains its won associated scope. The class members are
said to have local scope within the class. If the name of a variable is reused by a class member,
which already has a file scope, then the variable will be hidden inside the class. Member
functions also have class scope.
A class in C++ combines related data and functions together. It makes a data type
which is used for creating objects of this type.
Classes represent real world entities that have both data type properties
(characteristics) and associated operations (behavior).
Function declaration;
Function declaration;
};
Here, the keyword class specifies that we are using a new data type and is followed by the class
name.
In C++, the keywords private and public are called access specifiers. The data
hiding concept in C++ is achieved by using the keyword private. Private data and functions can
only be accessed from within the class itself. Public data and functions are accessible outside
the class also. This is shown below :
Class
Private
Public
Data hiding not mean the security technique used for protecting computer databases.
The security measure is used to protect unauthorized users from performing any operation
(read/write or modify) on the data.
The data declared under Private section are hidden and safe from accidental
manipulation. Though the user can use the private data but not by accident.
The functions that operate on the data are generally public so that they can be
accessed from outside the class but this is not a rule that we must follow.
(i) Class definition. It describes both data members and member functions.
(ii) Class method definitions. It describes how certain class member functions
are coded.
We have already seen the class definition syntax as well as an example.
In case of inline function the compiler inserts the code of the body of the function at
the place where it is invoked (called) and in doing so the program execution is faster but
memory penalty is there.
Name_of_the_class :: function_name
The syntax for a member function definition outside the class definition is :
{
body of function
}
Here the operator::known as scope resolution operator helps in defining the member
function outside the class. Earlier the scope resolution operator(::)was ised om situations where
a global variable exists with the same name as a local variable and it identifies the global
variable.
The objects of a class are declared after the class definition. One must remember
that a class definition does not define any objects of its type, but it defines the properties of a
class. For utilizing the defined class, we need variables of the class type. For example,
will create two objects ob1 and ob2 of largest class type. As mentioned earlier, in
C++ the variables of a class are known as objects. These are declared like a simple variable
i.e., like fundamental data types.
In C++, all the member functions of a class are created and stored when the class is
defined and this memory space can be accessed by all the objects related to that class.
Memory space is allocated separately to each object for their data members. Member
variables store different values for different objects of a class.
Object 1 Object 2
objects declared
After defining a class and creating a class variable i.e., object we can access the data
members and member functions of the class. Because the data members and member
functions are parts of the class, we must access these using the variables we created. For
functions are parts of the class, we must access these using the variable we created. For
Example,
Class student
private:
char reg_no[10];
` char name[30];
int age;
char address[25];
public :
void init_data()
- - - - - //body of function
- - - - -
void display_data()
};
- - - - -
- - - - -
- - - - -
- - - - -
Here, the data members can be accessed in the member functions as these have private
scope, and the member functions can be accessed outside the class i.e., before or after the
main() function.
Data members and member functions of a class in C++, may be qualified as static.
We can have static data members and static member function in a class.
common to the whole class. The static data member differs from an ordinary data
member in the followingways :
(i) Only a single copy of the static data member is used by all the objects.
(ii) It can be used within the class but its lifetime is the whole program.
For making a data member static, we require :
Class student
};
We can also initialize the static data member at the time of its definition as:
the static members of a class. We can do so by putting the keyword static before the name of
the function while declaring it for example,
Class student
public :
Cout<<”count=”<<count<<”\n”;
}
};
Here we have put the keyword static before the name of the function shwocount ().
In C++, a static member function fifers from the other member functions in the following
ways:
(i) Only static members (functions or variables) of the same class can be
accessed by a static member function.
(ii) It is called by using the name of the class rather than an object as given
below:
Name_of_the_class :: function_name
For example,
student::showcount();
FRIEND CLASSES
class ONE
………………………
…………….
public:
……………..
……………..
friend class TWO; // class TWO declared as friend of class ONE
};
Now from class TWO , all the member of class ONE can be accessed.
Summary
In this Unit, we have discussed the concept of function in c++, its declaration and
definition. we have also discussed the concept of class, its declaration and definition. It
also explained the ways for creating objects, accessing the data members of the class.
We have seen the way to pass objects as arguments to the functions with call by value
and call by reference.
Keywords
Review Questions
Q. 2. How are the argument data types specified for a C++ function? Explain with
Suitable example.
Q. 4. What is recursion? While writing any recursive function what thing(s) must be
taken care of ?
Q. 5. What is inline function? When will you make a function inline and why ?
Q. 8. Define data members , member function, private and public members with
example.
Adm_no integer
Sname 20 characters
Total float
calculate total.
screen.
Further Readings
It is defined like other member functions of the class, i.e., either inside the class
definition or outside the class definition.
#include <iostram.h>
#include <conio.h>
Class rectangle
{
private :
public:
length-10.0;
breadth=20.5;
float area()
return (length*breadth);
};
void main()
clrscr();
getch();
Type Of Constructor
There are different type of constructors in C++.
Overloaded Constructors
Besides performing the role of member data initialization, constructors are no
different from other functions. This included overloading also. In fact, it is very common to find
overloaded constructors. For example, consider the following program with overloaded
constructors for the figure class :
#include<iostream.h>
#include<conio.h>
#include<math.h>
Private:
Char shape[10];
Public:
radius=r;
strcpy
Side1=s1;
Side2=s2;
side1=s1;
side2=s2;
side3=s3;
radius=0.0;
strcpy(shape,”triangle”);
{
float ar,s;
if(radius==0.0)
if (side3==0.0)
ar=side1*side2;
else
ar=3.14*radius*radius;
};
Void main()
Clrscr();
Rectangle.area();
Triangle.area();
Copy Constructor
It is of the form classname (classname &) and used for the initialization of an
object form another object of same type. For example,
Class fun
Float x,y;
Public:
{
x = a;
y = b;
X = f.x;
Y = f.y;
}
Cout<<””<<y<<end1;
};
Here we have two constructors, one copy constructor for copying data value of a fun
object to another and other one a parameterized constructor for assignment of initial values
given.
#include <iostream.h>
#include <conio.h>
Class employee
Int empl_no;
Float salary;
Public:
{}
Empl_no=empno;
Salary=s;
Empl_no=emp.empl_no;
Salary=emp.salary;
Cout<<”\nEmp.No:”<<empl_no<<”salary:”<<salary<<end1;
};
Void main()
int eno;
float sal;
clrscr();
cin>>eno>>sal;
cin>eno>>sal;
employee obj2(eno,sal); //dynamic initialization of object
obj3.display();
getch();
float i(2.5), j(7.8); //I,j, initialized with valurs 2.5 and 7.8
Class add
{
Private:
Public:
Void sum();
Void display();
};
//Default constructor definition
num1=n1;
num2=n2;
num3=n0;
}
Void add ::sum()
{
Num3=num1+num2;
}
Void add::display ()
{
Cout<<”\nThe sum of two numbers is “<<num3<<end1;
}
Now using the above code objects of type add can be created with no initial values, one
initial values or two initial values. For Example,
Here, obj1 will have values of data members num1=0, num2=0 and
num3=0
Obj2 will have values of data members num1=5, num2=0 and num3=0
Obj3 will have values of data members num1=10, num2=20 and num3=0
Then the default argument constructor can be invoked with either two or one or no
parameter(s).
Without argument, it is treated as a default constructor-using these two forms together causes
ambiguity. For example,
add :: add()
or add :: add(int=0,int=0)
(i) These are called automatically when the objects are created.
(ii) All objects of the class having a constructor are initialized before some use.
(iii) These should be declared in the public section for availability to all the
functions.
(iv) Return type (not even void) cannot be specified for constructors.
(v) These cannot be inherited, but a derived class can call the base class
constructor.
(vi) These cannot be static.
(vii) Default and copy constructors are generated by the compiler wherever
required. Generated constructors are public.
(viii) These can have default arguments as other C++ functions.
(ix) A constructor can call member functions of its class.
(x) An object of a class with a constructor cannot be used as a member of a
union.
(xi) A constructor can call member functions of its class.
(xii) We can use a constructor to create new objects of its class type by using the
syntax.
Name_of_the_class (expresson_list)
For example,
Or even
(xiii) The make implicit calls to the memory allocation and deallocation operators
new and delete.
(xiv) These cannot be virtual.
-name_of_the_class()
So the name of the class and destructor is same but it is prefixed with a ~
(tilde). It does not take any parameter nor does it return any value. Overloading a
destructor is not possible and can be explicitly invoked. In other words, a class can have only
one destructor. A destructor can be defined outside the class. The following program illustrates
this concept :
#include<iostream.h>
#include<conio.h>
class add
private :
int num1,num2,num3;
public :
void sum();
void display();
~ add(void); //Destructor
};
Num1=num2=num3=0;
{
num1=n1;
num2=n2;
num3=0;
Void add::sum()
num3=num1+num2;
Void add::display ()
void main()
Obj2.sum();
Obj3.sum();
cout<<”\nUsing obj1 \n”;
obj2.display();
obj3.display();
(i) These are called automatically when the objects are destroyed.
(ii) Destructor functions follow the usual access rules as other member functions.
(iii) These de-initialize each object before the object goes out of scope.
(iv) No argument and return type (even void) permitted with destructors.
(v) These cannot be inherited.
(vi) Static destructors are not allowed.
(vii) Address of a destructor cannot be taken.
(viii) A destructor can call member functions of its class.
(ix) An object of a class having a destructor cannot be a member of a union.
For defining an additional task to an operator, we must mention what is means in relation
to the class to which it (the operator) is applied. The operator function helps us in doing so.
Operator Operator_name
For example, suppose that we want to declare an Operator function for ‘=’. We can
do it as follows:
operator =
A Binary Operator can be defined either a member function taking one argument or a
global function taking one arguments. For a Binary Operator X, a X b can be interpreted as either
an operator X (b) or operator X (a, b).
For a Prefix unary operator Y, Ya can be interpreted as either a.operator Y ( ) or Operator Y (a).
For a Postfix unary operator Z, aZ can be interpreted as either a.operator Z(int) or Operator
(Z(a),int).
The operator functions namely operator=, operator [ ], operator ( ) and operator? must be non-
static member functions. Due to this, their first operands will be lvalues.
An operator function should be either a member or take at least one class object argument. The
operators new and delete need not follow the rule. Also, an operator function, which needs to
accept a basic type as its first argument, cannot be a member function. Some examples of
declarations of operator functions are given below:
class P
{
P operator ++ (int);//Postfix increment
P operator ++ ( ); //Prefix increment
P operator || (P); //Binary OR
}
Class time
{
int r;
int i;
public:
friend time operator + (const time &x, const time &y );
// operator overloading using friend
time ( ) { r = i = 0;}
time (int x, int y) {r = x; i = y;}
};
time operator + (const time &x, const time &y)
{
time z;
z.r = x.r +y.r;
z.i = x.i + y.i;
return z;
}
main ( )
{
time x,y,z;
x = time (5,6);
y = time (7,8);
z = time (9, 10);
z = x+y; // addition using friend function +
}
Class abc
{
char * str;
int len ; // Present length of the string
int max_length; // (maximum space allocated to string)
public:
abc ( ); // black string of length 0 of maximum allowed length of size 10.
abc (const abc &s ) ;// copy constructor
~ abc ( ) {delete str;}
int operator = = (const abc &s ) const; // check for equality
abc & operator = (const abc &s );
// overloaded assignment operator
friend abc operator + (const abc &s1, const abc &s2);
} // string concatenation
abc:: abc ()
{
max_length = 10;
str = new char [ max_length];
len = 0;
str [0] = ‘\0’;
}
abc :: abc (const abc &s )
{
len = s. len;
max_length = s.max_length;
str = new char [max_length];
strcpy (str, s.str); // physical copying in the new location.
}
[ Not: Please note the need of explicit copy constructor as we are using
pointers. For example, if a string object containing string “first” is to be used to
initialise a new string and if we do not use copy constructor then will cause:
Str1
F I R S T ‘\
Str2
That is two pointers pointing to one instance of allocated memory, this will create
problem if we just want to modify the current value of one of the string only. Even
destruction of one string will create problem. That is why we need to create separate
space for the pointed string as:
Str1 F I R S T ‘\
Str2 F I R S T ‘\
Thus, we have explicitly written the copy constructor. We have also written the explicit
destructor for the class. This will not be a problem if we do not use pointers.
abc :: ~ abc ( )
{
delete str;
}
abc & abc :: operator = (const abc &s )
{
if (this ! = &s) // if the left and right hand variables are different
{
len = s.len;
max_length = s.max-length;
delete str; // get rid of old memory space allocated to this string
str = new char [max_length]; // create new locations
strcpy (str, s.str); // copy the content using string copy function
}
return *this;
}
// Please note the use of this operator which is a pointer to object that
invokes the call
to this assignment operator function.
class student
{
char name;
int rollno;
public:
student ( ) {name = new char [20];}
~ student ( ) {delete [ ] name;}
};
int f ( )
{ student S1, S2;
cin >> S1;
cin >> S2;
S1 = S2;
}
Now, the problem is that after the execution of f ( ), destructors for S1& S2 will be
executed. Since both S1 & S2 point to the same storage, execution of destructor twice
will lead to error as the storage being pointed by S1 & S2 were disposed off during
the execution of destructor for S1 itself.
TYPE CONVERSIONS
We have overloaded several kinds of operators but we haven’t considered the assignment
operator (=). It is a very special operator having complex properties. We know that = operator
assigns values form one variable to another or assigns the value of user defined object to
another of the same type. For example,
int x, y ;
x = 100;
y = x;
This statement used in program 11.2 earlier, assigns the result of addition, which is of
type time to object t3 also of type time.
So the assignments between basic types or user defined types are taken care by the
compiler provided the data type on both sides of = are of same type.
But what to do in case the variables are of different types on both sides of the =
operator? In this case we need to tell to the compiler for the solution.
Three types of situations might arise for data conversion between different types :
This type of conversion is very easy. For example, the following code segment
converts an int type to a class type.
class distance
int feet;
int inches;
public:
.....
.....
feet = dist/12;
inches = dist%12;
};
After the execution of above statements, the feet member of dist1 will have a value of 1 and
inches member a value of 8, meaning 1 feet and 8 inches.
A class object has been used as the left hand operand of = operator, so the type
conversion can also be done by using an overloaded = operator in C++.
For conversion from a basic type to class type, the constructors can be used. But
for conversion from a class type to basic type constructors do not help at all. In C++, we have to
define an overloaded casting operator that helps in converting a class type to a basic type.
The syntax of the conversion function is given below:
Operator typename()
.......
....... //statements
Here, the function converts a class type data to typename. For example, the operator
float ( ) converts a class type to type float, the operator int ( ) converts a class type object to
type int. For example,
for(int i=0;i<m;i++)
sum=sum+a[i][j]*a[i][j];
}
Here, the function finds the norm of the matrix (Norm is the square root of the sum of the
squares of the matrix elements). We can use the operator float ( ) as given below :
or
where arr is an object of type matrix. When a class type to a basic type conversion is
required, the compiler will call the casting operator function for performing this task.
Suppose obj1 is an object of class studdata and obj2 is that of class result. We are
converting the class studdata data type to class result type data and the value is assigned to
obj2. Here studdata is known as source class and result is known as the destination class.
Keywords
Constructor: Constructors is special member functions of classes that are used to
construct class objects.
Destructor: destructors are special member functions of classes that are used to
destroy class objects.
Review Questions
Q. 1. What is the use of a constructor function in a class? Give a suitable example of a
constructor function in a class.
Q. 2. Design a class having the constructor and destructor functions that shiukd display
the number of object being created or destroyed of this class type.
Q. 3. Write a C++ program, to find the factorial of a number using a constructor and a
destructor ( generating the message “you have done it” )
Q. 4. Define a class “string” with members to initialize and determine the length of the
string. Overload the operators ‘+’ and ‘+=’ for the class “string”.
Further Readings
1. Rambagh J. , “ Object Oriented Modeling and Design” , Prentice Hall of India ,
New Delhi.
2. E. Balagrusamy, “Object Oriented Programming with C++”, Tata McGraw Hill.
Subject: Object Oriented Programming using C++
4.1 INTRODUCTION
CONCEPT OF INHERITANCE
PUBLIC INHERITANCE
PROTECTED INHERITANCE
MULTIPLE INHERITANCE
NESTESD CLASSES
DYNAMIC MEMORY ALLOCATION/ DEALLOCATION OPERATORS USING
New, Delete
THE THIS POINTER
VIRTUAL FUNCTIONS
POLYMORPHIM
STATIC POLYMORPHISM OR COMPILE TIME POLYMORPHISM
DYNAMIC POLYMORPHISM
STATIC AND DYNAMIC BINDING
Summary
Keywords
Review Questions
Further Readings
Introduction
Inheritance allows a class to include the members of other classes without repetition
of members. There were three ways to inheritance means, “public parts of super class
remain public and protected parts of super class remain protected.” Private Inheritance
means “Public and Protected Parts of Super Class remain Private in Sub-Class”.
Protected Inheritance means “Public and Protected Parts of Superclass remain protected
in Subclass.
A pointer is a variable which holds a memory address. Any variable declared in a
program has two components:
(i) Address of the variable
(ii) Value stored in the variable.
For example,
int x = 386;
The above declaration tells the C++ compiler for :
(a) Reservation of space in memory for storing the value.
(b) Associating the name x with his memory location.
(c) Storing the value 386 at this location.
It can be represented with the following figure :
location name x
value at location 386
location number 3313
Here, the address 3313 is assumed one, it may be some other address also.
The pointers are one of the most useful and strongest features of C++. There are
three useful reason for proper utilization of pointer :
(i) The memory location can be directly accessed and manipulated.
(ii) Dynamic memory allocation is possible.
(iii) Efficiency of some particular routines can be improved.
CONCEPT OF INHERITANCE
class Employee
{ public:
char* name;
int age;
char* address;
int salary;
char*department;
int id;
};
Class Manager
{ public:
char* name;
int age;
char* address;
int salary;
char*department;
int id;
employee* team_members; //He heads a group of employees
int level; // his position in hierarchy of the organisation
.
.
.
.
};
Now, without repeating the entire information of class Employee in class Manager,
we can declare the Manager class as follows:
The latest declaration of class Manager is the same as that of its previous one, with
the exception that we did not repeat the information of class Employee explicitly.
This is what is meant by the Application of inheritance mechanism. Please note
that in the above example, Employee is called Base Class and Manager is called
Derived Class.
SINGLE INHERITANCE
In this Section, you will learn the ways of deriving a class from single class. So,
there will be only one base class for the derived class.
Private Inheritance
All the public parts of class A and all the protected parts of class A, become
private members/parts of the derived class C in class C. No private member of
class A can be accessed by class C. To do so, you need to write public or private
functions in the Base class. A public function can be accessed by any object,
however, private function can be used only within the class hierarchy that is class
A and class C and friends of these classes in the above cases.
Public Inheritance
Consider the following classes:
class A{/*. ..... */};
class E: public A
{ /*
:
:
:
};
Now, all the public parts of class A become public in class E and protected part of
A become protected in E
Now, all the public and protected parts of class A become protected in class E.
class closed_shape
{
public:
.
.
.
}
class circle: public closed_shape
// circle is derived in public access mode from class
// closed-shape
{
float x, y; // Co-ordinates of the centre of the circle
float radius;
public:
.
.
.
.
}
MULTIPLE INHERITANCE
A class can have more than one direct base classes.
.
.
.
.
*/
};
This is called Multiple Inheritance. If a class is having only one base class, then it is
known as single inheritance. In the case of Class C, other than the operations
specified in it, the union of operations of classes A and B can also be applied.
Nestesd Classes
A class may be declared as a member of another class. Consider the following:
Class M1
{
int n;
public:
int m;
};
class M2
{
int n;
public:
int m;
};
class M3
{ M1 N1;
public:
M2 N2;
};
Now, N1 and N2 are nested classes of M3. M3 can access only public members of
N1
and N2. A nested class is hidden in the lexically enclosing class.
New Operator
char * cptr
The above statements allocate 1 byte and assigns the address to cptr.
The following statement allocates 21 bytes of memory and assigns the starting address to cptr :
char * cptr;
We can also allocate and initialize the memory in the following way :
Where value is the value to be stored in the newly allocated memory space and it must also be
of the type of specified data_type. For example,
Delete Operator
delete_pointer_variable;
For example,
delete cptr;
We know that while defining a class the space is allocated for member functions
only once and separate memory space is allocated for each object, as shown in figure
Member func Member func Member func 3()
Object 1 object 2
With the above shown allocation there exists a serious problem that is which object’s data
member is to be manipulated by any member function. For example, if memberfunc2( ) is
responsible for modifying the value of datamember1 and we are interested in modifying the
value of datamember1 of object3. In the situation like it, how to decide the manipulation of
which object’s datamember1? The this pointer is an answer to this problem. The this is a
pointer that points to that object using which the function is called. The This pointer is
automatically passed to a member function when it is called. The following program illustrates
the above mentioned concept :
#include<iostream.h>
#include<string.h>
class per
char name[20];
float saralry;
public :
per (char *s,float a)
{ if (x.salary> =salary)
return &x;
else
return this;
void display()
cout<<”name : “<<name<<’\n’;
cout<<”salar :”<<salary<<’\n’;
}
};
Void main ()
Name : REEMA
Salary : 10000
Name :KRISHANAN
Salary : 20000
Here, the first call to the function GR returns reference to the object P1 and the second
call returns reference to the object P2.
VIRTUAL FUNCTIONS
Polymorphism is a mechanism that enables same interface functions to work
with the whole class hierarchy. Polymorphism mechanism is supported in C++ by
the use of virtual functions. The concept of virtual function is related to the concept
of dynamic binding. The term Binding refers to binding of actual code to a function
call. Dynamic binding also called late binding is a binding mechanism in which the
actual function call is bound at run-time and it is dependent on the contents of
function pointer at run time. It meant that by altering the content of function
pointers, we may be able to call different functions having a same name but
different code, that is demonstrating polymorphic behaviour.
Polymorphim
Polymorphism means ‘one name multiple forms’. Runtime polymorphism can
be achieved by using virtual functions. The polymorphism implementation in C++ can be
shown as in figure.
Polymorphism
Overloading of Overloading of
Virtual functions
Function( s) Operator (s)
When the function volume ( ) is invoked, the passed parameters determine which one to be
executed. This resolution takes place at compile time.
DYNAMIC POLYMORPHISM
It means change of form by entity depending on the situation. A function is said to exhibit
dynamic polymorphism if it exists in various forms, and the resolution to different function calls
are made dyanamically during execution time. This feature makes the program more flexible as
a function can be called, depending on the context.
Statically bound functions do not require run-time search, while the dynamic function
calls need it. But in case of dynamic binding, the function calls are resolved at execution time
and the user has the flexibility to alter the call without modifying the source code.
For a programmer, efficiency and performance are more important, but to the user,
flexibility and maintainability are of primary concern. So a trade-off between the efficiency and
flexibility can be made.
Summary
In this Unit, you have been exposed to the concepts of base class and derived
classes. A derived class is a class which includes the member of another class.
This concept is also known as inheritance. When a derived class has more than
one direct base class, then it is called Multiple Inheritance. There were three types
of inheritance. We can also declare classes as members of another class. We
have also touched on the concept of polymorphism.
Keywords
Inheritance:- Inheritance is a mechanism of reusing and extending existing classes
without modifying them.
Polymorphism:- Polymorphism is a mechanism that enables same interface
functions to work with the whole class hierarchy.
Review Questions
Further Readings
Unit structure
Introduction
C++ streams
C++ streams classes
Unformatted I/O Operations
Formatted console I/O Operations
Managing output with manipulators
Design Our Own Manipulators
5.1 Introduction:
C++ supports two complete I/O systems: the one inherited from C and the object-
oriented I/O system defined by C++ (hereafter called simply the C++ I/O system). Like
C-based I/O, C++'s I/O system is fully integrated. The different aspects of C++'s I/O
system, such as console I/O and disk I/O, are actually just different perspectives on the
same mechanism.Every program takes some data as input and generates processed data
as output following the input-process-output cycle.C++ supports all of C’s rich set of I/O
functions that can be used in the C++ programs.But these are restrained from using due to
two reasons ,first I/O methods in C++ supports the concept of OOP and secondly I/O
methods in c can not handle the user defined data types such as class objects.C++ uses
the concept of streams and stream classes to implement its I/O operation with the console
and disk fils.
ios
pointer
input output
iostream
As in figure 5.1 ios is the base class for istream(input stream) and ostream(output
stream) which are base classes for iostream(input/output stream).The class ios is declared
as the virtual base class so that only one copy of its members are inherited by the
iostream.
The class ios provides the basic support for formatted and unformatted input/output
operations.The class istream provides the facilities for formatted and unformatted input
while the class ostream(through inheritance) provides the facilities for formatted
output.The class iostream provides the facilities for handling both input output
streams.Three classes namely istream_withassign, ostream_withassign and
iostream_withassign add assignment operators to these classes.
Table 5.1 Stream classes for console operations
ios(General input/output Contains basic facilities that are ued by all other input and
stream class) output classes
Also contains a pointer to buffer object(streambuf object)
Declares constants and functions that are necessary for
handling formatted input and output operations
iostream (input/output Inherits the properties of ios stream and ostream through
stream) multiple inheritance and thus contains all the input and output
functions
Example
Char c;
cin.get( c ) //get a character from the keyboard and assigns it to c
while( c!=’\n’)
{ cout<< c; //display the character on screen
cin.get( c ) //get another character
}
this code reads and display a line of text. The operator >> can be used to read a character
but it will skip the white spaces and newline character.The above while loop will not
work properly if the statement
cin >> c;
is used in place of cin.get ( c );
The get(void) version is used as follows:
…………..
char c;
c= cin.get();
…………
The value returned by the function get() is assigned to the variable c.
The function put(), a member of ostream class can be used to output a line of text,
character by character. For example
cout.put(‘x’);
displays the character x and
cout.put(ch);
while ( c 1=’\n’ )
{ cout.put( c);
count++;
cin.get( c );
}
cout<< “\n Number of characters =” <<count <<”\n”;
return 0;
Input
Object oriented programming
Output
Object oriented programming
Number of characters=27
char name[20];
cin.getline(name,20);
Assume that we have given the following input through key board:
Bjarne Stroustrup<press Return>
This input will be read correctly and assigned to the character array name.Let us suppose
the input is as follows:
Object Oriented Programming<press Return>
In this case ,the input will be terminated after reading the following 19 characters
Object Oriented Pro
Remember ,the two blank spaces contained in the string are also taken into
account.Strings cen be read using the operator >> as follows
cin>>name;
But remember cin can read strings that do not contain white spaces.This means that cin
can read just one word and not a series of words such as “Bjarne Stroustrup”.But it can
read the following string correctly:
Bjarne_Stroustrup
After reading the string ,cin automatically adds the terminating null character to the
character array.
The program 5.2 demonstrates the use of >> and getline() for reading the strings.
Program 5.2
The write() function displays an entire line and has the following form:
cout.write(line,size)
The first argument line represents the name of the string to be displayed and the second
argument size indicates the number of characters automatically when the null character is
encountered.If the size is greater than the length of line, then it displays beyond the
bound of line.Program5.3 illustrates how write() method displays a string
Program 5.3
{
char * string1=”C++”;
char * string2 =”Programming”;
int m=strlen(string1);
int n =strlen(string2);
for (int i=1;i<n;i++)
{
cout.write(string2,i);
cout<<”\n”;
}
for (i<n;i>0;i--)
{
cout.write(string2,i);
cout<<”\n”;}
//concatenating strings
cout.write(string1,m).write(string2,n);
cout<<”\n”;
//crossing the boundary
cout.write(string1,10);
return 0;
output
P
Pr
Pro
Prog
Progr
Progra
Program
Programm
Programmi
Programmin
Programming
Programmin
Programmi
Programm
Program
Progra
Progr
Prog
Pro
Pr
P
C++ Programming
C++ Progr
Function Task
Setf() To specify format flags that can control the form of output
display(such as left-justification and right-justification)
Manipulators are special functions that can be included in the I/O statements to alter the
format parameter of stream .Table 5.3 shows some important manipulator functions that
are frequently used. To access these manipulators, the file iomanip should be included in
the program.
Table 5.3 Manipulators
setw() width()
setprecision() precision()
setfill() fill()
setiosflags() setf()
resetiosflags() unsetf()
In addition to these standard library manipulators we can create our own manipulator
functions to provide any special output formats.
The value 543 is printed right justified in the first five columns.The specification
width(5) does not retain the setting for printing the number 12.this can be improved as
follows:
cout.width(5);
cout<<543;
cout.width(5);
cout<<12<<”\n”;
This produces the following output:
5 4 3 1 2
The field width should be specified for each item.C++ never truncate the values and
therefore,if the specified field width is smaller than the size of the value to be
printed,C++ expands the field to fit the value.program 5.4 demonstrates how the function
width() works.
Program 5.4
cout.width(15);
cout<<”Total Value”<<”\n”;
int sum=0;
for(int i=0;i<4 ;i++)
{
cout.width(5);
cout<<items[i];
cout.width(8);
cout<<cost[i];
}
The output of program 5.4 would be
1 2 3
Program 5.5 shows how the function width() and precision() are jointly used to control
the output format.
Program 5.5
cout<<”sqrt_of _value”<<”\n”;
for (int n=1;n<=5;n++)
{
cout.width(8);
cout<<n;
cout.width(13);
cout<<sqrt(n)<<”\n”;
}
cout<<”\n precision set to 5 digits\n\n”;
cout.precision(5);
cout<<”sqrt(10) = “ <<sqrt(10)<<”\n\n”;
cout.precision(0);
1 1
2 1.41
3 1.73
4 2
5 2.24
* * * * * * 5 2 5 0
Financial institutions and banks use this kind of padding while printing cheques so that
no one can change the amount easily.Like precision (),fill()
Stays in effect till we change it.As shown in following program
Program 5.6
#include<iostream>
using namespace std;
int main()
{ cout.fill(‘<’);
cout.precision(3);
for(int n=1;n<=6;n++)
{
cout.width(5);
cout<<n;
cout.width(10);
cout<<1.0/float(n)<<”\n”;
if(n==3)
cout.fill(‘>’);
}
cout<<”\nPadding changed \n\n”;
cout.fill(‘#’); //fill() reset
cout.width(15);
cout<<12.345678<<”\n”;
return 0;
}
The output will be
<<<<1<<<<<<<<<1
<<<<2<<<<<<<<0.5
<<<<3<<<<<<0.333
>>>>4>>>>>>0.25
>>>>5>>>>>>>0.2
PADDING CHANGED
#########12.346
cout.fill(‘*’);
cout.setf(ios::left,ios::adjustfield);
cout.width(15);
cout<<”table1”<<”\n”;
This will produce the following output:
T A B L E 1 * * * * * * * *
The statements
cout.fill(‘*’);
cout.precision(3);
cout.setf(ios::internal,ios::adjustfield);
cout.setf(ios::scientific,ios::floatfield);
cout.width(15);
cout<<-12.34567<<”\n”;
Will produce the following output:
- * * * * * 1 . 2 3 5 e + 0 1
follows:
cout<<setw(10)<<setiosflags(ios::left)<<12345;
One statement can be used to format output for two or more values.For example, the
statement
cout<<setw(5)<<setprecision(2)<<1.2345
<<setw(10)<<setprecision(4)<<sqrt(2)<<setw(15)<<setiosflags(ios::scientific)<<sqrt(3);
<<endl;
will print all the three values in one line with the field sizes of 5,10,15 respectively.
The following program illustrates the formatting of the output values using both
manipulators and ios functions.
Program 5.7
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
cout.setf(ios::showpoint);
cout<<setw(5)<<”n”<<setw(15)<<”inverse of n”<<setw(15)<<”sum of terms”;
double term,sum=0;
cout<<setw(5)<<n<<setw(14)<<setprecision(4) <<setiosflags(ios::scientific)<<term
<<setw(13)<<resetioflags(ios::scientific) <<sum<<endl;
}
return 0;
}
Program 5.8
#include <iostream>
#include <iomanip>
using namespace std;
ostream ¤cy (ostream & output)
{
output<< “Rs”;
return output;
}
ostream & form (ostream &output)
{
output.set(ios::showpos);
output.setf(ios::showpoint);
output.fill(‘*’);
output.precision(2);
output<<setiosflags(ios::fixed)<<setw(10);
return output;
}
int main()
{
cout<<currency<<form<<7864.5;
return 0;
}
the output of program is
Rs**+7864.50
In the program form represents a complex set of format functions and manipulators.
Summary
5.1.A stream is a sequence of bytes and serves as a source or destination for an I/O data.
The source stream that provides data to the program is called as input
stream and thedestination stream that receives output from the program is called
the output stream.
The C++ I/O system contains a hierarchy of stream classes used for input
and outputoperations.These classes are declared in the header file ‘iostream’.
cin represents the input stream connected to standard input device and cout
representsthe output stream connected to standard output device.
The >> operator is overloaded in the istream class as an extraction operator and the
<< operator is overloaded in the ostream class as an insertion operator.
We can read and write a line of text more efficiently using the line
oriented I/Ofunctions getline() and write() respectively.
The header file iomanip provides a set of manipulator functions to
manipulate outputformats.
Key Terms
adjustfield output stream
console I/O operations precision()
fill() put()
flags setfill()
get() setiosflags()
getline() setw()
ios write()
iostream
ostream
Exercises
What is a stream?
Describe briefly the features of I/O system supported by C++.
How is cout able to display various types of data without any special instructions?
5.4.Why it is necessary to include the file iostream in all our programs?
Unit Structure
6.1Introduction
6.2File stream classes
6.3 Steps of file operations
6.4Finding end of file
6.5File opening modes
6.6File pointers and manipulators
6.7Sequential input and output operations
Error handling functions
Command Line argument
6.1 Introduction :-
When a large amount of data is to be handled in such situations floppy disk or hard
disk are needed to store the data .The data is stored in these devices using the concept of
files. A file is a collection of related data stored in a particular area on a disk. Programs
can be designed to perform the read and write operations on these files .The I/O system
of C++ handles file operations which are very much similar to the console input and
output operations .It uses file streams as an interface between the programs and files. The
stream that supplies data to the program is called input stream and the one that receives
data from the program is called output stream. In other words input stream extracts data
from the file and output stream inserts data to the file. The input operation involves the
creation of an input stream and linking it with the program and input file. Similarly, the
output operation involves establishing an output stream with the necessary links with the
program and output file.
Input Streams
Output stream
Figure 6.1 File Input and output stream
ios
fstream file
fstream base
Class Contents
filebuf Its purpose is to set the file buffers to read and write. Contains
Openprot constant used in the open() of file stream classes.Also
contain close() and open() as members.
The filename is a string of characters that makeup a valid filename for the operating
system. It may contain two parts ,primary name and optional period with extension.
Examples are Input.data, Test.doc etc. For opening a file firstly a file stream is
created and then it is linked to the filename.A file stream can be defined using the classes
ifstream, ofstream and fstream that contained in the header file fstream.The class to be
used depends upon the purpose whether the write data or read data operation is to be
performed on the file.A file can be opened in two ways:
(a) Using the constructor function of class.
(b) Using the member function open() of the class.
The first method is useful only when one file is used in the stream.The second method is
used when multiple files are to be managed using one stream.
…………………..
……………….
ofstream outfile (“salary”); //creates outfile and connects salary to it
………………
…………………..
Program 2
………………
……………
ifstream infile (“salary”); //creates infile and connects salary to it
………………..
………………….
The connection with a file is closed automatically when the stream object expires i.e
when a program terminates.In the above statement ,when the program 1 is terminated,the
salary file is disconnected from the outfile stream.The same thing happens when program
2 terminates.
Instead of using two programs,one for writing data and another for reading data ,a single
program can be used to do both operations on a file.
…………
…………….
outfile.close(); //disconnect salary from outfile and connect to infile
ifstream infile (“salary”);
………….
……………
infile.close();
The following program uses a single file for both reading and writing the data .First it
take data from the keyboard and writes it to file.After the writing is completed the file is
closed.The program again opens the same file read the information already written to it
and displays the same on the screen.
PROGRAM 6.1
inf >>cost;
cout <<”\n”;
cout <<”item name : “ << name <<”\n”;
cout <<”item cost: “ << cost <<”\n”;
inf.close();
return 0;
int main()
{
ofstream fout;
fout.open(“country”);
fout<<”United states of America \n”;
fout<<”United Kingdom”;
fout<<”South korea”;
fout.close();
fout.open(“capital”);
fout<<”Washington\n”;
fout<<”London\n”;
fout<<”Seoul \n”;
fout.close();
{
fin.getline(line,N);
cout<<line;
}
fin.close();
fin.open(“capital”);
}
Finding End of File:
While reading a data from a file,it is necessary to find where the file ends i.e end
of file.The programmer cannot predict the end of file,if the program does not detect end
of file,the program drops in an infinite loop.To avoid this,it is necessary to provide
correct instruction to the program that detects the end of file.Thus when end of file of file
is detected,the process of reading data can be easily terminated. An ifstream object such
as fin returns a value of 0 if any error occurs in the file operation including the end-of –
file condition.Thus the while loop terminates when fin returns a value of zero on reaching
the end-of –file condition.There is an another approach to detect the end of file
condition.The statement
if(fin1.eof() !=0 )
{
exit(1);
}
returns a non zero value if end of file condition is encountered and zero
otherwise.Therefore the above statement terminates the program on reaching the end of
file.
stream-object.open(“filename”,mode);
The second argument mode specifies the purpose for which the file is opened.The
prototype of these class member functions contain default values for second argument
and therefore they use the default values in the absence of actual values.The default
values are as follows :
ios::in for ifstream functions meaning open for reading only.
ios::out for ofstream functions meaning open for writing only.
The file mode parameter can take one of such constants defined in class ios.The
following table lists the file mode parameter and their meanings.
Table 6.2 File Mode Operation
Parameter Meaning
Default actions:
When a file is opened in read-only mode,the input pointer is automatically set at
the beginning so that file can be read from the start.Similarly when a file is opened in
write-only mode the existing contents are deleted and the output pointer is set at the
beginning.This enables us to write the file from start.In case an existing file is to be
opened in order to add more data,the file is opened in ‘append’ mode.This moves the
pointer to the end of file.
infile.seekg(10);
moves the pointer to the byte number 10.The bytes in a file are numbered beginning
from zero.Therefore ,the pointer to the 11th byte in the file.Consider the following
statements:
ofstream fileout;
fileout.open(“hello”,ios::app);
int p=fileout.tellp();
On execution of these statements,the output pointer is moved to the end of file “hello”
And the value of p will represent the number of bytes in the file.
seekg (offset,refposition);
seekp (offset,refposition);
The parameter offset represents the number of bytes the file pointer is to be moved from
the location specified by the parameter refposition.The refposition takes one of the
following three constants defined in the ios class:
fout.seekg(o,ios::beg) Go to start
int main()
{
char string[80];
cout<<”enter a string \n”;
cin>>string;
int len =strlen(string);
fstream file;
file.open(“TEXT”. Ios::in | ios::out);
for (int i=o;i<len;i++)
file.put(string[i]);
file .seekg(0);
char ch;
while(file)
{
file.get(ch);
cout<<ch;
}
return 0;
{
float height[4] ={ 175.5,153.0,167.25,160.70};
ofstream outfile;
outfile.open(filename);
}
Error Handling during File Operations:
There are many problems encounterd while dealing with files like
a file which we are attempting to open for reading does not exist.
The file name used for a new file may already exist.
We are attempting an invalid operation such as reading past the end of file.
There may not be any space in the disk for storing more data.
We may attempt to perform an operation when the file is not opened for that
purpose.The C++ file stream inherits a ‘stream-state ‘member from the class
ios.This member records information on the status of a file that is being currently
used.The stream state member uses bit fields to store the status of error conditions
stated above.The class ios support several member functions that can be used to
read the status recorded in a file stream.
Table 6.4 Error Handling Functions
good() Returns true if no error has occurred.This means all the above
functions are false.For instance,if file.good() is true.all is well
with the stream file and we can proceed to perform I/O
operations.When it returns false,no further operations is carried
out.
These functions can be used at the appropriate places in a program to locate the status of
a file stream and thereby to take the necessary corrective measures.Example:
……………
…………..
ifstream infile;
infile.open(“ABC”);
while(!infile.fail())
{
…………
………….. (process the file)
…………….
}
if (infile.eof())
{
……………(terminate the program normally)
}
else
if (infile.bad())
{
…………….(report fatal error)
}
else
{
infile.clear(); //clear error state
……….
……….
}
……..
………..
The function clear() resets the error state so that further operations can be attempted.
Command Line Arguments:-
Like C,C++ also support the feature of command line argument i.e passing the arguments
at the time of invoking the program.They are typically used to pass the names of data
files.Example:
C>exam data results
Here exam is the name of file containing the program to be executed and data and results
are the filenames passed to program as command line arguments.The command line
arguments are typed by the user and are delimited by a space.The first argument is
alwayas the filename and contains the program to be executed.The main() functions
which have been using upto now without any argument can take two arguments as
shown below:
3. The iostream class is also a derived class .It is derived from istream and ostream
classes.There are three more derived classes istream_withassign,ostream_withassign and
iostream_withassign.They are derived from istream,ostream and iostream respectively.
4. There are two methods constructor of class and member function open() of the class for
opening the file.
5. The class ostream creates output stream objects and ifstream creates input stream
objects.
6. The close() member function closes the file.
7. When end of file is detected the process of readind data can be easily terminated.The
eof() function is used for this purpose.The eof() stands for end of file.The eof() function
returns 1 when end of file is detected.
8. The seekg () functions shifts the associated file’s input file pointer and output file
pointer.
9. The put() and get() functions are used for reading and writing a single character
whereas write() and read() are used to read or write block of binary data.
Key Terms
argv ios::in
clear() ios::out
eof() iostream
fail() ofstream
filemode open()
filebuf put()
get() read()
seekg() seekp()
Exercises
What are input and output streams?
What are the various classes available for file operations.
What is a file mode ?describe the various file mode options available.
6.4.Describes the various approaches by which we can detect the end of file condition.
6.5.What do you mean by command line arguments?
References
Paper Code:302 Paper Name: OOP with C++
Lesson no: 7 Lesson Name: OO System Development
Structure:
Introduction
Procedure oriented paradigm
Procedure oriented development tools
Object oriented paradigm
Object Oriented notations and graphs
Object oriented analysis
Problem understanding
Requirement specification
Identification of objects
Data flow diagram
Textual analysis
Identification of services
Establishing interconnections
Object oriented design
Review of problem space objects
Class dependencies
Organization of class hierarchies
Design of class
Design of member functions
Design of driver programs
System implementation
Prototyping paradigm
Introduction
Software engineers have been trying various tools, methods, and procedures to control
the process of software development in order to build high quality software with
improved productivity. The methods provide “how to s” for building the software while
the tools provide automated or semi-automated support for the methods. They are used in
all the stages of software development process, namely, planning, analysis, design,
development and maintenance. The software development procedures integrate the
methods and tools together and enable rational and timely development of software
systems. They provide guidelines as to apply the methods and tools, how to produce the
deliverables at each stage, what controls to apply, and what milestones to use to assess
the progress.
Software development
Procedures
Methods
Tools
There exist a number of software development paradigms, each using a different set of
methods and tools. The selection of particular paradigms depends on the nature of the
application, the programming language used, and the controls and deliverables required.
The development of a successful system depends not only on the use of the appropriate
methods and techniques but also on the developer’s commitment to the objectives of the
systems. A successful system must:
1. satisfy the user requirements,
2. be easy to understand by the users and operators,
3. be easy to operate,
4. have a good user interface,
5. be easy to modify,
6. be expandable,
7. have adequate security controls against misuse of data,
8. handle the errors and exceptions satisfactorily, and
9. Be delivered on schedule within the budget.
In this chapter, we shall review some of the conventional approaches that are being
widely used in software development and then discuss some of the current ideas that are
applicable to the object-oriented software development.
Procedure-Oriented Paradigms
Software development is usually characterized by a series of stages depicting the various
asks involved in the development process. Figure 7.2 illustrates the classic software life
cycle that is most widely used for the procedure oriented development. The classic life
cycle is based on an underlying model, commonly referred to as the “water fall” model.
This model attempts to break up the identifiable activities into series of actions, each of
which must be completed before the next begins. The activities include problem
definition, requirement analysis, design, coding, testing, and maintenance. Further
refinements to this model include iteration back to the previous stages in order to
incorporate any changes or missing links.
Problem Definition: This activity requires a precise definition of the problem in user
terms. A clear statement of the problem is crucial to the success of the software. It helps
not only the development but also the user to understand the problem better.
Analysis: this covers a detailed study of the requirements of both the user and the
software. The activity is basically concerned with what of the system such as
Design: the design phase deals with various concepts of system design such as data
structure, software architecture, and algorithms. This phase translates the requirements
into a representation of the software. This stage answers the questions of how.
Coding: coding refers to the translation of the design into machine-readable form. The
more detailed the design, the easier is the coding, and better its reliability.
Testing: once the code is written, it should be tested rigorously for correctness of the code
and results. Testing may involve the individual units and the whole systems. It requires a
detailed plan as to what, when and how to test.
Maintenance: After the software has been installed, it may undergo some changes. This
may occur due to a change in the user’s requirement, a change in the operating
environment, or an error in the software that has been fixed during the testing.
Maintenance ensures that these changes are incorporated wherever necessary.
Problem
Definitio
Analysis
Design
Coding
Testing
Mainte-
nance
Each phases of the life cycle has its own goals and outputs. The output of one phase acts
as an input to the next phase. Table 7.1 shows typical outputs that could be generated for
each phase of the life cycle.
The software life cycle, as described below, is often implemented using the functional
decomposition technique, popularly known as top-down, modular approach. The
functional decomposition technique is based on the interpretation of the problem space
and its translation into the solution space as an inter-dependent set of functional. The
functions are decomposed into a sequence of progressively simpler functions that are
eventually implemented. The final system is seen as a set of functions that are organized
in atop-down hierarchal structure.
There are several flaws in the top-down, functional decomposition approach. They
include:
The development tools available today may be classified as the first generation, second
generation, and third generation tools. The first generation tools developed in the 1960’s
and 1970’s are called the traditional tools. The second generation tools introduced in the
late 1970’s and early 1980’s are meant for the structured systems analysis and design and
therefore they are known as the structured tools. The recent tools are the third generation
ones evolved since late 1980’s to suit the object-oriented analysis and design.
Table7.2 shows some of the popular tools used for various development processes under
the three categories. Although this categorization is questionable, it gives a fair idea if the
growth of the tools during the last three decades.
This section gives an overview of some of the most frequently used first and second
generation tools. Object oriented development tools will be later in this chapter (as and
when they are required).
Process First generation Second generation Third generation
Physical System flowchart Context diagrams Inheritance graphs
Processes object-relationship charts
System flowcharts: A graphical representation of the important inputs, outputs, and data
flow among the key points in the system.
Layout forms: A format designed for putting the input data or displaying results.
Grid charts: A chart showing the relationship between different modules of a system.
Context diagrams: A diagram showing the inputs and their sources and the outputs and
their destinations. A context diagram basically outlines the system boundary.
Data flow diagrams: They describe the flow of data between various components of a
system. It is a network representation of the system which includes processes and data
files.
Data dictionary: A structured repository of data about data. It contains a list of terms and
their definitions for all the data items and stores.
Decision table: A table of configurations for defining a problem and the actions to be
taken. It presents the logic that tells us what action to take when a given condition is true
or otherwise.
Decision tree: A graphic representation of the condition and outcomes that resemble the
branches of a tree.
Warnier / Orr diagrams: A horizontal hierarchy chart using nested sets of braces,
psuedocodes, and logic symbols to indicate the program structure.
Object-Oriented Paradigm
The object-oriented paradigm draws heavily on the general systems theory as a
conceptual background. A system can be viewed as a collection of entities that interact
together to accomplish certain objectives (fig. 7.3.). Entities may represent physical
objects such as equipment and people, and abstract concepts such as data files and
functions. In object oriented analysis, the entities are called objects.
PROCESS
Entity Entity
INPUT
OUTPUT
Entity
Entity Entity
Application
OOP
Object-oriented Objects
Programming in program
OOD
Objects
Object-oriented in a solution space
Design
OOA Object
Object-oriented in problem space
Analysis
All the phases in the object-oriented approach work more closely together because of the
commonality of the object model. In one phase, the problem domain objects are
identified, while in the next phase additional objects required for a particular solution are
specified. The design process is repeated for these implementation-level objects.
Problem space
Objects defined in
Problem space
Solution specific
Objects defined
We must use these notations and graphs wherever possible. They improve not only the
clarity of the processes but also the productivity of the software developers.
Class Name
Class name
Class Name
Function 1
Data Function Data
Function 2 Data
Functions
Function 3
Is A
Is A Is A
Object A Object B
A
Base Class
B
Derived Class
Vehicle
A Kind of
Car Cycle
Vehicle
(a)
Car Cycle
(b)
House
A Part of
Door Window
(a)
House
Window
Door
(b)
Fig 7.11 Composition relationship
B C D
B1 B2
Server Client
Process Process
A B
Process Process
C D
Object–Oriented Analysis
Object-oriented analysis provides us with simple, yet powerful, mechanism for
identifying objects, the building block of the software to be developed. The analysis is
basically concerned with the decomposition of a problem into its component parts and
establishing a logical model to describe the system functions.
The object-oriented analysis (OOA) approach consists of the following steps:
Although we have shown the above tasks as a series of discrete steps, the last three
activities are carried out inter-dependently as shown in Fig. 7.15.
Problem
Definition
Requirement
Specification
Identify objects
Design
Problem Understanding
The first step in the analysis process is to understand the problem of the user. The
problem statement should be refined and redefined in terms of computer system
engineering that could suggest a computer-based solution. The problem statement should
be stated, as far as possible, in a single, grammatically correct sentence. This will enable
the software engineers to have a highly focused attention on the solution of the problem.
The problem statement provides the basis for drawing the requirements specification of
both the user and the software.
Requirements Specification
Once the problem is clearly defined, the next step is to understand what the proposed
system is required to do. It is important at this stage to generate a list of user
requirements. A clear understanding should exist between user and the developer of what
is required. Based on the user requirements, the specification for the software should be
drawn. The developer should state clearly:
These specifications often server as a reference to test the final product for its
performance of the intended tasks.
Identification of Objects
Objects can often be identified in terms of the real world objects as well as the abstract
objects. Therefore, the best place to look for object is the application itself. The
applications may be analyzed by using one of the following two approaches:
1. Data flow diagrams(DFD)
2. Textual analysis(TA)
Textual Analysis
This approach is based on the textual description of the problem or proposed solution.
The description may be of one or two sentences or one or two paragraphs depending on
the type and complexity of the problem. The nouns are good indicators of the objects.
The names can further the classified as proper nouns, common nouns, and mass or
abstract nouns. Table 7.3 shows the various types of nouns and their meaning.
Book database
Data store
Data
Stores
Store
Shipment
Shipping Notice Collection information
Customer order
Fig. 7.16 Data flow diagram for order processing and shipping for a publishing
company.
Order Instruction
Customer Process order
Warehouse
It is important to note that the context and semantics must be used to determine the
noun categories. A particular word may mean a common noun in one context and a mass
or abstract noun in another.
These approaches are only a guide and note the ultimate tools. Creative perception and
intuition of the experienced developers play an important role in identifying the objects.
Using one of the above approaches, prepare a list of objects for the application
problem. This might include the following task:
Identification of services
Once the objects in the solutions space have been identified, the next step is to identify a
set of services that each object should offer. Services are identified by examining all the
verbs and verb phrases in the problem description statement. Verbs which can note
actions or occurrences may be classified as shown in table 7.4.
Doing verbs and compare verbs usually give rise to services. Being verbs indicate the
existence of the classification structure while having verbs give rise to the composition
structures.
Establishing interconnections
This step identifies the services that objects provide and receive. We may use an
information flow diagram (IFD) or an entity-relationship(ER) diagram to enlist this
information. Here, we must establish a correspondence between the services and the
actual information that are being communicated.
Object-Oriented Design
Design is concerned with a mapping of objects in the problem space into objects in the
solution space, and creating an overall structure and computational models of the system.
This stage normally uses the bottom-up approach to build the structure of the system and
the top-down functional decomposition approach to design the class member function
that provides services. It is particularly important to construct structured hierarchies, to
identify abstract classes, and to simplify the inter-object communications. Reusability of
classes from the previous designs, classification of the objects into subsystems and
determination of appropriate protocols are some of the considerations of the design stage.
The object oriented design (OOD) approach may involve the following steps:
An exercise to review the objects identified in the problem space is undertaken as a first
step in the design stage. The main objective of this review exercise is to refine the objects
in terms of their attributes and operations and to identify other objects that are solution
specific. Some guidelines that might help the review process are:
1. If only one object is necessary for a service, then it operates only on that object.
2. If two or more objects are required for an operation to occur, then it is necessary
to identify which object’s private part should be known to the operation.
3. If an operation requires knowledge of more than one type of objects, then the
operation is not functionally cohesive and should be rejected.
Class Dependencies
Use relationship gives information such as the various classes a class uses and the way it
uses them. For example, a class A can use classes B and C in several ways:
1. A reads member of B
2. A calls a member of C
3. A creates B using new operator
A
B
D E
X Y
A B C D E
X Y
A B C D E
Fig. 7.18
Design of Classes
We have identified classes, their attributes, and minimal set of operations required by the
concept a class is representing. Now we must look at the complete details that each class
represents. The important issues is to decide what function are to be provided. For a class
to be useful, it must contain the following functions, in addition to service functions:
Function 1
Data
Function 2
B C D
B1 B2 D1 D2
B17
D17
7.20 Top down Design of functions
Every C++ program must contain a main () function code known as the driver program.
The executions of the program begin and end here. The driver program is mainly
responsible for:
Receiving data values from the user,
Creating objects from the class definitions,
Arranging communication between the objects as a sequence of message for
invoking the member functions, and
Displaying output results in the form required by the user.
All activities, including processing during the execution of the program, result from the
mutual interactions of the objects. One major design decision made is the logical order of
the messaging passing.
Implementation
Implementation includes coding and testing. Coding include writing codes for classes,
member function and the main program that acts as a driver in the program. Coding
becomes easy once a detailed design has been done with care.
No program works correctly the first time. So testing the program before using is an
essential part of the software development process. A detailed test plan should be drawn
as to what, when and how to test. The class interfaces and class dependencies are
important aspects for testing. The final goal of testing is to see that the system performs
its intended job satisfactorily.
Prototyping Paradigm
Most often the real world application problems are complex in nature and therefore the
structure of the system becomes too large to work out the precise requirements at the
beginning. After the large system is completed, incorporation of any features that has
been identified as “missing” at the testing or application stage might be too expensive and
time consuming. One way of understanding the system design and its ramifications
before a complete system is built is to build and test a working model of the proposed
system. The model system popularly known as prototype and the process is called
prototyping. Since the object-oriented analysis and design approach is evolutionary, it is
best suited for prototyping paradigm which is shown in fig. 7.22
A prototype is scaled down version of the system and may not have stringent
performance criteria and resource requirements. Developer and customer agree upon
certain “Outline specifications” of the system and a prototype design is proposed with the
outline requirements and available resources. The major interest is not in the prototype
itself but in its performance which is used to refine the requirement specifications.
Prototype provides an opportunity to experiment and analyze various aspects of the
system such as system structure, internal design, hardware requirements and the final
system requirements. The benefits of using the prototype approach are:
System
specifications
Outline
Requirements
Design
Prototype
Model
Build
Prototype
Make
Detailed
Full
System
Evaluate
prototype
Prototype is meant for experimenting. Most often it can not be tuned into a product.
However, occasionally, it may be possible to tune a prototype into a final product if
proper care is taken in redesigning the prototype.
Wrapping Up
You must consider the ideas presented here as only guidelines and use your experience,
innovation and creativity wherever possible.
Following are some points for your thought and innovation:
Set clear goals and tangible objectives.
Try to use existing systems as examples or models to analyze your system.
Use classes to represent concepts.
Keep in mind that the proposed system must be flexible, portable and extendable.
Keep a clear documentation of everything that goes into the system.
Try to reuse the existing functions and classes.
Keep functions strongly typed wherever possible.
Use prototypes wherever possible.
Match design and programming style.
Keep the system clean, simple and efficient as far as possible.
Summary
The classic System development life cycle most widely used for procedure
oriented development consists of following steps:
(a)Problem definition
(b)Analysis
(c)Design
(d)Coding
(e)Testing
(f)Maintenance
In object oriented paradigm, a system can be viewed as a collection of entities that
interact together to accomplish certain objectives.
In object oriented analysis, the entities are called objects. object oriented analysis
refer to the methods of specifying requirements of the software in terms of real
world objects, their behavior and their interactions with each other.
Object Oriented design translate the software requirements in to specification for
objects, and derives class hierarchies from which the objects can be created.
OOP refer to the implementation of the program using objects, with the help of
object oriented programming language such as C++.
The object oriented analysis approach consist of the following steps:
(a) Defining the problem.
(b) Estimating requirements of the user and the software.
(c) Identifying the objects and their attributes.
(d) Identifying the interface services that each object is supposed to provide.
(e) Establishing interconnections between the objects in terms of services
required and services rendered.
The object oriented design approach involves the following steps:
(a)Review of objects created in the analysis phase.
(b) Specification of class dependencies.
(c) Organization of class hierarchies.
(d) Design of classes.
(e) Design of member functions.
(f) Design of driver program.
The benefits of using the prototype approach are:
(a) You can produce understandable specifications which are correct and
complete as far as possible.
(b) The user can understand what is being offered.
(c) Maintenance changes that are requiring when a system is installed are
minimized.
(d) Development engineers can work fret of specifications.
Keywords:
Data flow diagram Proper nouns
Decision table Prototype
Design Prototyping
Development tools Prototyping paradigm
Doing verbs Second generation
Driver program Selection
Entities Sequence
Entity relationship diagram Single tree model
Entity-relationship Software life cycle
First generation Solution space
Flow charts Stative verbs
Forest model Structure chart
Fountain model Structured design
Functional decomposition Structured tools
Grid charts System flowcharts
Hierarchical charts Testing
Information flow diagram Textual analysis
Inheritance relationship Top down approach
Instances of objects Water fall model
Questions:
1. Five most important features, that a software developer should keep in mind while
designing a system.
2. Describe why the testing of software is important.
3. What do you mean by maintenance of software? How and when it is done?
4. Who are the major players in each stage of the system development life cycle?
5. What are the limitations of the classic software development life cycle?
6. “Software development process is an iterative process”. Discuss.
7. Distinguish between the “Water-fall” model and the “fountain” model.
8. Distinguish between object-oriented system analysis and system design. Which of the
two require more creative talents of the system developer?
9. Distinguish between the following:
(a) Classification relationship and composition relationship
(b) Inheritance relationship and client-server relationship.
(c) Object in problem space and object in solution space.
(d) Data flow diagrams and hierarchical charts.
10. Discuss the application of structured design techniques in object-oriented
programming.
11. What are the critical issues that are to be considered while designing the driver
program? Why?
12. What is prototyping? How does it help improve the system design?
References:
1. Object –Oriented –Programming in C++ by E Balagurusamy.
2. Object –Oriented –Programming with ANSI & Turbo C++ by Ashok N. Kamthane.
3. OO Programming in C++ by Robert Lafore, Galgotia Publications Pvt. Ltd.
4. Mastering C++ By K R Venugopal, Rajkumar Buyya, T Ravishankar.
5. Object Oriented Programming and C++ By R. Rajaram.
6. Object –Oriented –Programming in C++ by Robert Lafore.
Paper Code: Paper Name: OOP with C++
Lesson no: 8 Lesson Name: Template
Structure:
Introduction
Class templates
Multiple parameters in class templates
Function templates
Multiple parameters in function templates
Overloading of template functions
Member function templates
Non-type template arguments
Introduction
Template is a new concept which enables us to define generic and functions and thus
provides support for generic programming. Generic programming as an approach where
generic types are used as parameters in algorithms so that they work for a variety of
suitable data types and data structures.
A template can be used to create a family of classes or functions. For example, a class
template for an array class would enable us to create arrays of various data types such as
int array and float array .similarly, we can define a template for a function, say mul(),hat
would help us create versions of mul() for multiplying int, float and double type values.
A template can be considered as a kind of macro. When an object of a specific type is
define for actual use, the template definition for that class is substitute with the required
data type. Since a template is defined with a parameter that would be replaced by a
specified data type at the time of actual use of the class or function, the templates are
sometimes called parameterized class or functions.
Class Template:
Consider a vector class defined as follows:
Class vector
{
int *v ;
int size;
public:
vector(int m ) // create a null vector
{
v=new int[size = m];
for(int i=0;i<size;i++)
v[i]=0;
}
vector(int *a) //create a vector from an array
{
for(int i=0;i<size;i++)
v[i]=a[i];
}
int operator*9vector &y) //scalar product
{
int sum=0;
for(int i=0;i<size;i++)
sum+=this->v[i]*y-v[i];
return sum;
}
};
The vector class can store an array of int numbers and perform the scalar product of two
int vector as shown below:
int main()
{
int x[3]={1,2,3};
int y[3]={4,5,6};
vector v1(3); //create a null vector of 3 integers
vector v2(3);
v1=x; //create v1 from the array x
v2=y;
int R=v1*v2;
cout<<”R=”r;
return 0;
}
Now suppose we want to define a vector that can store an array of float value. We can do
this simply replacing the appropriate int declaration with float in the vector class. This
means that we can have to redefine the entire class all over again.
Assume that we want to define a vector class with the data type as a parameter and then
use this class to create a vector of any data type instead of defining a new class every
time. The template mechanism enables us to achieve this goal.
As mentioned earlier, template allows us to define generic classes. It is simple process to
create a generic class using a template with an anonymous type. The general format of a
class template is:
Template<class T>
class classname
{
…
//class member specification
//with anonymous type T
//whenever appropriate
….
….
};
The template definition of vector class shown below illutrates the syntax of a template:
template<class T>
class vector
{
T* v; // type T vector
int size;
public:
vector(int m )
{
v=new T [size = m];
for(int i=0; i<size; i++)
v[i] =0;
}
vector (T* a)
{
for(int i=0;i<size; i++)
v[i]=a[i];
}
T operator*( vector &y)
{
T sum =0;
for(int i=0;i<size;i++)
sum+=this->v[i]*y-v[i];
return sum;
}
};
Remember:
The class template definition is very similar to an ordinary class definition except the
prefix template<class T> and the use of type T. This prefix tells the complier that we are
going to declare a template and use T as a type name in the Declaration. Thus, vector has
become a parameterized class with the type T as its parameters. T may be substituted by
any data type including the user defined types. Now we can create vectors for holding
different data types.
Example;
vector<int> v1(10); //10 element int vector
vector<float> v2(30); //30 element float vector
The type T may represent a class name as well.
Example:
Vector<complex> v3 (5); // vector of 5 complex numbers
A class created from a class template is called a template class. The syntax for defining
an object of a template class is:
This process of creating a specific class from a class template is called instantiation. The
complier will perform the error analysis only when an instantiating take place. It is,
therefore, advisable to create and debug an ordinary class before converting it in to
template.
#include <iostream>
using namespace std;
const size=3;
template<class T>
class vector
{
T*v; // type T vector
public:
vector()
{
v=new T[size];
for(int i=0;i<size;i++)
v[i]=0;
}
vector(T* a)
{
for(int i=0;i<size;i++)
v[i]=a[i];
}
T operator*(vector &y)
{
T sum=0;
for(int i=0;i<size;i++)
sum+=this->v[i]*y.v[i];
return sum;
}
};
int main()
{
int x[3]={1,2,3};
int y[3]={4,5,6};
vector<int> v1;
vector<int> v2;
v1=x;
v2=y;
int R= v1*v2;
cout<<”R=”<<r<<”\n”;
return 0;
}
The output would be :
R=32
Another Example:
#include <iostream>
using namespace std;
const size=3;
template<classT>
class vector
{
T*v; // type T vector
public:
vector ()
{
v=new T[size];
for(inti=0;i<size;i++)
v[i]=0;
}
vector(T* a)
{
for(int i=0;i<size;i++)
v[i]=a[i];
}
T operator*(vector &y)
{
T sum=0;
for(int=0;i<size;i++)
sum+=this->v[i]*y.v[i];
return sum;
}
};
Int main()
{
float x[3]={1.1,2.2,3.3};
float y[3]={4.4,5.5,6.6};
vector <float> v1;
vector <float>v2;
v1=x;
v2=y;
float R=v1*v2;
cout<<”R=”<<R<<”\n”;
return 0;
}
The output would be:
R=38.720001
#include <iostream>
using name space std;
template<class t1,class t2>
class Test
{
T1 a;
T2 b;
public:
test(T1 x, T2 y)
{
a=x;
b=y;
}
void show()
{
cout<<a<<”and”<<<<”\n”;
}
};
int main()
{
Test<float,int> test1(1.23,123);
Test<int,char> test2(100,’W’);
test1.show();
test2.show();
return 0;
};
Function Templates
Like class templates, we can also define function templates that cold be used to create a
family of functions with different argument types. The general format of a function
template is:
template<class T>
returntype functionname (argument of type T)
{
//
//body of function
//with Type T
//whenever appropriate
//……………
}
The function template syntax is similar to that of the class template except that we are
defining functions instead of classes. We must use the template parameter T as and when
necessary in the function body and its argument list.
The following example declares a swap () function template that will swap two values of
a given type of data.
This essential declares a set of overloading functions, one for each type of data. We can
invoke the swap () function likes any ordinary function .for example, we can apply the
swap () function as follows:
void f ( int m , int n , float b )
{
swap ( m , n); //swap two integer values
swap ( a , b); //swap two float values
//……..
}
This will generate a swap () function template for each set of argument types. Example
will show how a template function is defined and implemented.
An example:
#include <iostream>
using namespace std;
Template <class T>
void swap (T &x, T &y)
{
T temp=x;
x=y;
y=temp;
}
void fun( int m, int n, float a, float b)
{
cout<<”m and n before swap:”<<m<<””<<n<<”\n”;
swap(m,n);
cout<<”m and n after swap:”<<m<<””<<n<<”\n”;
cout<<”a and b before swap:”<<a<<””<<b<<”\n”;
swap(a,b);
cout<<”a and b after swap:”<<a<<””<<b<<”\n”;
}
int main ()
{
fun(100,200,11.22,33.44);
return 0;
}
Template<class T>
bubble( T a[] , int n )
{
for( int i=0 ; i<n-1 ; i++ )
for( int j=n-1 ; i<j ; j-- )
if ( a[j] < a[j-1] )
{
T temp = v[j];
v[j]=v[j-1];
v[j-1]=temp;
}
}
template<class T>
T max ( T x, T y)
{
return x>y ? x : y;
}
# include <iostream>
using namespace std ;
template<class T>
void bubble (T a[], int n)
{
for (int i=0; i<n-1; i++)
for (int j=n-1; i<j; j--)
i f (a[j] < a[j-1])
{
swap (a [j],a[j-1];// calls template function
}
}
templte<class X>
void swap(X &a, X &b)
{
x temp=a;
a= b;
b= temp;
}
int main()
{
int x[5] = { 10,50,30,40,20,};
float y[5] ={1.1,5.5,3.3,4.4,2.2,};
bubble ( x , 5 ); // calls template function for int values
bubble ( y , 5 ); // calls template function for floate values
return 0;
}
Another example:
#include <isotream>
#include <iomanip>
#include <cmath>
using na,espace std;
template <class T>
void rootes(T a,T b,T c)
{
T d = b*b - 4*a*c;
if (d= = 0) // Roots are equal
{
cout << “R1 = R2 = “ << -b/(2*a) << endl;
}
else if (d>0) //two real roots
{
cout<<”roots are real \n”;
float R =sqrt (d);
float R1 = (-b+R)/(2*a);
float R2 = ( -b+R )/(2*a);
cout<< “R1 = “<< R1 << “ and”;
cout <<R2 = “<< R2 << endl;
}
else // roots are complex
{
cout <<”roots are complex \n”;
float R1 = -b/( 2*a);
float R2 = sqrt( -d )/( 2*a );
cout <<” real part = “ << R1 << endl;
cout<< “imaginary part =” << R2;
cout<< endl;
}
}
int main()
{
cout<< “integer coefficients \n”;
roots(1,-5 ,6);
cout << “\n float coefficients \n”;
roots (1.5, 3.6, 5.0);
return 0;
}
Output would be :
integer coefficients
roots are real
R1= 3 and R2 =2
float coefficients
roots are complex
real part = -1.2
imaginary part = 1.3757985
#inlude <iostream>
#include<string>
using namespace std;
template<class T1,class T2>
void display( T1 x, T2 y)
{
cout<<x<<” “<<y<<”\n”;
}
int main()
{
display(1999, “EBG”);
display(12.34, “1234);
return 0;
}
1999 EBG
12.34 1234
#include <iostream>
#include <string>
using namespace std;
template <class T>
void display(T x)
{
cout<<”template display:” << x<< “\n”;
}
void display ( int x)
{
cout<<”Explicit display: “<< x <<”\n”;
}
int main()
{
display(100);
display(12.34);
display(‘c’);
return 0;
}
Explict display:100
template display:12.34
template display:c
Remember:
The call display (100) invokes the ordinary version of display() and not the template
version.
The vector class template and its member fnctions are redefined as follow:
// class template……….
template<class T>
class vector
{
T*v;
int size;
public:
vector(int m);
vector(T* a);
T operator*(vector & y);
};
//member function templates
template<class T>
vector<T> :: vector (int m );
{
v=new T[size=m];
for(int i=0; i<size ; i++)
v[i]= 0;
}
template<class T>
vector <T>::vector(t*a)
{
for(int i=0; i<size ; i++)
v[i]=a[i];
}
template< class T >
T vector < T > :: operator*(vector & y)
{
T sum =0;
for ( int i=0; i< size ; i++)
sum += this -> v[i]*y.v[i];
return sum;
}
This template supplies the size of the array as an argument. This implies that the size of
the array is known to the complier at the compile time itself. The arguments must be
specified whenever a template class is created. Example:
Array <int,10> a1; //array of 10 integers
Array <float,5> a2; //array of 5 floats
Array <char,20> a3; //string of size 20
The size is given as an argument to the template class.
Summary
Question
References:
1. Object –Oriented –Programming in C++ by E Balagurusamy.
2. Object –Oriented –Programming with ANSI & Turbo C++ by Ashok N. Kamthane.
3. OO Programming in C++ by Robert Lafore, Galgotia Publications Pvt. Ltd.
4. Mastering C++ By K R Venugopal, Rajkumar Buyya, T Ravishankar.
5. Object Oriented Programming and C++ By R. Rajaram.
6. Object –Oriented –Programming in C++ by Robert Lafore.
Paper code: 302 Paper Name: OOPS using C++
Lesson no: 9 Lesson name: Exception Handling
Unit Structure
Introduction
Principles of Exception handling
Exception handling mechanism
Throwing mechanism
Catching mechanism
Rethrowing an Exception
Specifying Exception
Introduction:-
Usually there are mainly two type of bugs, logical errors and syntactic errors. The
logical errors occur due to poor understanding of problem and syntactic errors arise due
to poor understanding of language. There are some other problems called exceptions that
are run time anomalies or unused conditions that a program may encounter while
executing. These anomalies can be division by zero,access to an array outside of its
bounds or running out of memory or disk space. When a program encounters an
exceptional condition it is important to identify it and dealt with it effectively.An
exception is an object that is sent from the part of the program where an error occurs to
that part of program which is going to control the error.
………………..
try
{
…………
…………….. //block of statements which detects and throw an exceptions
throw exception;
…………….
…………….
}
catch(type arg) //catches exceptions
{
…………… // Block of statements that handles the exceptions
………………
…………….
}
………….
…………..
When the try block throws an exception, the program control leaves the try block and
enters the catch statement of the catch block. If the type of object thrown matches the
arg type in the catch statement,then the catch block is executed for handling the
exception.If they donot match,the program is aborted with the help of abort() function
which is executed implicitly by the compiler.When no exception is detected and
thrown,the control goes to the statement immediately after the catch block i.e catch block
is skipped.The below diagram 9.1 will show the mechanism of exception handling
try block
Exception object
catch block
Program9.1
#include<iostream>
using namespace std;
int main()
{
int a,b;
cout<<”enter the values of a and b”;
cin>>a;
cin>>b;
int x = a- b;
try
{
if(x!=0)
{
cout<<”result(a/x) = “<<a/x<<”\n”;
}
else
{
throw(x);
}
}
catch(int i)
{
cout<<”exception caught : x = “<<x<<”\n”;
}
cout<<”end”;
return 0;
}
Output:
enter value of a and b
20 15
result(a/x)=4
end
Second run
Enter value of a and b
10 10
exception caught:x=0
end
The program detects and catches a division by zero problem.The output of first run shows
a successful execution. When no exception is thrown, the catch statement is skipped and
execution resumes with the first line after the catch. In the second run the denominator x
become zero and therefore a division by zero situation occurs. This exception is thrown
using the object x.Since the exception object is of integer type, the catch statement
containing int type argument catches the exception and displays necessary message.
The exceptions are thrown by functions that are invoked from within the try
block. The point at which the throw is executed is called throw point. Once an exception
is thrown to catch block ,control cannot return to the throw point.
The general format of code for this kind of relationship is shown below
type function (arg list) //function with exception
{ ………..
……………
throw(object); //throw exception
………..
………..
}
………
………….
try
{ ……….
………. Invoke function here
………..
}
catch(type arg) //catches exception
{
…………..
…………. Handle exception here
………….
}
………..
It is to be noted here that the try block is immediately followed by the catch block
irrespective of the location of the throw point.
The below program demonstrates how a try block invokes a function that generates an
exception
Program 9.2
}
else
{
throw(x-y);
}
}
int main()
{
try
{
cout<<”we are inside the try block”;
divide(10,20,30);
divide(10,10,20);
}
catch (int i)
{
cout<<”caught the exception”;
}
return 0;
}
The output of the above program is
We are outside the try block
We are inside the function
Result =-3
We are inside the function
Caught the exception
Throwing mechanism:-
When an exception is encountered it is thrown using the throw statement in the following
form:
throw (exception);
throw exception;
throw;
The operand object exception may be of any type including constants. It is also possible
to throw objects not intended for error handling. When an exception is thrown, it will be
caught by the catch statement associated with the try block.In other words the control
exits the try block and transferred to catch block after the try block.Throw point can be in
the deep nested scope within the try block or in a deeply nested function call.
Catching mechanism:-
Code for handling exceptions is included in catch blocks. The catch block is like a
function definition and is of form
Catch(type arg)
{ statements for managing exceptions
}
The type indicates the type of exception that catch block handles. The parameter arg is
an optional parameter name. The catch statement catches an exception whose type
matches with the type of catch argument. When it is caught, the code in the catch block is
executed. After executing the handler, the control goes to the statement immediately
following in catch block. Due to mismatch ,if an exception is not caught abnormal
program termination will occur.In other words catch block is simply skipped if the catch
statement does not catch an exception.
{
//catch block N
}
When an exception is thrown, the exception handlers are searched in order for an
appropriate match. The first handler that yields a match is executed. After executing the
handler, the control goes to the first statement after the last catch block for that try.
When no match is found, the program is terminated.If in some case the arguments of
several catch statements match the type of an exception,then the first handler that
matches the exception type is executed.
}
catch(char c) //Catch 1
{
cout<<”Caught a character \n”;
}
catch (int m) //Catch 2
{ cout <<”caught an integer\n”;
}
test(1);
cout<<”x== 0 \n”;
test(0);
cout<<”x == -1 \n”;
test (-1);
cout <<”x== 2 \n”;
test (2);
return 0;
}
The program when executed first invokes the function test() with x=1 and throws x an int
exception.This matches the type of parameter m in catch 2 and therefore catch2 handler is
executed.Immediately after the execution , the function throws ‘x’, a character type
exception and therefore the first handler is executed.Finally the handler catch3 is
executed when a double type exception is thrown.Every time only the handler which
catches the exception is executed and all other handlers are bypassed.
{
try
{
if (x== 0) throw x; //int
if ( x== -1) throw ‘x’; //char
if ( x== 1) throw 1.0; //float
}
test(0);
test(1);
return 0;}
We can use the catch(. . .) as a default statement along with other catch handlers so that it
can catch all those exceptions that are not handled explicitly.
Rethrowing an Exception:-
A handler may decide to rethrow an exception caught without processing them.In such
situations we can simply invoke throw without any argument like
throw;
This cause the current exception to be thrown to the next enclosing try/catch sequence
and is caught by a catch statement listed after that enclosing try block. The following
program shows how an exception is rethrown and caught.
Program 9.5
RETHROWING AN EXCEPTION
#include <iostream>
using namespace std;
{ if (y== 0.0)
throw y; //throwing double
else
{ divide(10.5,2.0);
divide(20.0,0.0);
}
catch (double)
{ cout <<”caught double inside main \n”;
}
cout <<”End of mai\n “;
return 0;
}
When an exception is rethrown, it will not be caught by the same catch statement or any
other catch in that group. It will be caught by the an appropriate catch in the outer
try/catch sequence for processing.
Specifying Exceptions:-
In some cases it may be possible to restrict a function to throw only certain specified
exceptions. This is achieved by adding a throw list clause to function definition. The
general form of using an exception specification is:
Type function (arg-list) throw (type-list)
{
…………..
………… function body
……….
}
The type list specifies the type of exceptions that may be thrown.Throwing any other
type of exception will cause abnormal program termination.To prevent a function from
throwing any exception, it can be done by making the type list empty like
throw(); //empty list
in the function header line.
The following program will show this
Program 9.6
int main()
{
try
{
cout<<”testing throw restrictions\n”;
cout<<”x== 0\n “;
test (0);
cout<<”x==1 \n”;
test(1);
cout<<”x== -1 \n”;
test(-1);
cout <<”x== 2 \n”;
test(2);
}
catch( char c)
{
cout <<”caught a character \n”;
}
catch(int m)
{
cout<<”caught an integer \n”;
}
catch (double d)
{
cout<<”caught a double \n”;
}
cout<<” end of try catch system \n \n”;
return 0;
}
Summary
1. Exceptions are peculiar problems that a program may encounter at run time.
2. ANSI C++ has built in language function for trapping the errors and controlling the
exceptions.All C ++ compilers support this newly added facility.
3. An exception is an object.It is send from the part of the program where an error occurs
to the part of program which is going to control the error.
4. C++ exception method provides three keywords,try,throw and catch.The keyword try is
used at the starting of exception.The entire exception statement are enclosed in the curly
braces.It is known as try block.
5. The catch block receives the exception send by the throw block in the try block.
Key Terms
abort() function multiple catch
asynchronous exception out-of-range index
catch block synchronous exception
catch(…..) statement syntactic error
exception handler throw
exceptions throw point
logic errors throw()
Exercises
What do you mean by exception handling?
Describe the role of keywords try,throw and catch in exception handling?
When should a program throw an exception?
What is an exception specification?When is it used?
When do we used multiple catch handlers?
Explain mechanism of exception handling.
References
1. Object –Oriented –Programming in C++ by E Balagurusamy.
2. Object –Oriented –Programming with ANSI & Turbo C++ by Ashok N. Kamthane.