BIT 3201object Oriented Analysis and Design
BIT 3201object Oriented Analysis and Design
BIT 3201object Oriented Analysis and Design
Object-Oriented Analysis and Design with UML (OOAD/UML) presents the concepts and
techniques necessary to effectively use system requirements captured in use cases to drive the
development of a robust design model. In this module, participants learn to apply the UML to
fundamental object-oriented analysis and design concepts.
Audience
This course is intended for practitioners who desire an understanding of object-oriented
analysis and design concepts, as well as hands-on practical experience applying the
techniques within a use-case-driven, architecture-centric, and iterative development process.
Objective
Apply an iterative, use case-driven, architecture-centric process to the development of a
robust design model.
Use the UML to represent the design model.
Apply the concepts of abstraction, encapsulation, inheritance, and polymorphism.
Explain the different views of software architecture, the key mechanisms that are defined in
support of that architecture and the effect of the architecture and mechanisms on the produced
design.
Describe some basic design considerations, including the use of patterns
COURSE OUTLINE
Key topics
1: Best Practices of Software Engineering
2: Concepts of Object Orientation
3: Requirements Overview
4: Analysis and Design Overview
5: Architectural Analysis
6: Use-Case Analysis
7: Identify Design Elements
8: Identify Design Mechanisms
9: Describe the Run-time Architecture
10: Describe Distribution
11: Use-Case Design
12: Subsystem Design
13: Class Design
14: Database Design
Object Oriented Analysis And Design
Table of Contents
COURSE CONTENT ................................................................................................................................... 2
COURSE OUTLINE .................................................................................................................................... 2
1 INTRODUCTION ............................................................................................................................... 8
1.1 Software Crisis ......................................................................................................................... 8
1.2 Software Evaluation ................................................................................................................ 8
1.3 Procedure-Oriented Programming ....................................................................................... 10
1.4 Object Oriented Paradigm..................................................................................................... 11
1.5 Basic Concepts of Object Oriented Programming ................................................................. 12
1.5.1 Objects........................................................................................................................... 12
1.5.2 Classes ........................................................................................................................... 13
1.5.3 Data Abstraction and Encapsulation ............................................................................. 13
1.5.4 Inheritance .................................................................................................................... 14
1.5.5 Polymorphism ............................................................................................................... 15
1.5.6 Dynamic Binding ............................................................................................................ 16
1.5.7 Message Passing ............................................................................................................ 16
1.6 Benefits of OOP ..................................................................................................................... 17
1.7 Object Oriented Language .................................................................................................... 17
1.8 Application of OOP ................................................................................................................ 18
1.9 Introduction of C++ ............................................................................................................... 19
1.9.1 Application of C++ ......................................................................................................... 19
1.10 Simple C++ Program .............................................................................................................. 19
1.10.1 Program feature ............................................................................................................ 20
1.10.2 Comments ..................................................................................................................... 20
1.10.3 Output operator ............................................................................................................ 20
1.10.4 The iostream File ........................................................................................................... 21
1.10.5 Namespace .................................................................................................................... 21
1.10.6 Return Type of main() ................................................................................................... 21
1.11 More C++ Statements ........................................................................................................... 22
1.11.1 Variables ........................................................................................................................ 22
1.11.2 Input Operator .............................................................................................................. 22
1.11.3 Cascading of I/O Operators ........................................................................................... 23
1.12 An Example with Class........................................................................................................... 24
1.13 Structure of C++ Program...................................................................................................... 25
1.14 Creating the Source File ........................................................................................................ 26
1.15 Compiling and Linking ........................................................................................................... 27
1.16 Summary ............................................................................................................................... 27
1.17 Questions .............................................................................................................................. 29
Object Oriented Analysis And Design
2 INTRODUCTION ............................................................................................................................. 30
2.1 Function definition and declaration ...................................................................................... 31
2.2 Arguments to a function ....................................................................................................... 32
2.2.1 Passing arguments to a function ................................................................................... 32
2.2.2 Default arguments......................................................................................................... 33
2.2.3 Constant arguments ...................................................................................................... 34
2.2.4 Calling functions ............................................................................................................ 34
2.3 Inline functions ...................................................................................................................... 36
2.4 Scope rules of functions and variables.................................................................................. 37
2.5 Definition and declaration of a class...................................................................................... 39
2.6 Member function definition .................................................................................................. 41
2.6.1 Inside Class Definition: .................................................................................................. 41
2.6.2 Outside Class Definition Using Scope Resolution Operator (::) :.................................... 41
2.7 Declaration of objects as instances of a class ........................................................................ 42
2.8 Accessing members from object(s) ....................................................................................... 43
2.9 Static class members ............................................................................................................. 44
2.9.1 Static Data Member: ..................................................................................................... 44
2.9.2 Static Member Function: ............................................................................................... 45
2.10 Friend classes......................................................................................................................... 46
2.11 Summary ............................................................................................................................... 46
2.12 Review Questions .................................................................................................................. 47
2.13 Further Readings ................................................................................................................... 48
............................................................................................................................................................... 49
3 INTRODUCTION ............................................................................................................................. 49
3.1 Declaration and Definition of a Constructor:-........................................................................ 49
3.2 Type Of Constructor .............................................................................................................. 50
3.2.1 Overloaded Constructors............................................................................................... 50
3.2.2 Copy Constructor ........................................................................................................... 52
3.2.3 Dynamic Initialization of Objects ................................................................................... 53
3.2.4 Constructors and Primitive Types .................................................................................. 54
3.2.5 Constructor with Default Arguments............................................................................. 54
3.3 Special characteristics of constructors .................................................................................. 55
3.4 Declaration and Definition of a Destructor ........................................................................... 56
3.5 Special Characteristics of Destructors ................................................................................... 58
3.6 Declaration and definition of a overloading ......................................................................... 58
3.7 Assignment and initialisation ................................................................................................ 61
3.8 Type conversions ................................................................................................................... 62
3.9 Summary ............................................................................................................................... 65
Object Oriented Analysis And Design
3.10 Review Questions .................................................................................................................. 66
Q. 1. What is the use of a constructor function in a class? Give a suitable example of a ................ 66
3.11 Further Readings ................................................................................................................... 66
4 Introduction................................................................................................................................... 67
4.1 Concept of inheritance .......................................................................................................... 67
4.2 Base class and derived class .................................................................................................. 68
4.3 Single inheritance .................................................................................................................. 68
4.3.1 Private Inheritance ........................................................................................................ 68
4.3.2 Public Inheritance .......................................................................................................... 69
4.3.3 Protected Inheritance ................................................................................................... 69
4.4 Multiple inheritance .............................................................................................................. 70
4.5 Nested Classes ....................................................................................................................... 71
4.6 Dynamic Memory Allocation/ Deallocation Operators New, Delete:-.................................. 71
4.7 The This Pointer..................................................................................................................... 72
4.8 Virtual functions .................................................................................................................... 74
4.9 Polymorphism ....................................................................................................................... 75
4.9.1 Static polymorphism or compile time polymorphism ................................................... 75
4.9.2 Dynamic polymorphism ................................................................................................ 75
4.9.3 Static and dynamic binding ........................................................................................... 75
4.10 Summary ............................................................................................................................... 76
4.11 Review Questions .................................................................................................................. 76
4.12 Further Readings ................................................................................................................... 76
5 Introduction: ................................................................................................................................. 77
5.1 C++ streams:-......................................................................................................................... 77
5.2 C++ Stream Classes:............................................................................................................... 77
5.3 Unformatted input/output Operations:- ............................................................................. 78
5.3.1 Overloaded operators >> and<< ................................................................................... 78
5.3.2 put() and get() functions:- ............................................................................................. 79
5.3.3 getline() and write() functions:- .................................................................................... 81
5.4 Formatted Console I/O Operations:-..................................................................................... 84
5.4.1 Defining Field Width:width() ......................................................................................... 85
5.4.2 Setting Precision: precision():- ...................................................................................... 87
5.4.3 FILLING AND PADDING :fill() .......................................................................................... 88
5.5 FORMATTING FLAGS,Bit Fields and setf():- ........................................................................... 90
5.6 Managing Output with Manipulators:- ................................................................................. 91
5.7 Designing our own manipulators:- ........................................................................................ 93
5.8 Summary ............................................................................................................................... 94
5.9 Exercises ................................................................................................................................ 95
Object Oriented Analysis And Design
6 Introduction :- ............................................................................................................................... 96
6.1 File Stream Classes:- .............................................................................................................. 96
6.2 Steps of File Operations:- ...................................................................................................... 96
6.2.1 Opening Files using Constructor: .................................................................................. 97
6.2.2 Opening Files using open() ........................................................................................... 99
6.3 Finding End of File: .............................................................................................................. 100
6.4 File Opening Modes: ........................................................................................................... 101
6.5 File Pointers and Manipulators: .......................................................................................... 101
6.5.1 Default actions: ........................................................................................................... 102
6.5.2 Functions for Manipulations of File pointer: .............................................................. 102
6.5.3 Specifying the Offset: .................................................................................................. 102
6.6 Sequential Input and Output Operations:........................................................................... 104
6.6.1 put() and get() Functions: ............................................................................................ 104
6.6.2 write() and read () functions: ...................................................................................... 105
6.7 Error Handling during File Operations: ............................................................................... 106
6.8 Command Line Arguments:-................................................................................................ 108
6.9 Summary ............................................................................................................................. 109
6.10 Exercises .............................................................................................................................. 110
7 Introduction................................................................................................................................. 111
7.1 Procedure-Oriented Paradigms ........................................................................................... 112
7.2 Procedure-Oriented Development Tools ............................................................................. 114
7.3 Object-Oriented Paradigm................................................................................................... 116
7.4 Object-Oriented Notation and Graphs ................................................................................ 118
7.5 Object–Oriented Analysis .................................................................................................... 124
7.5.1 Problem Understanding .............................................................................................. 125
7.5.2 Requirements Specification ........................................................................................ 126
7.5.3 Identification of Objects .............................................................................................. 126
7.5.4 Data flow diagram ....................................................................................................... 126
7.5.5 Textual Analysis ........................................................................................................... 126
7.5.6 Identification of services ............................................................................................. 128
7.5.7 Establishing interconnections ..................................................................................... 128
7.6 Object-Oriented Design ....................................................................................................... 129
7.7 Review of Problem Space Objects ....................................................................................... 129
7.7.1 Class Dependencies ..................................................................................................... 129
7.7.2 Organization of Class Hierarchies ................................................................................ 130
7.7.3 Design of Classes ......................................................................................................... 132
7.7.4 Design of Member Functions ...................................................................................... 133
7.7.5 Design of the Driver Program ...................................................................................... 134
Object Oriented Analysis And Design
7.8 Implementation................................................................................................................... 134
7.9 Prototyping Paradigm .......................................................................................................... 134
7.10 Summary ............................................................................................................................. 136
7.11 Questions: ........................................................................................................................... 137
8 Introduction................................................................................................................................. 139
8.1 Class Template:.................................................................................................................... 139
8.2 Class Templates with Multiple Parameters ......................................................................... 143
8.3 Function Templates ............................................................................................................. 144
8.4 Function Template with Multiple Parameters ..................................................................... 148
8.5 Overloading of Template Functions: ................................................................................... 148
8.6 Member Function Templates: ............................................................................................. 149
8.7 Non-Type Template Arguments .......................................................................................... 150
8.8 Summary ............................................................................................................................. 151
8.9 Question .............................................................................................................................. 152
9 Introduction:- .............................................................................................................................. 153
9.1 Principles of Exception handling:- ....................................................................................... 153
9.2 Exception handling mechanism:- ........................................................................................ 153
9.3 Throwing mechanism:- ........................................................................................................ 158
9.4 Catching mechanism:- ......................................................................................................... 158
9.4.1 Multiple Catch Statements:- ....................................................................................... 158
9.4.2 Catch All Exceptions:- .................................................................................................. 161
9.5 Rethrowing an Exception:- .................................................................................................. 162
9.6 Specifying Exceptions:- ........................................................................................................ 163
9.7 Summary ............................................................................................................................. 165
9.8 Exercises .............................................................................................................................. 166
10 References ............................................................................................................................... 167
11 EXAMS ..................................................................................................................................... 169
11.1 EXAM 1 ................................................................................................................................ 169
Object Oriented Analysis And Design
Objective
By the end of the chapter the reader will be to understand procedure-oriented
programming, object oriented paradigm, concepts and applications of OOP, and be
able to write simple C++ programs and statements.
1 INTRODUCTION
1.1 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?
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 the figure below, 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
Object Oriented Analysis And Design
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.
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
figure below. 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.
The major motivating factor in the invention of object-oriented approach is to remove some
of the flaws encountered in the procedural approach. OOP treats data as a critical element in
the program development and does not allow it to flow freely around the system. It ties data
more closely to the function that operate on it, and protects it from accidental modification
from outside function. OOP allows decomposition of a problem into a number of entities
called objects and then builds data and function around these objects. The organization of
data and function in object-oriented programs is shown in fig.1.3. The data of an object can
be accessed only by the function associated with that object. However, function of one
object can access the function of other objects.
Organization of data and function in OOP
Object A Object B
DATA DATA
Communication
FUNCTION FUNCTION
Object
DATA
FUNCTION
Object Oriented Analysis And Design
1.5.1 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 analysed 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. eg,
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.
Object Oriented Analysis And Design
OBJECTS: STUDENT
DATA
Name
Date-of-birth
Marks
1.5.2 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.
Object Oriented Analysis And Design
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.
4 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
Lay Eggs
Attributes Attributes
………… ………..
………... ………..
Allows the programmer to reuse a class i.e almost, but not exactly, what he wants, and to
tailor the class in such a way that it does not introduced any undesirable side-effects into the
rest of classes.
1.5.5 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” 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.
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 behaviour,
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 Oriented Analysis And Design
Object has a life cycle. They can be created and destroyed. Communication with an
object is feasible as long as it is alive.
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
cannot 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-centred 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.
Object-oriented programming is not the right of any particular languages. Like structured
programming, OOP concepts can be implemented using languages such as C and Pascal.
However, programming becomes clumsy and may generate confusion when the programs
grow large. A language that is specially id designed to support the OOP concepts makes it
easier to implement them.
Object Oriented Analysis And Design
The languages should support several of the OOP concepts to claim that they are
object-oriented. Depending upon the features they support, they can be classified into the
following two categories:
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 modelling
• 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
Object Oriented Analysis And Design
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, analyse, design and implement future system.
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.
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.
Printing A String
#include<iostream> Using namespace
std; int main()
{
cout<<” c++ is better than c \n”;
return 0;
}
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.
1.10.2 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:
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.
1.10.5 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 ()
{
…………..
………….
}
Object Oriented Analysis And Design
1.11 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
Float number1, number2,sum, average; Cin >> number1; // Read Numbers Cin >>
number2; // from keyboard Sum = number1 + number2;
Average = sum/2;
Cout << ”Sum = “ << sum << “\n”;
Cout << “Average = “ << average << “\n”; Return 0;
} //end of example
Program 1.11.1
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.
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 . 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:
We can also cascade input iperator >> as shown below: Cin >> number1 >> number2;
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.
• One of the major features of C++ is classes. They provide a method of binding
together data and functions which operate on them. Like structures in C, classes are user-
defined data types.
USE OF CLASS
public:
void getdata(void);
void display(void);
};
void person :: getdata(void)
{
cout << “Enter name: “;
cin >> name;
cout << “Enter age: “;
cin >> age;
Object Oriented Analysis And Design
}
Void person : : display(void)
{
cout << “\nNameame: “ << name;
cout << “\nAge: “ << age;
}
Int main()
{
person p; p.getdata(); p.display();
Return 0;
} //end of example
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.
A typical C++ program would contain four sections. This section may be placed in
separate code files and then compiled independently or jointly.
It is a common practice to organize a program into three separate files. The class
declarations are placed in a header file and the definitions of member functions go into
another file. This approach enables the programmer to separate the abstract specification of
the interface from the implementation details (member function definition).
Finally, the main program that uses the class is places in a third file which “includes: the
previous two files as well as any other file required.
Object Oriented Analysis And Design
Include Files
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
Like C programs can be created using any text editor. For example, on the UNIX, we can
use vi or ed text editor for creating using any text editor for creating and editing the
source code. On the DOS system, we can use endlin or any other editor available or a
word processor system under non-document mode.
Some systems such as Turboc C++ provide an integrated environment for developing
and editing programs
Object Oriented Analysis And Design
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.
The process of compiling and linking again depends upon the operating system. A few
popular systems are discussed in this section.
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.
1.16 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.
Object Oriented Analysis And Design
• 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:
• Cascading • Float
• Namespace • Get from Operator
• Class • Input operator
• Object • Turbo c++
• Operator overloading • iostream
• Comments • int
• Output operator • using
• cout • iostream.h
• edlin • windows
• return () • Keyboard
1.17 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:
Objective
By the end of the chapter the reader will be to understand Function Definition and
Declaration, Arguments to a Function, Calling Functions, Inline Functions, Member
Function Definition, and Declaration of Objects as Instances of a Class, Static Class
Members and Friend Classes
2 INTRODUCTION
Functions are the building blocks of C++ programs where all the program activity occurs. Function
is a collection of declarations and statements.
A function has a clearly defined objective (purpose) and a clearly defined interface with other
functions in the program. Reduction in program size is another reason for using functions. The
functions code is stored in only one place in memory, even though it may be executed as many
times as a user needs.
}
//function definition void disp()
{
cout<<”Welcome to the GJU of S&T\n”;
cout<<”Programming is nothing but logic implementation”;
}
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
Object Oriented Analysis And Design
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:
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 :
Arguments(s) of a function is (are) the data that the function receives when called/invoked
from another function.
It is not always necessary for a function to have arguments or parameters. The functions
add ( ) and divide ( ) in program 6.3 did not contain any arguments. The following example
illustrates the concept of passing arguments to function SUMFUN ( ):
return type
………………………….
………………………….
//function declaration
{
………………………….
…………………………. Body of the function
………………………….
}
No semicolon here
C++ allows a function to assign a parameter the default value in case no argument for that
parameter is specified in the function call. For example.
return U+2
}
Void pattern (char M, int B=2)
{
for (int CNT=0;CNT<B; CNT++) cout<calc(CNT) <<M; cout<<endl;
}
Void main ()
{ Pattern(‘*’); Pattern (‘#’,4)’ Pattern (;@;,3);
}
Object Oriented Analysis And Design
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 :
(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
Void calculate (float, float, float); //function prototype clrscr();
Cin>>principal;
Object Oriented Analysis And Design
Cout<<”\nRate of interest:”; Cin>>rate;
“<<interest;
}
Call by Reference: - A reference provides an alias – an alternate name – for the variable, i.e., the
same variable’s value can be used by two different names : the original name and the alias name.
In call by reference method, a reference to the actual arguments(s) in the calling program is passed
(only variables). So the called function does not create its own copy of original value(s) but works
with the original value(s) with different name. Any change in the original data in the called function
gets reflected back to the calling function.
It is useful when you want to change the original variables in the calling function by the called
function.
cout<<endl<<”num2: “<<num2;
swap(num1,num2); //function call cout<<”\n\nAfter swapping : \Num1: “<<num1;
Object Oriented Analysis And Design
cout<<endl<<”num2: “<<num2;
getch();
}
//function fefinition swap()
void swap (int & a, int & b)
{
Int temp=a;
a=b;
b=temp;
}
inline function_header
{
body of the function
}
For example,
//function definition min()
inline void min (int x, int y)
cout<< (x < Y? x : y);
}
Void main()
{
int num1, num2;
Object Oriented Analysis And Design
cout<<”\Enter the two intergers\n”;
cin>>num1>>num2;
min (num1,num2; //function code inserted here
------------------
------------------
}
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 except in the following scenarios.
1. For functions returning values and having a loop or a switch or a goto statement.
2. For functions that do not return value and having a return statement.
3. For functions having static variable(s).
4. If the inline functions are recursive (i.e. a function defined in terms of itself).
1. Local Scope
2. Function Scope
3. File Scope
Object Oriented Analysis And Design
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;
}
}
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,
}
//function definition add2()
coid add2(float x,float y,float z)
{
Float sum = 0.0; sum = x+y+z; cout<<sum;
}
Object Oriented Analysis And Design
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;
void square (int n)
{
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 own 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;
};
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 data members
Public
data members and Can only be accessed from outside the class
member functions
Object Oriented Analysis And Design
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 C++, the member
functions can be coded in two ways :
(a) Inside class definition
(b) Outside class definition using scope resolution operator (::)
The code of the function is same in both the cases, but the function header is different as explained
below :
When a member function is defined inside a class, we do not require to place a membership label
along with the function name. We use only small functions inside the class definition and such
functions are known as inline functions.
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];
Object Oriented Analysis And Design
public :
void init_data()
{
- - - - - //body of function
-----
}
void display_data()
}
};
student ob; //class variable (object) created
-----
-----
Ob.init_data(); //Access the member function ob.display_data(); //Access the member function
- ----
-----
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.
(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 :
(a) Declare it within the class. (b) Define it outside the class.
Object Oriented Analysis And Design
For example
Class student
{
Static int count; //declaration within class
-----------------
-----------------
-----------------
};
The static data member is defined outside the class as :
We can also initialize the static data member at the time of its definition as:
Class student
{
Static int count;
----------------- public :
-----------------
-----------------
static void showcount (void) //static member function
{
Cout<<”count=”<<count<<”\n”;
Object Oriented Analysis And Design
}
};
int student ::count=0;
Here we have put the keyword static before the name of the function shwocount ().
a static member function fifers from the other member functions in the following
(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();
In C++ , a class can be made a friend to another class. For example, class TWO; // forward
{
………………………
…………….
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.
2.11 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
Object Oriented Analysis And Design
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
Q. 5. What is inline function? When will you make a function inline and why ?
Sname 20 characters
Eng, math, science float (marks in three subjects) Total float
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.
Object Oriented Analysis And Design
Objective
By the end of the chapter the reader will be to understand declaration of constructors,
destructors, function upload and type conversions
INTRODUCTION
A constructor (having the same name as that of the class) is a member function which is
automatically used to initialize the objects of the class type with legal initial values. Destructors are
the functions that are complimentary to constructors. These are used to de- initialize objects when
they are destroyed. A destructor is called when an object of the class goes out of scope, or when the
memory space used by it is de allocated with the help of delete operator.
It is defined like other member functions of the class, i.e., either inside the class definition or
outside the class definition.
private :
float length, breadth;
public:
rectangle ()//constructor definition
Object Oriented Analysis And Design
{
//displayed whenever an object is created cout<<”I am in the constructor”;
length-10.0;
breadth=20.5;
}
float area()
{
return (length*breadth);
}
};
void main()
{
clrscr();
rectangle rect; //object declared
cout<<”\nThe area of the rectangle with default parameters is:”<<rect.area()<<”sq.units\n”;
getch();
}
{
radius=r;
strcpy (shape, “circle”);
}
figure (float s1,float s2) //constructor for rectangle strcpy
{
Side1=s1; Side2=s2;
}
void area() //calculate area{
float ar,s;
if(radius==0.0)
{
if (side3==0.0)
ar=side1*side2;
else
ar=3.14*radius*radius;
cout<<”\n\nArea of the “<<shape<<”is :”<<ar<<”sq.units\n”;
Object Oriented Analysis And Design
}
};
Void main()
{ Clrscr();
Class fun
{
Float x,y; Public:
}
Fun (fun &f) //copy constructor
}
Void display (void)
{
{ Cout<<””<<y<<end1;
}
};
Here we have two constructors, one copy constructor for copying data value of a fun
Object Oriented Analysis And Design
object to another and other one a parameterized constructor for assignment of initial values given.
{
Int empl_no; Float salary;
Public:
Employee() //default constructor
{}
Employee(int empno,float s)//constructor with arguments
{ Empl_no=empno; Salary=s;
}
}
Void display (void)
{ Cout<<”\nEmp.No:”<<empl_no<<”salary:”<<salary<<end1;
}
};
Void main()
{
int eno; float sal; clrscr();
cout<<”Enter the employee number and salary\n”;
cin>>eno>>sal;
Object Oriented Analysis And Design
salary\n”; cin>eno>>sal;
getch();
}
float i(2.5), j(7.8); //I,j, initialized with valurs 2.5 and 7.8
Private:
Int num1, num2,num3; Public:
};
//Default constructor definition add::add(int n1, int n2)
{
num1=n1;
Object Oriented Analysis And Design
num2=n2;
num3=n0;
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
If two constructors for the above class add are
ii) These should be declared in the public section for availability to all the functions.
iii) Return type (not even void) cannot be specified for constructors.
iv) These cannot be inherited, but a derived class can call the base class constructor.
v) These cannot be static.
vi) Default and copy constructors are generated by the compiler wherever required. Generated
constructors are public.
vii) These can have default arguments as other C++ functions. (ix) A constructor can call
member functions of its classAn object of a class with a constructor cannot be used as a
member of a union.
viii) A constructor can call member functions of its class.
ix) We can use a constructor to create new objects of its class type by using the syntax.
a. Name_of_the_class (expresson_list) For example,
int num1,num2,num3;
public :
add(int=0, int=0); //default argument constructor
//to reduce the number of constructors void sum();
void display();
~ add(void); //Destructor
};
//Destructor definition ~add()
Add::~add(void) //destructor called automatically at end of program
{
Num1=num2=num3=0;
the”Cout<<”\nAfter the final execution, me, the object has entered in
}
//function definition sum () Void add::sum()
{
num3=num1+num2;
}
//function definition display () Void add::display ()
{
Cout<<”\nThe sum of two numbers is “<<num3<<end1;
}
void main()
{
Add obj1,obj2(5),obj3(10,20): //objects created and initialized clrscr();
Obj1.sum(); //function call
Object Oriented Analysis And Design
Obj2.sum(); Obj3.sum();
cout<<”\nUsing obj1 \n”; obj1.display(); //function call cout<<”\nUsing obj2 \n”; obj2.display();
cout<<”\nUsing obj3 \n”;
obj3.display();
}
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.
The Syntax of declaration of an Operator function is as follows: 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
Object Oriented Analysis And Design
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
}
We can declare these Global Operator Functions as being friends of any other class.
Examples of operator overloading:
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
Object Oriented Analysis And Design
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
Object Oriented Analysis And Design
{
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.
Defining assignment of strings as follows can solve this problem, class student
{ Public:
char name;
int rollno;
student ( ) {name = new char [20];}
~ student ( ) {delete [ ] name ;}
student & operator = (const student & )
}
student & student :: Operator = (const student &e)
{
if (this ! =&e)
delete [] name;
name = new char [20];
strcpy(name, name);
}
return *this;
}
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;
Here, first 100 is assigned to x and then x to y. Consider another statement, 13 = t1 + t2;
This statement used in program 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
Object Oriented Analysis And Design
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:
.....
.....
distance (int dist) //constructor
{
feet = dist/12;
inches = dist%12;
}
};
The following conversion statements can be coded in a function :
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,
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.
If we take a single-argument constructor function for converting the argument’s type to the class
type (whose member it is). So the argument is of the source class and being passed to the
destination class for the purpose of conversion. Therefore it is compulsory that the conversion
constructor be kept in the destination class.
2.22 Summary
In this lesson , we discussed the concept and type of constructor and destructor. All the
operators that can be overloaded. Even after writing operator overloaded functions, the precedence
of operators remains unchanged. The ‘++’ & ‘--’ operators can be used as Postfix or Prefix
operators. So, separate functions overloading them for both the different applications have been
shown. we are of a view that Private data of a class can be accessed only in member functions of
that 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.
Operator Overloading: Overloaded operators are implemented as functions and can be member
functions or global functions.
Object Oriented Analysis And Design
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”.
Objective
By the end of the chapter the reader will be to understand the concept of inheritance, and
polymorphism,
3 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:
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
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.
Inheritance is a concept which is the result of commonality between classes. Due to this
mechanism, we need not repeat the declaration as well as member functions in a class if they
are already present in another class. For example, consider the classes namely “minister”
and “prime minister”. Whatever information is present in minister, the same will be present in
prime minister also. Apart from that there will be some extra information in class prime
minister due to the extra privileges enjoyed by him. Now, due to the mechanism of inheritance,
it is enough only to indicate that information which is a specific to prime minister in its class.
In addition, the class prime minister will inherit the information of class minister.
Object Oriented Analysis And Design
class Employee
{ public:
char* name;
int age;
char* address; int salary; char*department; int id;
};
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.
class A { /*......*/);
class C: private A
Object Oriented Analysis And Design
{ /*
.
.
.
.
*/
}
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.
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. No private
class closed_shape
{
public:
.
.
Object Oriented Analysis And Design
.
}
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:
.
.
.
.
}
*/
};
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.
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
In C++, the pointer support dynamic memory allocation (allocation of memory during runtime).
While studying arrays we declared the array size approximately. In this case if the array is less
than the amount of data we cannot increase it at runtime. So, if we wish to allocate memory as
and when required new operator helps in this context.
char * cptr
Object Oriented Analysis And Design
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;
delete [ ] empno; //some versions of C++ may require size
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,
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
Object Oriented Analysis And Design
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 :
Void main ()
{
Per p1(“REEMA:, 10000), p2(“KRISHANAN”,20000), p3 (“GEORGE”, 50000);
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.
Object Oriented Analysis And Design
3.9 Polymorphism
Polymorphism means ‘one name multiple forms’. Runtime polymorphism can be achieved by
using virtual functions. The polymorphism implementation in C++.
3.9.1 Static polymorphism or compile time polymorphism
When the function volume ( ) is invoked, the passed parameters determine which one to be
executed. This resolution takes place at compile time.
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.
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.
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.
Object Oriented Analysis And Design
Objective
By the end of the chapter the reader will be to understand the concept of C++ streams, C++
streams classes, Unformatted I/O Operations, Formatted console I/O Operations, Managing
output with manipulators, Design Our Own Manipulators
4 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 cannot 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(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
cin.get( c ) //get a character from the keyboard and assigns it to c while( c!=’\n’)
}
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
Object Oriented Analysis And Design
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);
{ cout.put(c);
cin.get ( c);
}
The program illustrate the use of two character handling functions.
Program 5.1
{
int count=0;
char c;
cout<<”INPUT TEXT \n”;
Object Oriented Analysis And Design
cin.get( c );
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
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;
Object Oriented Analysis And Design
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 demonstrates the use of >> and getline() for reading the strings.
Program
#include <iostream>
using namespace std;
int main()
{ int size=20;
char city[20];
cout<<”enter city name:\n “;
cin>>city;
cout<<”city name:”<<city<<”\n\n”; cout<<”enter city name again: \n”;
cin.getline(city,size);
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
Object Oriented Analysis And Design
P Pr Pro Prog
Pr
P
C++ Programming
C++ Progr
The last line of the output indicates that the statement cout.write(string1,10);
Function Task
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.
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:
Object Oriented Analysis And Design
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
{
int item[4] ={ 10,8,12,15}; int cost[4]={75,100,60,99}; cout.width(5); cout<<”Items”;
cout.width(8); cout<<”Cost”; 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];
}
cout<<”\n Grand total = “; cout.width(2); cout<<sum<<”\n”;
return 0;
We can also combine the field specification with the precision setting.example:
cout.precision(2); cout.width(5); cout<<1.2345;
The first two statement instruct :”print two digits after the decimal point in a field of five
character width”.Thus the output will be:
1 2 3
Program shows how the function width() and precision() are jointly used to control
the output format.
Program 5.5
{
cout<<”precision set to 3 digits\n\n”;
Object Oriented Analysis And Design
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);
cout<<”sqrt(10) = “ <<sqrt(10)<<”(default setting)\n”;
return 0;
}
The output is
1 1
2 1.41
3 1.73
4 2
5 2.24
Where ch represents the character which is used for filling the unused positions.Example:
cout.fill(‘*’); cout.width(10); cout<<5250<<”\n”; The output would be:
* * * * * * 5 2 5 0
Object Oriented Analysis And Design
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
{ 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;
cout.setf(ios::internal,ios::adjustfield); cout.setf(ios::scientific,ios::floatfield);
cout.width(15);
cout<<-12.34567<<”\n”;
<<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;
for (int n=1;n<=10;n++)
{
term=1.0/float(n);
Object Oriented Analysis And Design
sum=sum + term;
cout<<setw(5)<<n<<setw(14)<<setprecision(4) <<setiosflags(ios::scientific)<<term
<<setw(13)<<resetioflags(ios::scientific) <<sum<<endl;
}
return 0;
}
The general form for creating a manipulator without any argument is ostream &
manipulator (ostream & output)
{
……………
…………….(code)
…………….. return output;
}
The following program illustrate the creation and use of user defined manipulators.
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(‘*’);
Object Oriented Analysis And Design
}
int main()
{
cout<<currency<<form<<7864.5;
return 0;
4.8 Summary
.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 the
destination 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 output
operations.These classes are declared in the header file ‘iostream’.
cin represents the input stream connected to standard input device and cout represents the
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/O
functions getline() and write() respectively.
The header file iomanip provides a set of manipulator functions to manipulate output
formats.
Key Terms
adjustfield output stream console I/O operations
precision()
fill() put()
flags setfill()
get() setiosflags()
getline() setw() ios
Object Oriented Analysis And Design
4.9 Exercises
5.1.What is a stream?
5.2.Describe briefly the features of I/O system supported by C++.
5.3.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?
5.5.What is the role of iomanip file?
5.6. What is the basic difference between manipulators and ios member functions in
implementation?Give examples.
Object Oriented Analysis And Design
Objective
By the end of the chapter the reader will be to understand the concept of stream classes,
steps of file operations, Finding end of file, opening modes, File pointers and manipulators,
Sequential input and output operations, Error handling functions, Command Line argument
5 Introduction:-
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.
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.
Object Oriented Analysis And Design
fstreambase Provides operations common to file streams.Serves as a base for
fstream,ifstream and ofstream class.Contains open() and close()
functions.
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.
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
{
ofstream outf(“ITEM”);
cout <<”enter item name: “;
char name[30];
cin >>name;
outf <<name <<”\n”;
cout <<”enter item cost :”;
float cost;
cin >>cost;
outf <<cost <<”\n”;
outf.close();
ifstream inf(“item”);
inf >>name; inf >>cost; cout <<”\n”;
cout <<”item name : “ << name <<”\n”; cout <<”item cost: “ << cost <<”\n”;
inf.close();
return 0;
} fin.close(); fin.open(“capital”);
{
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.
Parameter Meaning
• tellp() Give the current position of the put pointer. For example, the statement
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
{
char string[80]; cout<<”enter a string \n”; cin>>string;
{
file.get(ch);
cout<<ch;
}
return 0;
{
float height[4] ={ 175.5,153.0,167.25,160.70};
ofstream outfile;
outfile.open(filename);
outfile.write((char *) & height,sizeof(height));
outfile.close();
for (int i=0;i<4;i++)
height[i]=0; ifstream infile; infile.open(filename);
{
cout.setf(ios::showpoint);
cout<<setw(10)<<setprecision(2)<<height[i];
} infile.close(); return 0;
}
5.7 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.
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)
}
Object Oriented Analysis And Design
else
{
infile.clear(); //clear error state
……….
……….
}
……..
………..
The function clear() resets the error state so that further operations can be attempted.
5.8 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 always
as 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:
The argv[0] alwayas represents the command name that invokes the program.The character
pointer argv[1], and argv[2] can be used as file names in the file opening statements as
shown:
…………
…………
inline.open(argv[1]); //open data file for reading
…………..
Object Oriented Analysis And Design
…………..
outfile.open(argv[2]); //open result file for writing
…………..
…………..
5.9 Summary
1.Stream is nothing but flow of data .In object oriented programming the streams are
controlled using classes.
2.The istream and ostream classes control input and output functions respectively.
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()
Object Oriented Analysis And Design
5.10 Exercises
6.1.What are input and output streams?
6.2.What are the various classes available for file operations.
6.3. 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?
Object Oriented Analysis And Design
Objective
By the end of the chapter the reader will be to understand the concept of Procedure oriented
paradigm, Procedure oriented development tools, Object oriented, Object oriented analysis,
Object oriented design, System implementation, Prototyping paradigm
6 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,
Object Oriented Analysis And Design
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.
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.
Object Oriented Analysis And Design
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:
phase output
Problem Definition • Problem statement sheet
(why) • Project request
Analysis • Requirements document
(What) • Feasibility Report
• Specification Document
Design • Design Document
(How) • Test Class design
Coding • Code document
(How) • Test plan
• User manual
Testing • Tested code
(What and How) • Test results
• System manual
Maintenance • Maintenance log sheets
• Version documents
A large number of tools are used in the analysis and design of the systems. It is important to
note that the process of systems development has been undergoing changes over the years due
to continuous changes in the computer technology. Consequently, there has been an
evolution of new system development tools and techniques. These tools and techniques
provide answers to how questions of the system development.
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).
Object Oriented Analysis And Design
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 Analysis And Design
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
By developing specifications of the objects found in the problem space, a clear and well-
organized statement of the problem is actually built into application. These objects form a high-
level layer of definitions that are written in terms of the problem space. During the refinement
of the definitions and the implementation of the application objects, other objects and identified
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.
In contrast to the traditional top-down functional decomposition approach, the object oriented
approach has many attribute of both the top-down and bottom-up design. The top functional
decomposition techniques can be applied to the design of individual classes, while the
final system can be constructed with the help of class modules using the bottom-up approach.
6.4 Object-Oriented Notation and Graphs
Graphical notations are an essential part of any design and development process, and object-
oriented design is no exception. We need notations to represent classes, objects, subclasses, and
their inter-relationships. Unfortunately, there are no standard notations for representing the
object and their interactions. Authors and researchers have used their own notations. Some of
them are used more frequently while others are not. Figures 2.6 show some of the commonly
used notations to represent the following:
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.
Object Oriented Analysis And Design
Class name
Class Name
Class Name
Data
Function Data
Function 1
Function 2 Data
Functions
Function 3
------------------------
Is A
Is A Is A
Object A Object B
A
Object Oriented Analysis And Design
Base Class
B
Derived Class
Vehicle
A Kind of
Car Cycle
Vehicle
(a)
Object Oriented Analysis And Design
Car Cycle
(b)
House
A Part of
Door Window
(a)
House
Object Oriented Analysis And Design
Window
Door
(b)
Fig 7.11 Composition relationship
B C D
B1 B2
Server Client
Process Process
A B
Process Process
C D
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
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.
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)
The application can be represented in the form of a data flow diagram indicating how the
data moves from one point to another in the system, the boxes and data store in the data
flow diagram are good candidate for the objects. The process bubbles correspond to the
procedures. Fig 7.16 may be expanded to include more information or condensed as
illustrated in fig. 7.17 to show only one bubble.
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
Object Oriented Analysis And Design
Data store
Data
Store Stores
Shipment information
Shipping Notice Collection
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:
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.
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.
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.
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 X Y
A B C D E
Fig. 7.18
6.7.3 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:
• The public interface of a class should have only functions of the class.
• An object of one class should not send a message directly to a member of another class.
• A function should be declared public only when it is required to be used by the objects
of the class.
• A class should be dependent on as few classes as possible.
• Interaction between two classes must be explicit.
• The top class of a structure should represent the abstract model of the target concept.
Function 1
Data
Function 2
B C D
B1 B2 D1 D2
B17
D17
Object Oriented Analysis And Design
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.
6.8 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.
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
Object Oriented Analysis And Design
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:
• We can produce understandable specifications which are correct and complete as far as
possible.
• The user can understand what is being offered.
• Maintenance changes that are required when a system is installed are minimized.
• Development engineers can work from a set of specifications which have been tested and
approved.
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.
Object Oriented Analysis And Design
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.
6.10 Summary
• 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.
6.11 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?
Object Oriented Analysis And Design
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:
Objective
By the end of the chapter the reader will be to understand the concept of 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
7 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 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;
}
};
Object Oriented Analysis And Design
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
Object Oriented Analysis And Design
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
{
Object Oriented Analysis And Design
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;
Object Oriented Analysis And Design
vector <float>v2;
v1=x;
v2=y;
float R=v1*v2; cout<<”R=”<<R<<”\n”; return 0;
}
#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;
};
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:
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:
int main ()
{
fun(100,200,11.22,33.44);
return 0;
}
Another function often used is sort () for sorting arrays of various types such as int and
double. The following shows a function template for bubble sort:
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;
}
}
Where swap () has been defined as a function template. Here is another example where a
function returns a value.
Object Oriented Analysis And Design
template<class T>
T max ( T x, T y)
{
return x>y ? x : y;
}
A function generated from a function is called a template function. Program of Bubble Sort
demonstrates the use of two template functions in nested from for implementing the bubble
sort algorithm.
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
cout << “sorted x-array:”; for ( int i=0; i<5; i + + ) cout << x[i] << “ ” ;
cout << endl ;
cout << “ Sorted y-array : ” ; for (int j=0; j<5; j + +) cout << y[j] <<
“ ”;
cout << endl ;
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;
}
#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;
}
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……….
Object Oriented Analysis And Design
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.
Object Oriented Analysis And Design
7.8 Summary
Keywords:
7.9 Question
References:
Objective
By the end of the chapter the reader will be to understand the concept of Principles of
Exception handling, Exception handling mechanism, Throwing mechanism, Catching
mechanism, Rethrowing an Exception, Specifying Exception
8 Introduction:-
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.
…………….
…………….
}
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.
{
int a,b;
cout<<”enter the values of a and b”;
cin>>a;
cin>>b;
int x = a- b;
try
Object Oriented Analysis And Design
{
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
Object Oriented Analysis And Design
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
………….
}
Object Oriented Analysis And Design
………..
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
{
cout<<”we are outside the function”;
if ( ( x-y) != 0)
{ int r=z/(x-y);
cout<<”result = “<<r;
}
else
{
throw(x-y);
}
}
int main()
{
try
{
cout<<”we are inside the try block”;
divide(10,20,30);
divide(10,10,20);
Object Oriented Analysis And Design
}
catch (int i)
{
cout<<”caught the exception”;
}
return 0;
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.
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 block1
}
catch(type 2 arg)
{
//catch block 2
}
……………..
…………….
catch (type N arg)
{
//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.
The below program shows the example of multiple catch statements. Program9.3
{
try
{
if (x==1) throw x; //int else
Object Oriented Analysis And Design
else
if(x==0) throw ‘x’; //char
}
catch(char c) //Catch 1
{
cout<<”Caught a character \n”;
}
catch (int m) //Catch 2
{ cout <<”caught an integer\n”;
}
catch (double d) //catch 3
{ cout<<”caught a double \n”;
}
cout<<”end of try –catch system \n\n”;
}
int main()
{
cout<<”Testing multiple catches \n”;
cout<<”x== 1 \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
Object Oriented Analysis And Design
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.
}
The below program illustrate the functioning of catch(…) Program 9.4
{
try
{
if (x== 0) throw x; //int
if ( x== -1) throw ‘x’; //char if ( x== 1) throw 1.0; //float
}
catch(. . .) //catch all
{
cout<<”caught an exception \n”;
}
}
int main()
{
cout<<”testing generic catch\n”;
test(-1); test(0); test(1); return 0;}
Object Oriented Analysis And Design
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.
Program 9.5
RETHROWING AN EXCEPTION
#include <iostream>
using namespace std;
void divide(double x, double y)
{
cout<<”Inside Function \n”;
try
{ if (y== 0.0)
throw y; //throwing double else
{
cout<<”Caught double inside a function \n”;
throw; //rethrowing double
}
cout<<”end of function\n\n”;
Object Oriented Analysis And Design
}
int main()
{
cout <<”inside main \n”;
try
{ 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.
{
if (x== 0) throw ‘x’; //char
else
if (x== 1) throw x; //int
else
int main()
{
try
{
cout<<”testing throw restrictions\n”;
cout<<”x== 0\n “;
test (0);
cout<<”x==1 \n”;
test(1);
cout<<”x== -1 \n”;
Object Oriented Analysis And Design
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;
8.7 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.
Object Oriented Analysis And Design
5.The catch block receives the exception send by the throw block in the try block.
6.Multiple catch blocks can be used in a program .
7.It is also possible to define single or default catch () block from one or more exception
of different type. In such situation a single catch block is used for catch exceptions
thrown by the multiple throw statement.
8.It is also possible to again pass the exception received to another exception handler i.e
an exception is thrown from catch() block and this is known as rethrowing the exception.
9.The specified exception are used when we want to bind the function to throw only
specified exceptions.Using a throw list condition can also do this.
Key Terms
abort() function multiple catch asynchronous exception
out-of-range index catch block synchronous exception
catch(…..) statement syntactic error exception handler
throw
8.8 Exercises
Bibliography
[Alexander-Ishikawa-Silverstein-Jacobson-1977b] Christopher Alexander, Sara Ishikawa,
Murray
Silverstein, and Max Jacobson. A Pattern Language. Oxford University Press. 1977.
[Alexander-1979] Christopher Alexander. The Timeless Way of Building. Oxford
University Press.
1979.
[Anderson-2003] Kenneth M. Anderson. Object Design: Roles, Responsibilities and
Collaborations.
Addison-Wesley/Pearsons Education. 2003.
[Ashmore-Henson-Chancellor-Nelson-2004] Perryn Ashmore, Joel Henson, Jeff
Chancellor, and
Mark Nelson. “Is you enterprise architecture all it can be?”. Business Process Trends. June
2004.
[Bass-Clements-Kazman-2003] Len Bass, Paul Clements, and Rick Kazman. Software
Architecture
in Practice. second edition. Addison Wesley. 2003.
[Beane-Giddings-Silverman-1984] J. Beane, N. Giddings, and J. Silverman. “Quantifying
Software
Designs”. Proceedings of the Seventh International Conference on Software Engineering.
314-322. March 1984.
[Beck-Cleal-1999] Kent Beck and Dave Cleal. “Optional Scope Contracts”. 1999.
[Beck-Fowler-2000] Kent Beck and Martin Fowler. Extreme Programming Explained.
Addison
Wesley. 0201710919. 2000.
[Ben-Abdallah-et.al-2004] H. Ben-Abdallah, N. Bouassida, F. Gargouri, and A. Ben-
Hamadou. “A
UML Based Framework Design Method”. Journal of Object Technology. 3. 8. 2004.
[Booch-1994] Grady Booch. Object-Oriented Analysis and Design with Applications.
Benjamin
Cummings. 1994.
[Booch-Rumbaugh-Jacobson-1999] Grady Booch, Jim Rumbaugh, and Ivar Jacobson. The
Unified
Modeling Language Reference Guide. Addison-Wesley. 1999.
[Brickley-Smith-Zimmermann-2001] James Brickley, Clifford W. Smith, and Jerold
Zimmermann.
Managerial Economics and Organizational Architecture . McGraw-Hill. 2001.
[Buschmann-Meunier-Rohnert-Sommerlad-Stal-1996] Frank Buschmann, Regine Meunier,
Hans
Rohnert, Peter Sommerlad, and Michael Stal. Pattern-Oriented Software Architecture. A
system of patterns. John Wiley & Sons. 1996.
[Cantor-1998] Murray R. Cantor. Object-Oriented Software Management. Wiley. 1998.
[Carlson-2001] D. Carlson. Modeling XML Applications with UML. Addison-Wesley.
2001.
[Clements-Kazman-Klein-2002] Paul Clements, Rick Katzman, and Mark Klein.
Evaluating Software Architectures. Methods and case studies. Addison-Wesley. 2002.
[Coad-Yourdon-1991a] P. Coad and E. Yourdon. Object Oriented Analysis. Yourdon.
1991.
[Coad-Yourdon-1991b] P. Coad and E. Yourdon. Object Oriented Design. Yourdon. 1991.
Object Oriented Analysis And Design
[Cockburn-2001] Alister Cockburn. Writing Effective Use Cases. Addison-Wesley. 2001.
[Coleman-Arnold-Bodoff-1994] D. Coleman, P. Arnold, S. Bodoff, C. Dollin, H. Gilchrist,
F.
Hayes, and P. Jeremes. Object-Oriented Development. The Fusion Method. rentice-Hall.
1994.
[Duell-1997] Object Magazine. Michael Duell. “ Non-software examples of software
design patterns ”. 54. July 1997.
254
Object Oriented Analysis And Design
10 EXAMS
10.1 EXAM 1
Answer Question 1 (ONE) and any 2(TWO) other questions
Question One
a) Briefly explain the difference between the following pairs of terms. You should include
small examples to illustrate your answers [12 marks]
i. Class / object
ii. Attribute / operation
iii. Association / multiplicity
iv. Subclass / superclass
v. Message / Method
vi. Encapsulation /data hiding
b) Draw a class diagram, including class attributes, to represent the information given in the
paragraph below. [5 marks]
A dental surgery keeps information about its patients, who may be either private or health
service. For each patient the surgery records the name, address, phone number, date of birth
and either the health service number or the payment method.
d) Visibility is used to specify which attributes and operations can be seen by the class
objects. Discuss the Four levels of Visibility [4 marks]
Question Two
a) A hospital admission system records the details of the admission, treatment and discharge
of all patients. It also provides a number of official reports to satisfy the requirements of
external authorities. Admission consists of the following tasks: Administration staff enters
the patient’s personal details from a completed hospital admission form and sometimes
helping them to complete the form. Next they allocate appropriate hospital accommodation
if one or more nights stay is required.
Following this they assign a doctor to attend for an initial examination, and check (in the
case that private medical care is required) that the patient has valid medical insurance.
Doctors and nurses use the system to record medical care given to patient during their stay.
(This medical care consists of treatments given and drugs administered). Only a doctor may
prescribe drugs to a patient, and this information is also recorded in the system. Both
doctors and nurses may administer drugs and doses are similarly recorded. Only doctors
have the authority to discharge a patient, and this information is, again, recorded within the
system.
i) Identify the use cases and actors of the hospital admissions system. [8 marks]
ii) Develop a possible use case diagram for the above narrative [4 marks]
b) Draw a state diagram to illustrate the behavior of a child’s bank account, where no
overdraft is allowed. The account is empty to start with. Money can then be deposited, to
put the account in credit, and taken out as long as the account does not become overdrawn.
The account can only be closed when the balance is Zero. [8 marks]
Object Oriented Analysis And Design
Question Three
Each elevator has a set of m buttons, one for each floor. These illuminate when pressed
and cause the elevator to visit the corresponding floor. The illumination is canceled when
the elevator visits the corresponding floor.
Each floor, except the first floor and top floor has two buttons, one to request and up-
elevator and one to request a down-elevator. These buttons illuminate when pressed. The
illumination is canceled when an elevator visits the floor and then moves in the desired
direction.
When an elevator has no requests, it remains at its current floor with its doors closed.
i) Using the above narrative provide a textual description of the above events in point form
[10 marks]
ii) Draw a use case diagram for the above narrative [10 marks]
Question Four
i) For the (question Three) narrative draw a class diagram [10 marks]
ii) Develop a sequence diagram for the events in the elevator narrative above for Serving Door
Button [10 marks]
Question Five
i) Write a program that allows the user to find the maximum of three given numbers. The
program should have: [14 marks]
ii) Create a class diagram for the program you have written in Five (i) above. [6 marks]