0% found this document useful (0 votes)
61 views791 pages

C++ I/O and Variable Fundamentals

This document provides an overview of procedural and object-oriented programming concepts. It discusses the key differences between procedural and object-oriented programming languages. Procedural languages follow a top-down approach and have global data sharing, while object-oriented languages model real-world objects and interactions through classes and objects. The document also covers basics of C++ like data types, variables, constants, pointers, input/output operations and formatting.

Uploaded by

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

C++ I/O and Variable Fundamentals

This document provides an overview of procedural and object-oriented programming concepts. It discusses the key differences between procedural and object-oriented programming languages. Procedural languages follow a top-down approach and have global data sharing, while object-oriented languages model real-world objects and interactions through classes and objects. The document also covers basics of C++ like data types, variables, constants, pointers, input/output operations and formatting.

Uploaded by

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

18CSC202J - OBJECT ORIENTED

DESIGN AND PROGRAMMING

Session 1

Topic : PROCEDURAL AND OBJECT


ORIENTED PROGRAMMING
• The main program coordinates calls to
procedures and hands over appropriate
data as parameters.
Procedure Oriented Programming Language
C function aspects Syntax

Function declaration Return-type function-name(argument list);

Eg : int add(int a, int b);


Function definition Return-type function-name(argument list)
{ body of function;}

Eg : int add(int a, int b)


{int c;
c=a+b;
Return c; }

Function call Function-name(argument list);

Eg : add(5,10);
Features of Procedure Oriented Programming
Language
• Smaller programs - A program in a procedural
language is a list of instructions.
• Larger programs are divided in to smaller programs
known as functions.
• Each function has a clearly defined purpose and a
clearly defined interface to the other functions in
the program.
• Data is Global and shared by almost all the
functions.
• Employs Top Down approach in Program Design.
Examples of Procedure Oriented
Programming Language

• COBOL
• FORTRAN
•C
Disadvantages of Procedural
Programming Language
Unrestricted access
• functions have unrestricted access to global data.
Real-world modeling
• unrelated (separated) functions and data, the
basis of the procedural paradigm, provide a poor
model of the real world.
• Complex real-world objects have both attributes
(data) and behavior (function).
Object-Oriented Concept

• Objects of the program interact by sending messages to


each other, hence it increases the data security (data can
be accessed only through its instances)
Object Oriented Programming

• Object-oriented programming is a programming paradigm that uses


abstraction in the form of classes and objects to create models based on
the real world environment.

• An object-oriented application uses a collection of objects, which


communicate by passing messages to request services.

• The aim of object-oriented programming is to try to increase the flexibility


and maintainability of programs. Because programs created using an OO
language are modular, they can be easier to develop, and simpler to
understand after development
Object-Oriented Concepts
• Everything is an object and each object has its own memory

• Computation is performed by objects communicating with each other

• Every object is an instance of a class. A class simply represents a grouping of


similar objects, such as Integers or lists.

• The class is the repository for behavior associated with an object. That is, that
all objects that are instances of the same class can perform the same actions.

• Classes are organized into a singly rooted tree structure, called the inheritance
hierarchy. Memory and behavior associated with instances of a class are
automatically available to any class associated with a descendant in this tree
structure.
Object-Oriented Programming vs.
Procedural Programming
• Programs are made up of modules, which are parts of a program that can
be coded and tested separately, and then assembled to form a complete
program.

• In procedural languages (i.e. C) these modules are procedures, where a


procedure is a sequence of statements.

• The design method used in procedural programming is called Top Down


Design. This is where you start with a problem (procedure) and then
systematically break the problem down into sub problems (sub
procedures).
Object-Oriented Programming vs.
Procedural Programming

• The difficulties with Procedural Programming, is that software maintenance can


be difficult and time consuming.
• When changes are made to the main procedure (top), those changes can cascade
to the sub procedures of main, and the sub-sub procedures and so on, where the
change may impact all procedures in the pyramid.

• Object oriented programming is meant to address the difficulties with procedural


programming.
The main difference
Comparison
Procedural Oriented Object Oriented

Program is divided into small parts Program is divided into small parts
called ‘Functions’ called ‘Objects’

Global and Local data Has access specifiers : Public,


Private, Protected

Doesn’t have any proper way for Provides data hiding and security
hiding data
Procedural programming follows a Object-oriented programming follows
top-down approach. a bottom-up approach.

Eg: C, VB, FORTAN Eg: C++, JAVA, VB.NET


Comparison
Basics of CPP
Difference between Cand C++
Structure of C++
Session-2
Topics covered

• I/O Operation
• Data types
• Variable
• Static
• Constant
• Pointer
• Type conversion
I/O Operation

• C++ I/O operation occurs in streams, which involve transfer of


information into byte
• It’s a sequences of bytes
• Stream involved in two ways
• It is the source as well as the destination of data
• C++ programs input data and output data from a stream.
• Streams are related with a physical device such as the monitor or
with a file stored on the secondary memory.
• In a text stream, the sequence of characters is divided into lines,
with each line being terminated.
• With a new-line character (\n) . On the other hand, a binary
stream contains data values using their memory representation.
Stream in C

Text Stream Binary Stream


Data Types in C++
Variables

A variable is the content of a memory location that stores a certain value. A variable is identified or denoted by a variable
name. The variable name is a sequence of one or more letters, digits or underscore, for example: character_
Rules for defining variable name:
❖ A variable name can have one or more letters or digits or underscore for example character_.
❖ White space, punctuation symbols or other characters are not permitted to denote variable name.
❖ A variable name must begin with a letter.
❖ Variable names cannot be keywords or any reserved words of the C++ programming language.
❖ Data C++ is a case-sensitive language. Variable names written in capital letters differ from variable names with the same
name but written in small letters.

01 Local Variables 03 Instance variables

02 Static Variables 04 Final Variables


CONSTANTS
• Constants are identifiers whose value does not change. While variables
can change their value at any time, constants can never change their
value.
• Constants are used to define fixed values such as Pi or the charge on an
electron so that their value does not get changed in the program even by
mistake.
• A constant is an explicit data value specified by the programmer.
• The value of the constant is known to the compiler at the compile time.
Declaring Constants
• Rule 1 Constant names are usually written in capital letters to
visually distinguish them from other variable names which are
normally written in lower case characters.
• Rule 2 No blank spaces are permitted in between the # symbol and
define keyword.
• Rule 3 Blank space must be used between #define and constant name
and between constant name and constant value.
• Rule 4 #define is a preprocessor compiler directive and not a
statement. Therefore, it does not end with a semi-colon. (give
instructions to the compiler to preprocess the information before actual compilation starts. )
Cascading of Input or Output Operators

• << insertion ( << ) operator, which is


pre-programmed for all standard C++ data
types, sends bytes to an output stream object.
• operator - It can be used multiple times in the same
line.
• It’s called Cascading
• cout, cin can be cascaded
Example:
• cout<<“\n Enter the Marks”;
• Cout<<“Computer Networks”>>”OODP”;
Reading and Writing Characters and Strings
• char marks;

cin.get(marks);//The value for marks is read


(OR)
marks=cin.get();//A character is read and assigned to marks

• string name;
cin>>name;

• #include <iostream>
using namespace std;
int main()
{ string name; getline(cin,name); cout<<name;
return 0;}
Formatted Input and Output Operations

Formatted I/O

I/O class function Manipulators


and flages
#include<iostream.h>
#define PI 3.14159
main()
{
cout.precision(3);
cout.width(10);
cout.fill(‘*’);
cout<<PI;
Output
*****3.142
Formatting with flags
• The setf() is a member function of the ios class
that is used to set flags for formatting output.
• syntax -cout.setf(flag, bit-field)
• Here, flag defined in the ios class specifies how
the output should be formatted and bit-field is a
constant (defined in ios ) that identifies the group
to which the formatting flag belongs to.
• There are two types of setf()—one that takes both
flag and bit-fields and the other that takes only the
flag .
Formatting Output Using Manipulators
• C++ has a header file iomanip.h that contains
certain manipulators to format the output
Variables

Local Variables Instance Variables Static Variables Constant Variables

Local variable: These are the Instance variable: These are


Static variables: Static Constant is something that
variables which are declared the variables which
variables are also called as doesn't change. In C
within the method of a class. are declared in a class but
class variables. These language and C++ we use
outside a method,
variables have only one copy the keyword const to make
Example: constructor or any block.
that is shared by all the program elements
public class Car { Example:
different objects in a class. constant.
public: public class Car {
Example: Example:
void display(int m){ private: String color;
public class Car { const int i = 10;
//Method // Created an instance
public static int tyres; void f(const int i)
int model=m; variable color
// Created a class variable class Test
// Created a local variable Car(String c)
void init(){ {
model {
tyres=4; const int i;
cout<<model; color=c;
}} };
} }}
Special Operators

Scope resolution operator

In C, the global version of a variable cannot be accessed from within the inner block. C++ resolves this
1
problem by using scope resolution operator (::), because this operator allows access to the global version of
a variable. New Operator

2 The new operator denotes a request for memory allocation on the Heap. If sufficient memory is available, new
operator initializes the memory and returns the address of the newly allocated and initialized memory to the
Delete Operator
pointer variable.
3 Since it is programmer’s responsibility to deallocate dynamically allocated memory, programmers are provided
.
delete operator by C++ language Member Operator

4 C++ permits us to define a class containing various types of data & functions as members. To access a
member using a pointer in the object & a pointer to the member.
Operator Precedence
Rank Operators Associativity
1 ++, --, +, -, !(logical complement) ,~(bitwise complement) ,(cast) Right
2 *(mul) , /(div), %(mod) Left
3 + , - (Binary) Left
4 >> , <<, >>> (Shift operator) Left
5 >, <, >=,<= Left
6 ==, != Left
7 & (Bitwise and) Left
8 ^ ( XOR) Left
9 | (Bitwise OR) Left
10 && (Logical and) Left
11 || (Logical OR) Left
12 Conditional Right
13 Shorthand Assignment Right
Pointers
• Pointer is variable in C++
• It holds the address of another variable
• Syntax data_type *pointer_variable;
• Example int *p,sum;
Assignment
• integer type pointer can hold the address of
another int variable
• To assign the address of variable to
pointer-ampersand symbol (&)
• p=&sum;
How to use it
• P=&sum;//assign address of another variable
• cout<<&sum; //to print the address of variable
• cout<<p;//print the value of variable
• Example of pointer
#include<iostream.h>
using namespace std;
int main()
{ int *p,sum=10; Output:
p=&sum; Address of sum : 0X77712
cout<<“Address of sum:”<<&sum<<endl; Address of sum: 0x77712
cout<<“Address of sum:”<<p<<endl; Address of p: 0x77717
cou<<“Address of p:”<<&p<<endl; Value of sum: 10
cout<<“Value of sum”<<*p;
}
Pointers and Arrays
assigning
•#include <iostream>
the address of array to pointer
don’t
using namespace
int main(){
use
std; ampersand sign(&)
//Pointer declaration
int *p;
//Array declaration
OUTPUT:
int arr[]={1, 2, 3, 4, 5, 6};
0
//Assignment
1
p = arr;
2
for(int i=0; i<6;i++){
3
cout<<*p<<endl;
4
//++ moves the pointer to next int position
5
p++;
6
}
return 0;
}
This Pointers
• this pointer hold the adderss of current
object
• int num;
• This->num=num;
Function using pointers
void swap(int *a,int *b)
#include<iostream> {
int c;
using namespace std;
c=*a;
void swap(int *a ,int *b ); *a=*b;
//Call By Reference *b=c;
int main() }
{
int p,q; Output:
cout<<"\nEnter Two Number You Want To Swap \n"; Enter Two Number You Want to Swap
cin>>p>>q; 10 20
swap(&p,&q); After Swapping Numbers Are Given below
cout<<"\nAfter Swapping Numbers Are Given below\n\n"; 20 10
cout<<p<<" "<<q<<" \n";
return 0;
}
Type conversion and type
casting
• Type conversion or typecasting of variables refers to
changing a variable of one data type into another. While type
conversion is done implicitly, casting has to be done
explicitly by the programmer.
Type Casting
• Type casting an arithmetic expression tells the compiler to represent the value of the
expression in a certain format.
• It is done when the value of a higher data type has to be converted into the value of
a lower data type.
• However, this cast is under the programmer’s control and not under the compiler’s
control. The general syntax for type casting is
destination_variable_name=destination_data_ty--pe(source_variable_name);

float sal=10000.00;
int income;
Income=int(sal);
Session-3
Class and objects
Class:

• Class is a user defined data type,


• It holds its own data members and member functions,
• It can be accessed and used by creating instance of that class.
• The variables inside class definition are called as data members and
the functions are called member functions
example:
Class of birds, all birds can fly and they all have wings and beaks. So here flying is a
behavior and wings and beaks are part of their characteristics. And there are many different
birds in this class with different names but they all posses this behavior and characteristics.

• class is just a blue print, which declares and defines characteristics and behavior,
namely data members and member functions respectively.
• All objects of this class will share these characteristics and behavior.
• Class name must start with an uppercase letter(Although this is not mandatory).
Example,
class Student
• Classes contain, data members and member functions, and the access of these
data members and variable depends on the access specifiers.
• Class's member functions can be defined inside the class definition or outside
the class definition.
• class defaults to private access control,
• Objects of class holds separate copies of data members. We can create as many
objects of a class as we need.
• No storage is assigned when we define a class.
Define a Class Type
Syntax: Example:
Name of the
class
class Rectangle
keywor class Class_name {
d
{ private:
permission_label:
int width;
member;
int length;
Body permission_label:
member; public:
... void set(int w, int
}; l);
int area();
};

67
- Data members Can be of any type, built-in or
user-defined.
This may be,
• non-static data member
Each class object has its own copy

• static data member


Acts as a global variable

68
• Static data member is declared using the static keyword.
• There is only one copy of the static data member in the class. All the
objects share the static data member.
• The static data member is always initialized to zero when the first class
object is created.

Syntax:
static data_type datamember_name;
Here
static is the keyword.
data_type – int , float etc…
datamember_name – user defined

69
Static Data Member
Rectangle r1;
class Rectangle Rectangle r2;
{ Rectangle r3;
private:
int width;
int length; count

static int count;


r1 r2
public: width width
void set(int w, int length length

l); width
int area(); r3 length

}
Member Functions
• Used to
– access the values of the data members (accessor)
– perform operations on the data members
(implementor)
• Are declared inside the class body
• Their definition can be placed inside the class
body, or outside the class body
• Can access both public and private members of
the class
• Can be referred to using dot or arrow member
access operator

71
Member function
keyword Class Name
class Rectangle
{ int main()
private: {
int width, length; Rectangle r2; Object creation
public: r1.set(5,8); Inside the
void set (int w, int l); int x=r1.area(); function
member
int area() cout<<"x value in r1 "<<x;
function
{ r2.set(5,8);
inside the class return width*length; int x=r1.area();
} class name cout<<"x value in r2 "<<x;
}r1,; Member function
Object void Rectangle :: set (int w, int l) }
creation {
outside the class
width = w;
length = l;
}
scope operator
const member function

• The const member functions are the functions which are declared as constant in the program.
• The object called by these functions cannot be modified.
• It is recommended to use const keyword so that accidental changes to object are avoided.
• A const member function can be called by any type of object.
• Note: Non-const functions can be called by non-const objects only.

Syntax: User defined


keyword
datatype function_name const();
Const Member Function
class Time
{
private : function declaration
int hrs, mins, secs ;

public :
void Write ( )
function definition
const ;
};

void Time :: Write( ) const


{
cout <<hrs << “:” << mins << “:” << secs << endl;
}

74
Access modifiers
• The access modifiers are used to set boundaries for availability of members of class be
it data members or member functions
• Access modifiers in the program, are followed by a colon.
• we can use either one, two or all 3 modifiers in the same class to set different boundaries for
different class members.

C++ has the following types of access modifiers,


1. public
2. private
3. protected
Public:
• Public class members declared under public will be available to everyone.
• The data members and member functions can be accessed by other classes too.
Hence there are chances that they might change them.
(So the key members must not be declared public).

class Student
{
// public access modifier
public:
int x; // Data Member Declaration
void display(); // Member Function decaration
}
Private :
• No one can access the class members which are declared private, outside that class.
• When try to access the private members of a class, it will show a compile time error.
• The default class variables and member functions are private.

Protected:
• it is similar to private, it makes class member inaccessible outside the class.
But they can be accessed by any subclass of that class.

Example:
class A is inherited by class B, then class B is subclass of class A.
so class B can access the class A data members and member functions
What is an object?

OBJECT
set of methods
Operations (member functions)

Data internal state


(values of private data members)

78
Object:
• Objects are instances of class, which holds the data variables declared in
class and the member functions work on these class objects.
• Each object has different data variables.
• Objects are initialized using special class functions called Constructors.
• Destructor is special class member function, to release the memory reserved
by the object.

Syntax of creating object :


Class_name object_name;
Declaration of an Object

class Rectangle
main()
{ {
private: Rectangle r1;
Rectangle r2;
int width;
int length; r1.set(5, 8);
public: cout<<r1.area()<<endl;

void set(int w, int r2.set(8,10);


l); cout<<r2.area()<<endl;
int area(); }

};

80
Another Example

#include <iostream.h> // member function definitions


void circle::store(double r)
class circle {
{ radius = r;
private: }
double radius; double circle::area(void)
{
public: return 3.14*radius*radius;
void store(double); }
double area(void); void circle::display(void)
void display(void); {
cout << “r = “ << radius <<
}; endl;
}
int main(void) {
circle c; // an object of circle class
c.store(5.0);
cout << "The area of circle c is " << c.area() << endl;
c.display();
}

81
Declaration of an Object
r1 is statically allocated
class Rectangle
{ main()
private: {
Rectangle r1;
int width;
r1.set(5, 8);
int length;
}
public:
void set(int w, int
r1
l); width = 5
length = 8
int area();
};

82
Declaration of an Object
r2 is a pointer to a Rectangle object
class Rectangle
{ main()
{
private: Rectangle r1;
int width; r1.set(5, 8); //dot notation

int length; Rectangle *r2;


r2 = &r1;
public: r2->set(8,10); //arrow notation
void set(int w, int }

l); 5000
r1 r
int area(); width = 8
5 2
6000
length = 10
8 5000
???
};

83
Object Initialization
1. By Assignment

#include <iostream.h>
• Only work for public data
members
class circle
{ • No control over the operations
public: on data members
double radius;
};
int main()
{
circle c1; // Declare an instance of the class circle
c1.radius = 5; // Initialize by assignment

84
Object Initialization
2. By Public Member Functions

#include <iostream.h>
class circle
{
private:
double radius;
public:
void set (double r)
{radius = r;}
double get_r ()
{return radius;}
};

int main(void) {
circle c; // an object of circle class
c.set(5.0); // initialize an object with a public member function
cout << "The radius of circle c is " << c.get_r() << endl;
// access a private data member with an accessor
}

85
Session-6

Feature : Objects and Classes


Objects and Classes
•Class is a user defined data type, which holds its own data members and
member functions, which can be accessed and used by creating instance of
that class.

–Attributes – member of a class.


•An attribute is the data defined in a class that maintains the
current state of an object. The state of an object is determined
by the current contents of all the attributes.

–Methods – member functions of a class

87
Objects and classes
• A class itself does not exist; it is merely a description of an object.
• A class can be considered a template for the creation of object

• Blueprint of a building class


• Building object

• An object exists and is definable.


• An object exhibits behavior, maintains state, and has traits. An object can
be manipulated.
• An object is an instance of a class.

88
Methods
• A method is a function that is part of the class definition. The methods of a
class specify how its objects will respond to any particular message.

• A method is a collection of statements that perform some specific task and


return the result to the caller. A method can perform some specific task
without returning anything.

• Methods allow us to reuse the code without retyping the code.

• A message is a request, sent to an object, that activates a method (i.e., a


member function).

89
Defining a Base Class - Example
•A base class is not defined on, nor does it inherit members from, any
other class.

#include <iostream>
using std::cout; //this example “uses” only the necessary
using std::endl; // objects, not the entire std namespace

class Fraction {
public:
void assign (int, int); //member functions
double convert();
void invert();
void print();
private:
int num, den; //member data
};
Continued…
90
Using objects of a Class - Example
The main() function:

int main()
{
Fraction x;
x.assign (22, 7);
cout << "x = "; x.print();
cout << " = " << x.convert() << endl;
x.invert();
cout << "1/x = "; x.print(); cout << endl;
return 0;
}

Continued…

91
Defining a Class – Example
Class Implementation:
void Fraction::assign (int numerator, int denominator)
{
num = numerator;
den = denominator;
}
double Fraction::convert ()
{
return double (num)/(den);
}
void Fraction::invert()
{
int temp = num;
num = den;
den = temp;
}
void Fraction::print()
{
cout << num << '/' <
}< den; 92
Session 7

Topic : UML Class Diagram, its components,


Class Diagram relations and Multiplicity
Overview of UML Diagrams
Behavioral
: behavioral features of a system / business
Structural process
: element of spec. irrespective of time
• Activity
• State machine
• Class
• Use case
• Component
• Interaction
• Deployment
• Object
• Composite structure Interaction
• Package : emphasize object interaction

• Communication(collaberati
on)
• Sequence
• Interaction overview
• Timing
UML Class diagram :
• The Unified Modeling Language (UML) is a
general-purpose, developmental, modeling language
in the field of software engineering that is intended to
provide a standard way to visualize the design of a
system.
UML Class diagram :
• The UML Class diagram is a graphical notation used to
construct and visualize object-oriented systems.

• A class diagram describes the structure of a system such


as Classes and their attributes , operations (or methods)
and the relationships among objects.
• A class diagram is used to show the existence of classes
and their relationships in the logical view of a system.
Basic components of a class diagram
The standard class diagram is composed of three sections:
Upper section: Contains the name of the class. This section is
always required, to know whether it represents the classifier or
an object.
Middle section: Contains the attributes of the class. Use this
section to describe the qualities of the class. This is only
required when describing a specific instance of a class.
Bottom section: Includes class operations (methods). Displayed
in list format, each operation takes up its own line. The
operations describe how a class interacts with data.
RULES TO BE FOLLOWED:
•Class name must be unique to its enclosing namespace.
•The class name begins in uppercase and the space between
multiple words is omitted.
•The first letter of the attribute and operation names is lowercase
with subsequent words starting in uppercase and spaces are
omitted.
• Since the class is the namespace for its attributes and operations
an attribute name must be unambiguous in the context of the
class.
•Attribute specification format:
visibility attributeName : Type [multiplicity] = DefaultValue
{property string}
•Operation specification format:
visibility operationName (parameterName : Type) : ReturnType
{property string}

VISIBILITY
Public (+) Visible to any element that can see the class.
Protected (#) Visible to other elements within the class and to
subclasses .
Private (-) Visible to other elements within the class .
Package (~) Visible to elements within the same package.
Abstract class
•An abstract class is one for which no instances
may be created.
•Because such classes are so important to
engineering good class inheritance trees, there
is a special way to designate an abstract class.
•To denote that an operation is abstract, we simply italicize the
operation name; this means that this operation may be
implemented differently by all instances of its subclasses.

• In the Hydroponics Gardening System, we have food items that


have a specific vitamin content and caloric equivalent, but there is
not a type of food called “food item.”
•Hence, the FoodItem class is abstract.
•Above fig also shows the subclass Tomato, which represents a
concrete (instantiable) food item grown in the greenhouse.
Class Relationships
The essential connections among classes include
•Association
•Generalization
•Aggregation
•Composition
Association :
•The association icon connects two classes and denotes a semantic
connection.
•Associations are often labeled with noun phrases, such as Analyzes,
denoting the nature of the relationship.
•A class may have an association to itself (called a reflexive
association), such as the collaboration among instances of the
PlanAnalyst class.
•A class may have an association to itself (called a reflexive
association), such as the collaboration among instances of the
PlanAnalyst class.
•The use of both the association end names and the association
name is to provide clarity.
•It is also possible to have more than one association between the
same pair of classes.
•Associations may be further adorned with their multiplicity, using
the following syntax:

1 Exactly one
* Unlimited number (zero or more)
0..* Zero or more
1..* One or more
0..1 Zero or one
3..7 Specified range (from three through seven, inclusive)
.
GENERALIZATION
•The generalization icon denotes a
generalization/specialization relationship and
appears as an association with a closed
arrowhead.
The GrowingPlan class in Figure is the superclass
and its subclass is the FruitGrowingPlan
AGGREGATION
•Aggregation, as manifested in the “part of ”
relationship, is a constrained form of the more
general association relationship.
•It appears as an association with an unfilled diamond at the end
denoting the aggregate (the whole).
•The class at the other end denotes the class whose instances are
part of the aggregate object.
• Reflexive and cyclic aggregation is possible.
In figure, an individual EnvironmentalController class has the Light,
Heater, and Cooler classes as its parts.
•The multiplicity of * (zero or more) at the aggregate end of the
relationship further highlights this lack of physical containment.

COMPOSITION
• Composition implies that the construction and destruction of
these parts occurs as a consequence of the construction and
destruction of the aggregate.
•The icons described thus far constitute the essential elements
of all class diagrams.
•Collectively, they provide the developer with a notation
sufficient to describe the fundamentals of a system’s class
structure.
Classes
A class is a description of a set of
ClassName objects that share the same attributes,
operations, relationships, and semantics.
attributes
Graphically, a class is rendered as a
rectangle, usually including its name,
operations attributes, and operations in separate,
designated compartments.
Class Names

The name of the class is the only required


ClassName tag in the graphical representation of a
class. It always appears in the top-most
attributes compartment.

operations
Class Attributes

Person

name : String An attribute is a named property of a


address : Address class that describes the object being modeled.
birthdate : Date In the class diagram, attributes appear in
ssn : Id the second compartment just below the
name-compartment.
Class Attributes (Cont’d)
Attributes are usually listed in the form:

Person attributeName : Type

name : String A derived attribute is one that can be


address : Address computed from other attributes, but
birthdate : Date doesn’t actually exist. For example,
/ age : Date a Person’s age can be computed from
ssn : Id his birth date. A derived attribute is
designated by a preceding ‘/’ as in:

/ age : Date
Class Attributes (Cont’d)

Person

+ name : String Attributes can be:


# address : + public
Address # protected
# birthdate : Date - private
/ age : Date / derived
- ssn : Id
Class Operations

Person
name : String
address :
Address
birthdate : Date
ssn : Id
eat Operations describe the class behavior
sleep and appear in the third compartment.
work
play
Class Operations (Cont’d)

PhoneBook

newEntry (n : Name, a : Address, p : PhoneNumber, d :


Description)
getPhone ( n : Name, a : Address) : PhoneNumber

You can specify an operation by stating its signature: listing the


name, type, and default value of all parameters, and, in the case of
functions, a return type.
Depicting Classes
When drawing a class, you needn’t show attributes and operation
in every diagram.

Person Person Person


name : String
birthdate : Date
Person ssn : Id
name Person eat()
address sleep()
birthdate eat work()
play play()
Class Responsibilities
A class may also include its responsibilities in a class diagram.

A responsibility is a contract or obligation of a class to perform


a particular service.

SmokeAlarm

Responsibilities

-- sound alert and notify guard station


when smoke is detected.

-- indicate battery state


Relationships

In UML, object interconnections (logical or physical), are


modeled as relationships.

There are three kinds of relationships in UML:

• dependencies

• generalizations

• associations
Dependency Relationships
A dependency indicates a semantic relationship between two or
more elements. The dependency from CourseSchedule to
Course exists because Course is used in both the add and
remove operations of CourseSchedule.

CourseSchedule
Course
add(c : Course)
remove(c :
Course)
Generalization Relationships

Person
A generalization connects a subclass
to its superclass. It denotes an
inheritance of attributes and behavior
from the superclass to the subclass and
indicates a specialization in the subclass
of the more general superclass.
Student
Generalization Relationships (Cont’d)
UML permits a class to inherit from multiple superclasses,
although some programming languages (e.g., Java) do not permit
multiple inheritance.

Student Employee

TeachingAssistant
Association Relationships
If two classes in a model need to communicate with each other,
there must be link between them.

An association denotes that link.

Student Instructor
Association Relationships (Cont’d)
We can indicate the multiplicity of an association by adding
multiplicity adornments to the line denoting the association.

The example indicates that a Student has one or more


Instructors:

Student Instructor
1..*
Association Relationships (Cont’d)

The example indicates that every Instructor has one or more


Students:

Student Instructor
1..*
Association Relationships (Cont’d)
We can also indicate the behavior of an object in an association
(i.e., the role of an object) using rolenames.

teaches learns from


Student Instructor
1..* 1..*
Association Relationships (Cont’d)
We can also name the association.

membership
Student Team
1..* 1..*
Association Relationships (Cont’d)
We can specify dual associations.

member of
1..* 1..*
Student Team
1 president of 1..*
Association Relationships (Cont’d)
We can constrain the association relationship by defining the
navigability of the association. Here, a Router object requests
services from a DNS object by sending messages to (invoking
the operations of) the server. The direction of the association
indicates that the server has no knowledge of the Router.

Router DomainNameServer
Association Relationships (Cont’d)
Associations can also be objects themselves, called link classes
or an association classes. (Ternary association)

Registration
modelNumber
serialNumber
warrentyCode

Product Warranty
Association Relationships (Cont’d)

A class can have a self association.

next

LinkedListNode
previous
Association Relationships (Cont’d)
We can model objects that contain other objects by way of
special associations called aggregations and compositions.

An aggregation specifies a whole-part relationship between an


aggregate (a whole) and a constituent part, where the part can
exist independently from the aggregate. Aggregations are
denoted by a hollow-diamond adornment on the association.
Adornments are textual or graphical items, which can be added to the basic notation of a
UML building block in order to visualise some details from that element's specification.

Engine
Car
Transmission
Association Relationships (Cont’d)
A composition indicates a strong ownership and coincident
lifetime of parts by the whole (i.e., they live and die as a
whole). Compositions are denoted by a filled-diamond
adornment on the association.

Scrollbar
1 1

Window Titlebar
1 1

Menu
1 1 .. *
Composition
Aggregation
Example: car consists of wheels, engine, gearbox, steering, and the main body, etc. It is an
assembly, and the other parts are its constituents.
Here, car to the wheel is one Aggregation, car to the engine is another aggregation, car to
gearbox another, and so on.
- This pairing helps to define the multiplicity of the constituent part within the assembly as
its outcome. The number of objects can also be depicted.

- A car needs a wheel to function correctly. However, we cannot say the same with a car.
The same logic can be applied to bike, bicycle, or any other vehicle but not a particular
car.
- Here, the wheel object is meaningful even without the car object. It is known as an
aggregation relationship.
Interfaces

An interface is a named set of operations


that specifies the behavior of objects
without showing their inner structure. It
<<interface>>
can be rendered in the model by a one- or
ControlPanel
two-compartment rectangle, with the
stereotype <<interface>> above the
interface name.
Multiplicity
1. One-to-one
2. One-to-many
3. Many-to-many
One-to-one relationship
For example, in retail telemarketing operations, we
would find
a one-to-one relationship between the class Sale and
the class CreditCardTransaction.
Many-to-many relationship
For example, each instance of the class Customer might
initiate a transaction with several instances of the
class SalesPerson,
Session 8

Topic : Feature Abstraction and


Encapsulation, Application of Abstraction and
Encapsulation
Features Of OOPS
• DATA ENCAPSULATION
– Combining data and functions into a single unit called class and the
process is known as Encapsulation.

• Provides security, flexibility and easy maintainability

• Encapsulation helps us in binding the data(instance variables) and


the member functions(that work on the instance variables) of a class.

• Encapsulation is also useful in hiding the data(instance variables) of a


class from an illegal direct access.

• Encapsulation also helps us to make a flexible code which is easy


to change and maintain.
Features Of OOPS
• ABSTRACTION OR DATA HIDING
– Class contains both data and functions. Data is not accessible from the
outside world and only those function which are present in the class
can access the data.

– The insulation of the data from direct access by the program is called
data hiding or information hiding. Hiding the complexity of program is
called Abstraction and only the essential features are represented.

– Uses
• 1) Makes the application secure by making data private and
avoiding the user level error that may corrupt the data.
• 2) This avoids code duplication and increases the code reusability.
Application of Abstraction
• For example, when you send an email to
someone you just click send and you get the
success message, what actually happens when
you click send, how data is transmitted over
network to the recipient is hidden from you
ENCAPSULATION
ADVANTAGES
• Encapsulated classes reduce complexity.
• Help protect our data. A client cannot change an Account's balance if we
encapsulate it.
• Encapsulated classes are easier to change.
Example

• The common example of encapsulation is Capsule. In capsule all medicine


are encapsulated in side capsule.
• Automatic Cola Vending Machine :Suppose you go to an automatic cola
vending machine and request for a cola. The machine processes your
request and gives the cola.
Examples
Data Abstraction and Encapsulation
Any C++ program where you implement a class with public and private members is an
example of data encapsulation and data abstraction

• #include <iostream>
• using namespace std;

• class Adder {
• public:
• // constructor
• Adder(int i = 0) {
• total = i;
• }

• // interface to outside world
• void addNum(int number) {
• total += number;
• }

• // interface to outside world
• int getTotal() {
• return total;
• };

• private:
• // hidden data from outside world
• int total;
• };
Session-11

ACCESS SPECIFIERS
Access control in classes

•public : A public member is accessible from anywhere outside the class but within a
program.

•private : A private member variable or function cannot be accessed, or even viewed


from outside the class. Only the class and friend functions can access private
members.

•protected : A protected member variable or function is very similar to a private
member but it provided one additional benefit that they can be accessed in child
classes which are called derived classes

144
Access Specifiers Example 1
#include <iostream> // Main function for the program
using namespace std;
int main( )
class Line {
{ Line line;
public:
double length; // set line length
void setLength( double len ); line.setLength(6.0);
double getLength( void ); cout << "Length of line : " << line.getLength() <<endl;
};
// set line length without member function
double Line::getLength(void)
{ line.length = 10.0; // OK: because length is public
return length ; cout << "Length of line : " << line.length <<endl;
} return 0;
}
void Line::setLength( double len )
{
Length of line : 6
length = len; Length of line :
} 10

1
4
5
Access Specifiers Example 2
#include <iostream>
using namespace std; // Main function for the program
int main( )
class Box {
Box box;
{
public: // set box length without member function
double length; box.length = 10.0; // OK: because length is public
void setWidth( double wid ); cout << "Length of box : " << box.length <<endl;
double getWidth( void );
// set box width without member function
private: // box.width = 10.0; // Error: because width is private
double width; box.setWidth(10.0); // Use member function to set it.
}; cout << "Width of box : " << box.getWidth() <<endl;

// Member functions definitions return 0;


double Box::getWidth(void) }
{
return width ;
}
Length of box :
void Box::setWidth( double wid ) 10 Width of box :
{
10
width = wid;
} 1
4
6
Access Specifiers Example 3
#include <iostream> void SmallBox::setSmallWidth( double wid )
using namespace std; {
width = wid;
class Box }
{
protected: // Main function for the program
double width; int main( )
}; {
SmallBox box;
class SmallBox:Box
{ // set box width using member function
public: box.setSmallWidth(5.0);
void setSmallWidth( double wid ); cout << "Width of box : "<< box.getSmallWidth();
double getSmallWidth( void );
}; return 0;
}
// Member functions of child class
double SmallBox::getSmallWidth(void)
{ Width of box : 5
return width ;
}

1
4
7
Friend function
•A friend function of a class is defined outside that class' scope but it has the right to
access all private and protected members of the class.

•Even though the prototypes for friend functions appear in the class definition, friends
are not member functions.

•A friend can be a function, function template, or member function, or a class or class


template, in which case the entire class and all of its members are friends.

148
Friend function Example
#include <iostream> //Global Function
using namespace std;
class XYZ void disp(XYZ obj)
{ {
cout<<obj.num<<endl;
private: int num=100; cout<<obj.ch<<endl;
char ch='Z'; }
public: friend void disp(XYZ obj); int main()
}; {
XYZ obj;
disp(obj);
return 0;
}

149

Inline Function
C++ provides an inline functions to reduce the function call overhead.

• Inline function is a function that is expanded in line when it is called.

• When the inline function is called whole code of the inline function gets inserted or
substituted at the point of inline function call. This substitution is performed by the
C++ compiler at compile time.

• Inline function may increase efficiency if it is small.


Inline Function - Example
Inline Function - Example
include <iostream> Output:
using namespace std;
inline int Max(int x, int y) { Max (20,10): 20
return (x > y)? x : y; Max (0,200): 200
} Max (100,1010): 1010
// Main function for the program
int main() {
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;
return 0;
}
Session 12

Topic : UML use case Diagram, use


case, Scenario, Use case Diagram
objects and relations
USECASE DIAGRAM
•Use case diagrams give us that capability.
•Use case diagrams are used to depict the context of the system
to be built and the functionality provided by that system.
•They depict who (or what) interacts with the system. They
show what the outside world wants the system to do.
NOTATIONS
• Actors are entities that interface with the system.
• They can be people or other systems.
• Actors, which are external to the system they are using,
are depicted as stylized stick figures.
Relationship
Two relationships used primarily for organizing use case models
are both powerful
• «include» relationship
• «extend» relationship
«include» relationship
• In our hydroponics example, we have an Update Crop
Encyclopedia use case.
• During analysis, we determine that the Nutritionist actor
using that use case will have to see what is in the crop
encyclopedia prior to updating it.
• This is why the Nutritionist can invoke the View Reports use
case.
• The same is true for the Gardener actor whenever invoking
Maintain StorageTanks.
• Neither actor should be executing the use cases blindly. Therefore,
the View Report use case is a common functionality that both
other use cases need.
• This can be depicted on the use case model via an «include»
relationship, as shown in Figure.
• This diagram states, for example, that the Update Crop
Encyclopedia usecase includes the View Reports use case.
• This means that View Reports must be executed when Update Crop
Encyclopedia is executed.
• UpdateCrop Encyclopedia would not be considered complete
without View Reports.
«extend» Relationships
• While developing your use cases, you may find that certain
activities might be performed as part of the use case but are
not mandatory for that use case to run successfully.
• In our example, as the Gardener actor executes the Manage
Garden use case, he or she may want to look at some
reports.
• This could be done by using the View Reports use case.
• However, View Reports is not required when Manage
Garden is run. Manage Garden is complete in and of itself.
So, we modify the use case diagram to indicate that the
View Reports use case extends the Manage Garden use
case.
• Where an extending use case is executed, it is indicated in
the use case specification as an extension point.
• The extension point specifies where, in the flow of the
including use case, the extending use case is to be executed.
Session 13

Topic : Constructor and Destructor


Object Initialization
By Constructor

• Default constructor
• Copy constructor
• Constructor with parameters

167
Constructor
• It is a special kind of class member function that is automatically called when
an object of that class is instantiated.
• Constructors are typically used to initialize member variables of the class to
appropriate default or user-provided values.

constructors have specific rules for how they must be named:


• Constructors must have the same name as the class (with the same
capitalization) .Constructors have no return type (not even void)
Example for default constructor:

#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}
Constructor with parameter:

• A constructor which has parameters is called parameterized constructor


• It is used to provide different values to distinct objects.
Example for constructor with parameter
Creating an
#include <iostream> object of
using namespace std; Employee
class Employee { int main(void) {
public: Employee e1 =Employee(101, "Sonoo", 890000);
int id;//data member (also e2=Employee(102, "Nakul", 59000);
instance variable) e1.display();
string name;//data e2.display();
member(also instance variable) return 0;
float salary; }
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<
salary<<endl;
}
};
Copy constructor:

• Copy Constructor is a type of constructor which is used to create a copy


of an already existing object of a class type.
• The compiler provides a default Copy Constructor to all the classes.

Copy Constructor is called in the following scenarios:

• When we initialize the object with another existing object of the same class
type.
For example, Student s1 = s2, where Student is the class.
• When the object of the same class type is passed by value as an argument.
• When the function returns the object of the same class type by value.
Example for copy constructor

#include <iostream> int main()


using namespace std; {
class A A a1(20); // Calling the
{ parameterized constructor.
public: cout<<a1.x<<endl;
int x; A a2(a1); // Calling the
A(int a) // parameterized copy constructor.
constructor. cout<<a2.x;
{ return 0;
x=a; }
}
A(A &i) // copy constructor
{
x = i.x;
}
};
Destructor:
• Destructors have the same name as their class and their name is
preceded by a tilde(~).
• Destructors in C++ are members functions in a class that delete an
object.
• They are called when the class object goes out of scope such as when
the function ends, the program ends, a delete variable is called etc.
• Destructors are don’t take any argument and don’t return anything.
When does the destructor get called?

A destructor is automatically called when:


1) The program finished execution.
2) When a scope (the { } parenthesis) containing local
variable ends.
3) When you call the delete operator.
Example program for destructor

#include <iostream>
using namespace std;
class HelloWorld{ int main()
public: {
HelloWorld obj; //Object
Constructor HelloWorld(){ created
//Member
cout<<"Constructor is
function
obj.display();
called"<<endl;
called
return 0;
}
}
Destructor
~HelloWorld(){
cout<<"Destructor is
called"<<endl; output
}
//Member function Constructor is called
void display(){ Hello World!
cout<<"Hello World!"<<endl; Destructor is called
}
};
Destructor rules
1) Name should begin with tilde sign(~) and must match class name.
2) There cannot be more than one destructor in a class.
3) Unlike constructors that can have parameters, destructors do not
allow any parameter.
4) They do not have any return type, just like constructors.
5) When you do not specify any destructor in a class, compiler generates
a default destructor and inserts it into your code.
Constructor
• A constructor is a member function that is invoked
automatically when an object is declared.
• It has the same name as the class and carries no return type
(not even void).
• The Compiler calls the Constructor whenever an object is
created
Syntax:
class A
{
public:
A() // constructor
{ }
};
178
Constructor
• Constructor can be defined either inside the class or outside of
the class using scope resolution operator ::
Example
class A
{
int a;
public:
A(); // constructor declaration
};
A::A() // constructor definition
{
a = 10;
}

179
Methods
• A method is a function that is part of the class definition. The methods of a
class specify how its objects will respond to any particular message.

• A method is a collection of statements that perform some specific task and


return the result to the caller. A method can perform some specific task
without returning anything.

• Methods allow us to reuse the code without retyping the code.

• A message is a request, sent to an object, that activates a method (i.e., a


member function).

180
Method Vs Constructor
• Used to define particular • Used to initialize the data
task for execution members
• Method can have same name • Constructor has same name
as class name or different as the class name
name based on the • Constructor is automatically
requirement called when an object is
• Explicit call statement created
required to call a method • There is always default
• There is no default method constructor provide by
provided by compiler compiler
• Return data type must be • Return type is not required
declared in constructor
Types of Constructor
Types of Constructors in C++
Constructors are of three types:
• Default Constructor - Default constructor is the constructor which
doesn't take any argument. It has no parameter.
• Parametrized Constructor : These are the constructors with
parameter. Using this Constructor you can provide different values
to data members of different objects, by passing the appropriate
values as argument.
• Copy Constructor: These are special type of Constructors which
takes an object as argument, and is used to copy values of data
members of one object into other object.

182
Example Program
// copy constructor
class Student
Student (const Student &s)
{ {
public: rollno = s.rollno;
int rollno; name = s.name;
string name; }
Student() //Default constructor }; // end of class
{ rollno = 0;
name = "None"; int main()
} {
Student(int x) // parameterized Student A1();
Student A(10);
{ rollno = x;
Student B=A;
name = "None";
}
}
Destructor
• A destructor is a special member function of a class that
is executed whenever an object of it's class goes out of
scope or whenever the delete expression is applied to a
pointer to the object of that class.

Example
class Line
{
public:
st1………
st2……….
Line();
~Line(); // This is the destructor: declaration

}; 184
18CSC202J
Object Oriented Design and Programming

UNIT-2

10/6/2022 1
Session 1

Topic : Types of Constructor

10/6/2022 2
CONSTRUCTORS
• It is very common for some part of an object to require
initialization before it can be used.

• Suppose you are working on 100's of objects and the default


value of a particular data member is needed to be zero.

• Initializing all objects manually will be very tedious job.

• Instead, you can define a constructor function which


initializes that data member to zero. Then all you have to do
is declare object and constructor will initialize object
automatically

10/6/2022 3
CONSTRUCTORS
• While defining a constructor you must remember that the
name of constructor will be same as the name of the class,
and constructors will never have a return type.

10/6/2022 4
CONSTRUCTORS
• Constructors can be defined either inside the class definition
or outside class definition using class name and scope
resolution :: operator.

10/6/2022 5
CONSTRUCTOR CHARACTERS
• They must be declared in the public scope.

• They are invoked automatically when the objects are


created.

• They do not have return types, not even void and they
cannot return values.

• They cannot be inherited, though a derived class can call the


base class constructor.

• Like other C++ functions, Constructors can have default


arguments.

10/6/2022 6
• Constructors cannot be virtual.

• We can not refer to their addresses.

• An object with a constructor (or destructor) can not be used


as a member of a union.

• They make ‘implicit calls’ to the operators new and delete


when memory allocation is required.

10/6/2022 7
CONSTRUCTOR TYPES

• Constructors are of three types:


– Default Constructor
– Parameterized Constructor
– Copy Constructor

10/6/2022 8
DEFAULT CONSTRUCTOR

• Default constructor is the constructor which doesn't take any


argument. It has no parameter.
– Syntax :

10/6/2022 9
DEFAULT CONSTRUCTOR

– Example

– Output : 10

10/6/2022 10
DEFAULT CONSTRUCTOR
– As soon as the object is created the constructor
is called which initializes its data members.

– A default constructor is so important for


initialization of object members, that even if we
do not define a constructor explicitly, the
compiler will provide a default constructor
implicitly.

10/6/2022 11
DEFAULT CONSTRUCTOR

Output: 0 or any random value

In this case, default constructor provided by the compiler


will be called which will initialize the object data members
to default value, that will be 0 or any random integer value
in this case.
10/6/2022 12
PARAMETERIZED CONSTRUCTOR
• These are the constructors with parameter.

• Using this Constructor you can provide


different values to data members of different
objects, by passing the appropriate values as
argument.

10/6/2022 13
PARAMETERIZED CONSTRUCTOR

OUTPUT
10
20
30
10/6/2022 14
PARAMETERIZED CONSTRUCTOR

By using parameterized constructor in above case, we


have initialized 3 objects with user defined values. We can
have any number of parameters in a constructor.

10/6/2022 15
COPY CONSTRUCTOR

• These are special type of Constructors which


takes an object as argument, and is used to
copy values of data members of one object
into other object.

10/6/2022 16
COPY CONSTRUCTOR

• These are special type of Constructors which


takes an object as argument, and is used to
copy values of data members of one object
into other object.

• It is usually of the form X (X&), where X is the


class name. The compiler provides a default
Copy Constructor to all the classes.

10/6/2022 17
COPY CONSTRUCTOR

• As it is used to create an object, hence it is called a constructor. And, it


creates a new object, which is exact copy of the existing copy, hence it is
called copy constructor.

10/6/2022 18
COPY CONSTRUCTOR

10/6/2022 19
COPY CONSTRUCTOR

Output :
Normal constructor : 10 15
Copy constructor : 10 15

10/6/2022 20
STATIC CONSTRUCTOR
• C++ doesn’t have static constructors but you can emulate them using a
static instance of a nested class.

class has_static_constructor {
friend class constructor;
struct constructor {
constructor() { /* do some constructing here … */ }
};
static constructor cons;
};

// C++ needs to define static members externally.


has_static_constructor::constructor has_static_constructor::cons;

10/6/2022 21
Try out program

10/6/2022 22
Questions
1. What is a copy constructor?
a) A constructor that allows a user to move data from one object to another
b) A constructor to initialize an object with the values of another object
c) A constructor to check the whether to objects are equal or not
d) A constructor to kill other copies of a given object.
2. What happens if a user forgets to define a constructor inside a class?
a) Error occurs
b) Segmentation fault
c) Objects are not created properly
d) Compiler provides a default constructor to avoid faults/errors.
3. How many parameters does a copy constructor require?
a) 1
b) 2
c) 0
d) 3

10/6/2022 23
Session 2 & 3

Feature Polymorphism:
Constructor overloading &
Method overloading

10/6/2022 24
Polymorphism

• The word polymorphism means having many forms.

• In simple words, we can define polymorphism as the ability of a


message to be displayed in more than one form.

• Real life example of polymorphism: A person at the same time


can have different characteristic. Like a man at the same time is
a father, a husband, an employee.

• So the same person posses different behaviour in different


situations. This is called polymorphism.

10/6/2022 25
Polymorphism

• Polymorphism is considered as one of the important features


of Object Oriented Programming.

• Polymorphism allows us to perform a single action in different


ways. In other words, polymorphism allows you to define one
interface and have multiple implementations.

• The word “poly” means many and “morphs” means forms, So


it means many forms.

10/6/2022 26
POLYMORPHISM
Types of Polymorphism

• Basically, there are two types of polymorphism:


– Compile time (or static) polymorphism
– Run-time (or dynamic) polymorphism.

• Static polymorphism -> Method overloading - calls a function


using the best match technique or overload resolution.

10/6/2022 28
Polymorphism

• Overloading
– Constructor Overloading
– Method Overloading
– Operator Overloading

• Overriding
– Method Overriding

10/6/2022 29
Constructor Overloading
Just like other member functions, constructors can also be overloaded. When
you have both default and parameterized constructors defined in your class
you are having Overloaded Constructors, one with no parameter and other
with parameter.
You can have any number of Constructors in a class that differ in parameter
list.

class Student
{
int rollno;
string name;
public:
Student(int x)
{
rollno=x;
name="None";
}
Student(int x, string str)
{
rollno=x ;
name=str ;
}
};

int main()
{
Student A(10);
Student B(11,"Ram");
}
In above case we have defined two constructors with different parameters,
hence overloading the constructors.
Example-2
include <iostream>
Using namespace std;
class Line
{
private:
double length;
public:g
double getLength( void );
};
// Member functions definitions including constructor
Line::Line(void) //constructor
{
cout << "Object is being created" << endl;
}
void Line::setLength( double len ) // len is 6.0
{
length = len;
}
double Line::getLength( void )
{
return length;
}
void main( ) // Main function for the program
{
Line line; //implicit call
(or) Line line=Line() ; //explicit call
line.setLength(6.0); // set line length
cout << "Length of line : " << line.getLength() <<endl;
Object as Arguments
The use of objects as function arguments .It Performs the addition of time in the hours
and minutes format

#include<iostream>
using namespace std;
class time
{
int hours,minutes;
public:
void gettime(int h, int m)
{
hours=h;
minutes=m;
}
void puttime(void)
{
cout<<hours<<"hours and";
cout<<minutes<<"minutes "<<endl;
}
void sum(time,time); //object as arguments
void time::sum(time t1,time t2)
{
minutes=t1.minutes +t2.minutes;
hours =minutes/60;
minutes=minutes%60;
hours=hours+t1.hours+t2.hours;
}
void main( )
{
The output of the program is
time t1,t2,t3;
T1 = 2 hours and 45 minutes
t1.gettime(2,45); T2 = 3 hours and 30 minutes
t2.gettime(3,30); T3 = 6 hours and 15 minutes
t3.sum(t1,t2);

cout<<“T1=";t1.puttime();
cout <<“T2=";t2.puttime();
cout <<“T3=";t3.puttime();

}
Default Arguments
Default Arguments
One of the most useful facilities available in C++ is the facility to defined default argument
values for functions. In the function prototype declaration, the default values are given.
Whenever a call is made to a function without specifying an argument, the program will
automatically assign values to the parameters from the default function prototype
declaration. default arguments facilitate easy development and maintenance of program.
// For example, The following program segment illustrates the default argument declaration:
#include <iostream>
using namespace std;
void sum (int x = 10, int y = 20);
/ / function prototype declaration
void main ( ) / / with default argument list
{
int a,b;
sum ( ); / / function calling
}
void sum (int a1, int a2) / / function definition
{
int temp;
temp = a1+a2; / / a1 = 10 and a2 = 20 by default arguments
}
A program find the sum of the given numbers using default argument declaration.
/ /default argument declaration
#include <iostream>
using namespace std;
void sum ( int a, int b, int c= 6, int d = 10); //default arguments must add right to left
void main ( )
{
int a, b, c, d;
cout << “ enter any two numbers \n”;
cin >> a >>b; // a=11 b=21
sum (a, b) ; / / sum of default values
}
void sum (int a1, int a2, int a3, int a4)
{
int temp;
temp = a1 + a2 + a3 + a4;
cout << “ a = “ << a1 << endl;
cout << “ b = “ << a2 << endl;
cout << “ c = “ << a3 << endl;
cout << “ d = “ << a4 << endl;
cout << “ sum = “ << temp;
}
We must add defaults from right to left. We cannot provide a default value to a particular
argument in the middle of an argument list.
Case 1

/ /default argument declaration


#include <iostream>
void main ( )
{
void sum (int a=2, int b, int c= 6, int d = 10);

sum (b); / / invalid


}
Case 2//
/ /default argument declaration
#include <iostream>
void main ( )
{
void main (int a=2 , int b =3 , int c , int d);

sum (c,d); / / invalid


}
.
A function may have more then one default parameter. The default
parameters must be grouped consecutively and are available only at the
end of a function declaration. Following is a valid way of a function
declaration and calling a function with default arguments

Case 3
/ /default argument declaration
#include <iostream>
void main ( )
{
void sum (int a ,int b ,int c= 5 , int d = 8);

sum (a,b) ; / / valid


}
MCQ Questions
1. Which among the following best describes constructor overloading?

a) Defining one constructor in each class of a program


b) Defining more than one constructor in single class
c) Defining more than one constructor in single class with different
signature
d) Defining destructor with each constructor

Answer: c
Explanation: If more than one constructors are defined in a class with same
signature, then that results in error. The signatures must be different. So that
the constructors can be differentiated.

10/6/2022 41
MCQ Questions
2. Can constructors be overloaded in derived class?

a) Yes, always
b) Yes, if derived class has no constructor
c) No, programmer can’t do it
d) No, never

Answer: d
Explanation: The constructor must be having the same name as that of a
class. Hence a constructor of one class can’t even be defined in another class.
Since the constructors can’t be defined in derived class, it can’t be overloaded
too, in derived class.

10/6/2022 42
MCQ Questions
3. Does constructor overloading include different return types for constructors to be
overloaded?

a) Yes, if return types are different, signature becomes different


b) Yes, because return types can differentiate two functions
c) No, return type can’t differentiate two functions
d) No, constructors doesn’t have any return type

Answer: d
Explanation: The constructors doesn’t have any return type. When we can’t
have return type of a constructor, overloading based on the return type is not
possible. Hence only parameters can be different.

10/6/2022 43
MCQ Questions
4. Why do we use constructor overloading?

a) To use different types of constructors


b) Because it’s a feature provided
c) To initialize the object in different ways
d) To differentiate one constructor from another

Answer: c
Explanation: The constructors are overloaded to initialize the objects of a
class in different ways. This allows us to initialize the object with either
default values or used given values. If data members are not initialized then
program may give unexpected results.

10/6/2022 44
MCQ Questions
5. Which constructor will be called from the object created in the code below?
class A
{ int i;
A()
{
i=0; cout&lt;&lt;i;
}
A(int x=0)
{
i=x; cout&lt;&lt;I;
}
};
A obj1;

a) Default constructor
ANSWER : C
b) Parameterized constructor Explanation: When a default constructor is
c) Compile time error defined and another constructor with 1 default
d) Run time error value argument is defined, creating object without
parameter will create ambiguity for the compiler.
The compiler won’t be able to decide which
10/6/2022
constructor should be called, hence compile 45time
error.
Method Overloading
• Method overloading is a feature in C++ that allows creation
of several methods with the same name but with different
parameters.

• For example, print(), print(int), and print("Hello") are


overloaded methods.

• While calling print() , no arguments are passed to the


function

• When calling print(int) and print("Hello") , an integer and a


string arguments are passed to the called function.

• Allows one function to perform different tasks


10/6/2022 46
Method Overloading
In C++ programming, two functions can have same name if either number of arguments or
type of arguments passed to functions are different. These types of functions having
similar name are called overloaded functions.
/* Example of function overloading */
voidt test() //no argument
{ cout<<“Display some text”;
}
void test(int a) //one argument
{
Cout<<“A value”<<a;
}
void test(double a) //one double argument
{
Cout<<“A float value”<<a;
}
Void test(int a, double b) //2 arguments
{
Cout<<“A and B values are “<<a<<b;
}
Method Overloading
/*Calling overloaded function test() with different argument/s.*/
#include <iostream>
using namespace std;
void test(int); //prototype declaration
void test(float);
void test(int, float);
void main()
{
int a = 5; float b = 5.5;
test(a); //function declaration or calling function
test(b);
test(a, b);
}
Method Overloading
void test(int var) //definition part or calling function
{
cout<<"Integer number: "<<var<<endl;
}
void test(float var)
{
cout<<"Float number: "<<var<<endl;
}
void test(int var1, float var2)
{
cout<<"Integer number: "<<var1;
cout<<" And float number:"<<var2;
}
Output
Integer number: 5 Float number: 5.5 Integer number: 5 And float number: 5.5
#include<iostream>
Example
#include<stdlib>
Using namespace std;
#define pi 3.14
class fn
{
public:
void area(int); //circle
void area(int,int); //rectangle
void area(float ,int,int); //triangle
};
void fn::area(int a)
{
cout<<"Area of Circle:"<<pi*a*a;
}
void fn::area(int a,int b)
{
cout<<"Area of rectangle:"<<a*b;
}
void fn::area(float t,int a,int b)
{
cout<<"Area of triangle:"<<t*a*b;
}
void main()
{
int ch;
int a,b,r;
clrscr();
fn obj;
cout<<"\n\t\tFunction Overloading";
cout<<"\n1.Area of Circle\n2.Area of Rectangle\n3.Area of Triangle\n4.Exit\n:”;
cout<<”Enter your Choice:";
cin>>ch;
switch(ch)
{
case 1:
cout<<"Enter Radius of the Circle:";
cin>>r;
obj.area(r);
break;
Questions
1. Which of the following permits function overloading on c++?
a) type
b) number of arguments
c) type & number of arguments
d) number of objects
2. Overloaded functions are ________________
a) Very long functions that can hardly run
b) One function containing another one or more functions inside it
c) Two or more functions with the same name but different number of
parameters or type
d) Very long functions
3. What should be passed in parameters when function does not require any
parameters?
a) void
b) blank space
c) both void & blank space
d) tab space

10/6/2022 52
Session 6, 7 & 8
Operator Overloading &
Types

10/6/2022 53
Operator overloading
• Overloading means assigning different meaning
to an operation depending on the context.
• C++ permits overloading of operators, thus
allowing us to assign multiple meanings to the
operators.
• Example:
• The input/output operators << and >> are good
examples of operator overloading although the
built in definition of the << operator is for shifting
of bits. It is also used for displaying the values of
various data types.
• We can overload all the C++ operators except
the following,
1. Class member access operators (., . *)
2. Scope resolution operator (: :)
3. Size operator (sizeof)
4. Conditional operator (?:)
• Defining operator overloading.
i) To define an additional task to an operator,
operator function is used.
The general form is.
Return type classname :: operator op (arglist)
{
Function body //task defined
}
Unary Operator
- Operators attached to a single operand.
(-a, +a, --a, ++a, a--, a++)
Binary Operator
- Operators attached to two operand.
(a-b, a+b, a*b, a/b, a%b, a>b, a<b )

10/6/2022 57
Unary Operator Over Loading -
• In overloading unary operator a member
function will have no arguments.
• Let us consider the unary minus operator. A
minus operator, when used as a unary takes
just one operand.
• This operator changes the sign of an operand
when applied to a basic data item.
# include <iostream>
void unary ::operator-( )
using namespace std; {
class unary x = -x ;
y = -y ;
{
z = -z ;
int x, y, z; }
public: main ( )
void getdata (int a, int , intc); {
unary u;
void display (void); u.getdata(20, -30, 40);
void operator- ( ); // cout << “ u :” ;
overload unary minus. u. display ( ) ;
}; -u;
cout << “ u :” ;
void unary :: getdata (int a, int b, int c) u. display ( ) ;
{ }
Output: -
x = a; u : 20 -30 40
y = b; u : -20 30 -40
z = c;
}
void unary : : display (void)
{
cout << x << “ ” << y << “ ” << z <<
“\n”;
Overloading the assignment operator
• The assignment operator (operator=) is used to copy values from one object to another already
existing object.
Assignment vs Copy constructor
• The purpose of the copy constructor and the assignment operator are almost equivalent -- both
copy one object to another. However, the copy constructor initializes new objects, whereas the
assignment operator replaces the contents of existing objects.

• The difference between the copy constructor and the assignment operator causes a lot of
confusion for new programmers, but it’s really not all that difficult. Summarizing:

• If a new object has to be created before the copying can occur, the copy constructor is used
(note: this includes passing or returning objects by value).
• If a new object does not have to be created before the copying can occur, the assignment
operator is used.
#include <iostream>
using namespace std;
class Distance
{
private:
int feet;
int inches;
public: // required constructors
Distance()
{
feet = 0;
inches = 0;
}
Distance(int f, int i)
{
feet = f;
inches = i;
}
void operator = (const Distance &D )
{
feet = D.feet;
inches = D.inches;
}
// method to display distance
void displayDistance()
{
cout << "F: " << feet << " I:“ << inches << endl;
} };
int main()
{
Distance D1(11, 10), D2(5, 11);
cout << "First Distance : "; D1.displayDistance();
cout << "Second Distance :"; D2.displayDistance();
// use assignment operator
D1 = D2;
cout << "First Distance :";
D1.displayDistance(); return 0; }

Output:
First Distance : F: 11 I:10
Second Distance :F: 5 I:11
First Distance :F: 5 I:11
Introduction
One of the exciting features of C++
Works only on the single variable
It can be overloaded two ways
1. Static member function
2. Friend function
-,+,++,-- those are unary operator which we can
overloaded.
10/6/2022 62
Using a member function to Overload Unary
Operator

10/6/2022 63
Using a Friend Function to Overload a Unary Operator

• The function will take one operand as an argument.


• This operand will be an object of the class.
• The function will use the private members of the class only
with the object name.
• The function may take the object by using value or by
reference.
• The function may or may not return any value.
• The friend function does not have access to the this pointer.
10/6/2022 64
Example:- Use of friend function to overload a unary operator

10/6/2022 65
10/6/2022 66
Binary Operator Overloading:-

• Following example shows how to overload +


operator to add 2 complex number
Syntax:-

return_type :: operator binary_operator_symbol (arg)


{
// function definition
}
Example-1
# include<iostream> void complex : : display (void)
using namespace std; {
class complex cout << x << “+ j” << y << “\n” .;
{
}
float x, y;
public : main ( )
complex ( ); {
complex (float real, float imag) complex c1,c2,c3;
{
c1 = complex (2.5, 3.5);
x = real;
y = imag; c2 = complex (1.6, 2.7);
} c3 = c1 + c2;
complex operator +(complex); cout << “c1 =” ; c1.display( ) ;
void display(void);
cout << “c2 =” ; c2.display( ) ;
};
complex complex:: cout << “c3 =” ; c3.display( ) ;
operator+(complex c) }
{ Output: -
complex temp; // obj creation
c1 = 2.5 + j 3.5
temp.x = x + c.x; // assign values
temp.y = y + c.y; c2 = 1.6 + j 2.7
return (temp); c3 = 4.1 + j 6.2
Example-2

#include <iostream>
using namespace std;
class multiply
{
int first,second;
public:
void getdata(int a,int b)
{
first=a; second=b;
}

Contd...,

10/6/2022 70
void display()
{
cout<<“first=“<<first<<“second=“<<second<<endl;
}
multiply operator *(multiply c);
};
void multiply::operator *(multiply c)
{
multiply temp;
temp.first=first*c.first;
temp.second=second*c.second;
return temp;
}

10/6/2022 Contd..,71
int main()
{
multiply obj1,obj2,obj3;
obj1.getdata(15,20);
obj2.getdata(3,45);
obj3=obj1*obj2;
obj3.display();
return 0;
}
Output:
45
900

10/6/2022 72
Binary Operator Overloading using Friend Function

#include <iostream> Complex operator + (Complex


c1, Complex c2)
using namespace std; {
class Complex Complex temp;
{ temp.real = c1.real + c2.real;
private: temp.img = c1.img + c2.img;
int real; return temp;
int img; }
public: int main ()
Complex (int r = 0, int i = 0) {
{ Complex C1(5, 3), C2(10, 5),
real = r; C3;
img = i; C1.Display();
} cout << " + ";
void Display () C2.Display();
{ cout << " = ";
cout << real << "+i" << C3 = C1 + C2;
img; C3.Display();
} }
friend Complex operator +
(Complex c1, Complex c2);
MCQ Questions
I. In case of operator overloading, operator function must be ______ .

1. Static member functions

2. Non- static member functions

3. Friend Functions

a. Only 2

b. Only 1, 3

c. Only 2 , 3

d. All 1 , 2, 3

10/6/2022 74
MCQ Questions
In case of operator overloading, operator function must be ______ .

1. Static member functions

2. Non- static member functions

3. Friend Functions

a. Only 2

b. Only 1, 3

c. Only 2 , 3

d. All 1 , 2, 3

10/6/2022 75
MCQ Questions

II. Using friend operator function, following perfect set of operators may
not be overloaded.

a. = , ( ) , [ ] , ->

b. <<, = = , [ ] , >>

c. ?, = , ( ) , ++

d. +,-,--,++

10/6/2022 76
MCQ Questions

II. Using friend operator function, following perfect set of operators may
not be overloaded.

a. = , ( ) , [ ] , ->

b. <<, = = , [ ] , >>

c. ?, = , ( ) , ++

d. +,-,--,++

10/6/2022 77
MCQ Questions

III. When overloading unary operators using Friend function,it


requires_____ argument/s.

a. Zero

b. One

c. Two

d. None of these.

10/6/2022 78
MCQ Questions

III. When overloading unary operators using Friend function,it


requires_____ argument/s.

a. Zero

b. One

c. Two

d. None of these.

10/6/2022 79
MCQ Questions

IV. In case of binary operator overloading with member function,


which of following statement should be taken into consideration?

a. Right hand operand must be object.

b. Left hand operand must be object.

c. Both the operands must be objects.

d. All of these should be considered.

10/6/2022 80
MCQ Questions

IV. In case of binary operator overloading with member function,


which of following statement should be taken into consideration?

a. Right hand operand must be object.

b. Left hand operand must be object.

c. Both the operands must be objects.

d. All of these should be considered.

10/6/2022 81
MCQ Questions

V.Which is the correct statement anout operator overloading


in C++?

A. Only arithmetic operators can be overloaded


B. Only non-arithmetic operators can be overloaded
C. Precedence of operators are changed after overlaoding
D. Associativity and precedence of operators does not
change

10/6/2022 82
MCQ Questions

V. Which is the correct statement anout operator overloading


in C++?

A. Only arithmetic operators can be overloaded


B. Only non-arithmetic operators can be overloaded
C. Precedence of operators are changed after overlaoding
D. Associativity and precedence of operators does not
change

10/6/2022 83
Session 11

UML Sequence Diagram

10/6/2022 84
Interaction Diagram
• Interaction diagrams are used to observe the dynamic
behavior of a system.

• Interaction diagram visualizes the communication and


sequence of message passing in the system.

• Interaction diagram represents the structural aspects of


various objects in the system.

• Interaction diagram represents the ordered sequence of


interactions within a system.

• Interaction diagram provides the means of visualizing the


real time data via UML.
10/6/2022 85
• This interactive behavior is represented in UML by two
diagrams known as

– Sequence diagram
– Collaboration diagram.

• Sequence diagram emphasizes on time sequence of


messages from one object to another.

• Collaboration diagram emphasizes on the structural


organization of the objects that send and receive messages.

10/6/2022 86
How to Draw an Interaction Diagram?
• The purpose of interaction diagrams is to capture the dynamic aspect of
a system.

• So to capture the dynamic aspect, we need to understand what a


dynamic aspect is and how it is visualized. Dynamic aspect can be defined
as the snapshot of the running system at a particular moment.

• Following things are to be identified clearly before drawing the


interaction diagram
– Objects taking part in the interaction.
– Message flows among the objects.
– The sequence in which the messages are flowing.
– Object organization.

10/6/2022 87
Sequence Diagram

• A sequence diagram simply depicts interaction between


objects in a sequential order i.e. the order in which these
interactions take place.

10/6/2022 88
Sequence Diagram Notations
Actors :
An actor in a UML diagram represents a type of role where it interacts
with the system and its objects.

10/6/2022 89
2.Lifelines :
A lifeline is a named element which depicts an individual participant
in a sequence diagram. So basically each instance in a sequence
diagram is represented by a lifeline.
Lifeline elements are located at the top in a sequence diagram.
lifeline follows the following format :
Instance Name : Class Name

10/6/2022 90
3.Messages :

Communication between objects is depicted using messages. The


messages appear in a sequential order on the lifeline.

We represent messages using arrows. Lifelines and messages form the


core of a sequence diagram.

10/6/2022 91
Synchronous messages
▪ A synchronous message waits for a reply before the interaction can move
forward.
▪ The sender waits until the receiver has completed the processing of the
message.
▪ The caller continues only when it knows that the receiver has processed
the previous message i.e. it receives a reply message.
▪ A large number of calls in object oriented programming are
synchronous. We use a solid arrow head to represent a synchronous
message.

10/6/2022 92
Asynchronous Messages

▪ An asynchronous message does not wait for a reply from the receiver.
▪ The interaction moves forward irrespective of the receiver processing
the previous message or not.
▪ We use a lined arrow head to represent an asynchronous message.

10/6/2022 93
Create message
▪ We use a Create message to instantiate a new object in the sequence
diagram.
▪ It is represented with a dotted arrow and create word labeled on it to
specify that it is the create Message symbol.
For example :
▪ The creation of a new order on a e-commerce website would require
a new object of Order class to be created.

10/6/2022 94
Delete Message

• We use a Delete Message to delete an object.


• It destroys the occurrence of the object in the system.
• It is represented by an arrow terminating with a x.
For example – In the scenario below when the order is received by the
user, the object of order class can be destroyed

10/6/2022 95
Self Message

• A message an object sends to itself, usually shown as a U


shaped arrow pointing back to itself.

10/6/2022 96
Reply Message

• Reply messages are used to show the message being sent from the
receiver to the sender.

• We represent a return/reply message using an open arrowhead with a


dotted line.

• The interaction moves forward only when a reply message is sent by the
receiver.

10/6/2022 97
Found Message

• A Found message is used to represent a scenario where an unknown


source sends the message.
• It is represented using an arrow directed towards a lifeline from an end
point.

10/6/2022 98
Lost Message
• A Lost message is used to represent a scenario where the recipient is not
known to the system.
• It is represented using an arrow directed towards an end point from a
lifeline.
For example:

10/6/2022 99
Sample example:

The above sequence diagram contains lifeline notations and notation of various
messages used in a sequence diagram such as a create, reply, asynchronous
message, etc.
Example:
• The ordered sequence of events in a given
sequence diagram is as follows:
– Place an order.
– Pay money to the cash counter.
– Order Confirmation.
– Order preparation.
– Order serving.
Sequence diagram example(1)
The following sequence diagram example represents McDonald's ordering system:
Example(2)
A sequence diagram for an emotion based music
player
• Firstly the application is opened by the user.
• The device then gets access to the web cam.
• The webcam captures the image of the user.
• The device uses algorithms to detect the face and predict
the mood.
• It then requests database for dictionary of possible
moods.
• The mood is retrieved from the database.
• The mood is displayed to the user.
• The music is requested from the database.
• The playlist is generated and finally shown to the user.
Example – 3

10/6/2022 105
Example-4

9/27/2022 106
Sequence Diagram from Use case diagram(
Online Library System)

9/27/2022 107
Identify the objects or actors
Librarian
Online Library Management system
User credentials database
Email system

Steps to create Sequence Diagram


The librarian request the system to create a new online library
account
The librarian then selects the library user account type
The librarian enters the user’s details
The user’s details are checked using the user Credentials Database
The new library user account is created
A summary of the new account’s details is then emailed to the user
9/27/2022 108
Sequence Diagram

9/27/2022 109
Benefits of a Sequence Diagram

Explore any real application or a system.


Represent message flow from one object to another object.
Easier to maintain and generate
Easily updated according to the changes within a system.

Drawbacks of a sequence diagram


Become complex when too many lifelines are involved in the system.
If the order of message sequence is changed, then incorrect results are
produced.
Each sequence needs to be represented using different message notation, which
can be a little complex.
The type of message decides the type of sequence inside the diagram.
9/27/2022 110
Questions
1. What does a message mean?
a) It Passes all communications from one object to another and are
represented by message arrows in sequence diagrams.
b) The message goes from the sending object’s lifeline to the receiving
object’s lifeline.
c) It is a rectangle containing an identifier with a dashed line extending below
the rectangle.
d) List of all attributes.
2. What is a lifeline?
a) It is a frame consisting of a rectangle with a pentagon in its upper left-hand
corner
b) It is a rectangle containing an identifier with a dashed line extending
below the rectangle
c) It is a name compartment; the interaction is represented inside the
rectangle
d) Emergency situation in real world approach.

10/6/2022 111
Session 12

UML Collaboration
Diagram

10/6/2022 112
Collaboration diagram

COLLABORATION DIAGRAM depicts the relationships


and interactions among software objects. They are
used to understand the object architecture within a
system rather than the flow of a message as in a
sequence diagram. They are also known as
“Communication Diagrams

In the collaboration diagram, the method call


sequence is indicated by some numbering technique.
The number indicates how the methods are called one
after another.
10/6/2022 113
Benefits of Collaboration Diagram

It is also called as a communication diagram.


It emphasizes the structural aspects of an interaction diagram - how
lifeline connects.
Its syntax is similar to that of sequence diagram except that lifeline
don't have tails.
Messages passed over sequencing is indicated by numbering each
message hierarchically.
Compared to the sequence diagram communication diagram is
semantically weak.
Object diagrams are special case of communication diagram.
It allows you to focus on the elements rather than focusing on the
message flow as described in the sequence diagram.
Sequence diagrams can be easily converted into a collaboration
diagram as collaboration diagrams are not very expressive.
10/6/2022 114
Components

10/6/2022 115
Example
Following diagram represents the sequencing over student management system:

10/6/2022 116
Example

The above collaboration diagram represents a student information


management system. The flow of communication in the above diagram
is given by,

A student requests a login through the login system.

An authentication mechanism of software checks the request.

If a student entry exists in the database, then the access is allowed;


otherwise, an error is returned .

10/6/2022 117
Drawbacks of a collaboration diagram
Collaboration diagrams can become complex when too many objects are
present within the system.

It is hard to explore each object inside the system.

Collaboration diagrams are time consuming.

The object is destroyed after the termination of a program.

9/27/2022 118
MCQ’s

1. A collaboration diagram shows


a. Structural Aspect
b. Behavioral Aspect
c. Environmental Aspect
d. Both A and B
e. Both B and C

2. which diagram is used to show interactions between messages


are classified as?
a.activity
b.state chart
c.collaboration
d.object lifeline

10/6/2022 119
Conversion of Sequence to Collaboration
Diagram

10/6/2022 120
Conversion of Sequence to Collaboration
Diagram

Sequence Diagrams Collaboration Diagrams

The sequence diagram represents the UML, The collaboration diagram also comes under
which is used to visualize the sequence of the UML representation which is used to
calls in a system that is used to perform a visualize the organization of the objects
specific functionality. and their interaction.
The collaboration diagram are used to
The sequence diagram are used to represent
represent the structural organization of
the sequence of messages that are flowing
the system and the messages that are sent
from one object to another.
and received.

The sequence diagram is used when time The collaboration diagram is used when
sequence is main focus. object organization is main focus.

The collaboration diagrams are better suited


The sequence diagrams are better suited of
for depicting simpler interactions of the
analysis activities.
smaller number of objects.

10/6/2022 121
Session 13

Inheritance & Types

10/6/2022 122
Inheritance

Inheritance is the capability of one class to acquire properties

01 Definition and characteristics from another class. The class whose


properties are inherited by other class is called
the Parent or Base or Super class. And, the class which inherits
properties of other class is called Child or Derived or Sub class.
02 Synta
x
Single Inheritance, Multiple Inheritance, Hierarchical
Inheritance, Multilevel Inheritance, and Hybrid Inheritance (also
03 Type
known as Virtual Inheritance)
s
Note : All members of a class except Private, are inherited
1. Code Reusability
04 Advantages 2. Method Overriding (Hence, Runtime Polymorphism.)
3. Use of Virtual Keyword
Inheritance Types
01 Single 02 Multiple 03 Hierarchic
al

04 Multilevel
05 Hybrid
Single Inheritance

• In single inheritance, a class derives from one base class only. This
means that there is only one subclass that is derived from one
superclass.
• Syntax:
class subclass_name : access_specifier base_class
{ //body of subclass };

Class A

Class B
Multiple Inheritance
• A class can inherit properties from more than one class which is
known as multiple inheritances.
• Syntax:
class subclass_name : access_specifier base_class1, access_mode
base_class2, ....
{ //body of subclass };

Class B Class C

Class A
Multilevel Inheritance

• A class can be derived from another derived class which is known as


multilevel inheritance.

Class C

Class B

Class A
Hierarchical Inheritance

• In this type of inheritance, one parent class has more than one child
class

Class A

Class B Class C

Class b1 Class b2 Class c1 Class c2


Hybrid Inheritance
• There could be situations where we need to apply two or more types of
inheritance to design one inheritance called hybrid inheritance.

Class C

Class B Class D

Class A
Modes of
Inheritance
If we derive a sub class from a public base class. Then the public
01 Public member of the base class will become public in the derived class
and protected members of the base class will become protected
in derived class
If we derive a sub class from a Protected base class. Then both
02 Protected
public member and protected members of the base class will
become protected in derived class.
If we derive a sub class from a Private base class. Then both
03 private
public member and protected members of the base class will
become Private in derived class.

The private members in the base class cannot be directly


accessed in the derived class, while protected members can be
Note:
directly accessed. For example, Classes B, C and D all contain
the variables x, y and z in below example
Inheritance Access Matrix
10/6/2022 132
18CSC202J - Syllabus
Unit 3 :

Single and Multiple Inheritance - Multilevel inheritance -


Hierarchical - Hybrid Inheritance - Advanced Functions -
Inline - Friend - Virtual -Overriding - Pure virtual function
-Abstract class and Interface -UML State Chart Diagram -
UML Activity Diagram

07-10-2022 Prepared by NWC Department 1


Inheritence

• The capability of a class to derive properties and


characteristics from another class is called
Inheritance. Inheritance is one of the most important
features of Object-Oriented Programming.

10/7/2022 C ,C++ and UML Basics 2


• When derived class inherits the base class, it means, the derived
class inherits all the properties of the base class, without
changing the properties of base class and may add new features
to its own.
• These new features in the derived class will not affect the base
class. The derived class is the specialized class for the base class.
• Sub Class: The class that inherits properties from another class
is called Subclass or Derived Class or Child Class
• Super Class: The class whose properties are inherited by a
subclass is called Base Class or Superclass or Parent Class.
10/7/2022 C ,C++ and UML Basics 3
Advantages of Inheritence

• Reusability: inheritance helps the code to be reused in


many situations.
• Using the concept of inheritance,the programmer can
create as many derived classes from the base class as
needed while adding specific features to each derived
class as needed.
• Saves Time and Effort:The above concept of
reusability achieved by inheritance saves the
programmer time and effort.The main code written can
be reused in various situations as needed.
10/7/2022 C ,C++ and UML Basics 4
Modes of Inheritence

• The visibility mode (private, public or protected) in the


definition of the derived class specifies whether the
features of the base class are privately derived, publicly
derived or protected derived.
• The visibility modes control the access-specifier to be for
inheritable members of base-class, in the derived class.
– Public Mode
– Private Mode
– Protected Mode
10/7/2022 C ,C++ and UML Basics 5
Publicly Visbility Modes of Inheritence

• Public Visibility mode gives the least privacy to the


attributes of the base class.
• If the visibility mode is public, it means that the derived
class can access the public and protected members of
the base class, but not the private members of the base
class.

10/7/2022 C ,C++ and UML Basics 6


Publicly Visbility Modes of Inheritence

10/7/2022 C ,C++ and UML Basics 7


Privately Visbility Modes of Inheritence

• Public Visibility mode gives the most privacy to the


attributes of the base class.
• If the visibility mode is private, that means that the
derived class can privately access the public and
protected members of the base class.

10/7/2022 C ,C++ and UML Basics 8


Privately Visbility Modes of Inheritence

10/7/2022 C ,C++ and UML Basics 9


Protected Visbility Modes of Inheritence

• Protected visibility mode is somewhat between the public


and private modes.
• If the visibility mode is protected, that means the derived
class can access the public and protected members of
the base class protectively.

10/7/2022 C ,C++ and UML Basics 10


Visbility Modes of Inheritence

10/7/2022 C ,C++ and UML Basics 11


Types of Inheritance

07-10-2022 Prepared by NWC Department 12


Inheritance

Inheritance is the capability of one class to acquire properties and

01 Definition
characteristics from another class. The class whose properties are
inherited by other class is called the Parent or Base or Super class.
And, the class which inherits properties of other class is
called Child or Derived or Sub class.
02 Syntax

Single Inheritance, Multiple Inheritance, Hierarchical Inheritance,


Multilevel Inheritance, and Hybrid Inheritance (also known as Virtual
03 Types
Inheritance)
Note : All members of a class except Private, are inherited
1. Code Reusability
04 Advantages
2. Method Overriding (Hence, Runtime Polymorphism.)
3. Use of Virtual Keyword
Inheritance Types
01 Single 02 Multiple 03 Hierarchical

04 Multilevel
05 Hybrid
Modes of
Inheritance
If we derive a sub class from a public base class. Then the public
01 Public member of the base class will become public in the derived class and
protected members of the base class will become protected in derived
class
If we derive a sub class from a Protected base class. Then both public
02 Protected
member and protected members of the base class will become
protected in derived class.
If we derive a sub class from a Private base class. Then both public
03 private member and protected members of the base class will become
Private in derived class.

The private members in the base class cannot be directly accessed in


the derived class, while protected members can be directly accessed.
Note:
For example, Classes B, C and D all contain the variables x, y and z in
below example
Inheritance Access Matrix
SINGLE INHERITANCE
Example

Base Class Base Class ClassA

Derived Derived Class Class B


Class
Single Inheritance
In single inheritance, a class is allowed to inherit from only one class.
i.e. one sub class is inherited by one base class only. Based on the
visibility mode used or access specifier used while deriving, the
properties of the base class are derived. Access specifier can be private,
protected or public.

Syntax:
class Classname // base class
{
..........
};
class classname: access_specifier baseclassname
{

};
Example
#include <iostream>
using namespace std;
class base //single base class
{ public:
int x;
void getdata()
{
cout << "Enter the value of x = ";
cin >> x;
}
};
class derived : public base //single derived
{
int y;
public:
void readdata()
{
cout << "Enter the value of y = ";
cin >> y;
}
Applications of Single Inheritance

Grading 1. University Grading System

System 2. Employee and Salary

Student
Multiple Inheritance

Base Class Base Class


Multiple Inheritance
In this type of inheritance a single derived class may inherit from two or
more than two base classes.

Syntax:
class A // base class
{
..........
};
class B
{
..........
}
class c : access_specifier A, access_specifier B // derived class
{
...........
};
Example:
#include using namespace std;
class sum1
{
protected: int n1;
};
class sum2
{
protected: int n2;
};
class show : public sum1, public sum2
{
public: int total()
{
cout<<“enter n1”;
cin>>n1;
Applications of Multiple Inhertiance

Distributed Database
MCQ Questions

• What are the things are inherited from the base class?
A. Constructor and its destructor
B. Operator=() members
C. Friends
D. All of the above

10/7/2022 C ,C++ and UML Basics 25


MCQ Questions

• What are the things are inherited from the base class?
A. Constructor and its destructor
B. Operator=() members
C. Friends
D. All of the above

10/7/2022 C ,C++ and UML Basics 26


MCQ Questions
using namespace std; int main()
class Base1 { {
public: Derived d;
Base1() return 0;
{ cout << " Base1" << endl; } }
};
class Base2 { A. Compiler Dependent
public: B. Base1 Base2 Derived
Base2() C. Base2 Base1 Derived
{ cout << "Base2" << endl; } D. Compiler Error
};
class Derived: public Base1, public Base2 {
public:
Derived()
{ cout << "Derived" << endl; }
};

10/7/2022 C ,C++ and UML Basics 27


MCQ Questions
using namespace std; int main()
class Base1 { {
public: Derived d;
Base1() return 0;
{ cout << " Base1" << endl; } }
};
class Base2 { A. Compiler Dependent
public: B. Base1 Base2 Derived
Base2() C. Base2 Base1 Derived
{ cout << "Base2" << endl; } D. Compiler Error
};
class Derived: public Base1, public Base2 {
public:
Derived()
{ cout << "Derived" << endl; }
};

10/7/2022 C ,C++ and UML Basics 28


MCQ Questions

class ABC is derived from Class X, class Y and


class Z . This is ______ inheritance.

A. Multiple
B. Multilevel
C. Hierarchical
D. Single

10/7/2022 C ,C++ and UML Basics 29


MCQ Questions

class ABC is derived from Class X, class Y and


class Z . This is ______ inheritance.

A. Multiple
B. Multilevel
C. Hierarchical
D. Single

10/7/2022 C ,C++ and UML Basics 30


Multilevel Inheritance
A derived class can be derived from another derived class. A child class
can be the parent of another class.

Syntax:
class A // base class
{
..........
};
class B
{
..........
}
class C : access_specifier B
// derived class
{
...........
};
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle";
}
};
class fourWheeler: public Vehicle
{ public:
fourWheeler()
{
cout<<"Objects with 4 wheels are vehicles"<<endl;
}
};
// sub class derived from two base classes
class Car: public fourWheeler{
public:
car()
Hierarichal Inheritance
• In Hierarichal Inheritance we
have several classes that are
derived from a common base
class (or parent class).
• Here in the diagram Class 1,
Class 2 and Class 3 are derived
from a common parent class
called Base Class.

07-10-2022 Prepared by NWC Department 33


Hierarchical Inheritance
How to implement Hierarchal Inheritance in C++
class A {
// Body of Class A • In the example present in the left we have
}; // Base Class class A as a parent class and class B and
class C that inherits some property of Class
A.
class B : access_specifier A
{ • While performing inheritance it is necessary
// Body of Class B to specify the access_specifier which can be
public, private or protected.
}; // Derived Class

class C : access_specifier A
{
// Body of Class C
}; // Derived Class

07-10-2022 Prepared by NWC Department 35


Example
#include <iostream> class C : public A //C is also derived from
using namespace std; class base
class A //single base class {
{ public:
public: void sum()
int x, y; {
void getdata() cout << "\nSum= " << x + y;
{ }
cout << "\nEnter value of x and y:\n"; };
cin >> x >> y; int main()
} {
}; B obj1; //object of derived class B
class B : public A //B is derived from class base C obj2; //object of derived class C
{ obj1.getdata();
public: obj1.product();
void product() obj2.getdata();
{ obj2.sum();
cout << "\nProduct= " << x * y; return 0;
} }
};
Example of Hierarchical Inheritance
class Car { class Volkswagen: public Car {
public: public:
int wheels = 4; string brand = "Volkswagen";
string model = “Beetle”;
void show() {
};
cout << "No of wheels : "<<wheels ;
} class Honda: public Car {
}; public:
string brand = "Honda";
class Audi: public Vehicle { string model = “City”;
public: };
string brand = "Audi";
string model = “A6”;
};

07-10-2022 Prepared by NWC Department 37


MCQ

1. What is the minimum number of levels for a implementing multilevel


inheritance?
a) 1
b) 2
c) 3
d) 4
Ans(C)
2. In multilevel inheritance one class inherits _______________
a) Only one class
b) More than one class
c) At least one class
d) As many classes as required
Ans(a)
3. Can abstract classes be used in multilevel inheritance?
a) Yes, always
b) Yes, only one abstract class
c) No, abstract class doesn’t have constructors
d) No, never
Ans(a)
4. How many abstract classes can be used in multilevel
inheritance?
a) Only 1
b) Only 2
c) At least one less than number of levels
d) Can’t be used
Ans(c)
5. Is it compulsory for all the classes in multilevel
inheritance to have constructors defined explicitly if
only last derived class object is created?
a) Yes, always
b) Yes, to initialize the members
c) No, it not necessary
d) No, Constructor must not be defined
Ans(c)
Hybrid Inheritance

07-10-2022 Prepared by NWC Department 41


Hybrid Inheritance
• Hybrid Inheritance involves
derivation of more than one
type of inheritance.
• Like in the given image we have
a combination of hierarichal and
multiple inheritance.
• Likewise we can have various
combinations.

07-10-2022 Prepared by NWC Department 42


Diagramatic Representation of Hybrid
Inheritance

07-10-2022 Prepared by NWC Department 43


How to implement Hybrid Inheritance in C++
class A
• Hybrid Inheritance is no
{
// Class A body
different than other type of
};
inheritance.
• You have to specify the access
class B : public A
specifier and the parent class in
{
// Class B body
front of the derived class to
};
implement hybrid inheritance.

class C
{
// Class C body
};
07-10-2022 Prepared by NWC Department 44
Access Specifiers
In C++ we have basically three types of access specifiers :
• Public : Here members of the class are accessible outside the class as
well.
• Private : Here members of the class are not accessible outside the
class.
• Protected : Here the members cannot be accessed outside the class,
but can be accessed in inherited classes.

07-10-2022 Prepared by NWC Department 45


Example of Hybrid Inheritance
class A class C
{
{ public:
public:
int x; int y;
}; C()
{
class B : public A
{ y = 4;
public: }
B() };
{
x = 10;
class D : public B, public C
} { public:
}; void sum()
{
07-10-2022 cout
Prepared by NWC Department << "Sum= " << x + y; 46
Order of Constructor Call
Base class constructors are always called in the derived class constructors.
Whenever you create derived class object, first the base class default constructor is
executed and then the derived class's constructor finishes execution.

Points to Remember

Whether derived class's default constructor is called or parameterised is called,


base class's default constructor is always called inside them.

To call base class's parameterised constructor inside derived class's parameterised


constructor, we must mention it explicitly while declaring derived class's
parameterized constructor.
Example
#include <iostream> public:
using namespace std; Derived()
class Base {
{ cout<<"Derived default constructor\n";
int x; y=1;
public: cout<<y<<"\n";
Base() }
{ // parameterized constructor
cout<<"Base default constructor\n"; Derived(int i)
x=0; {
cout<<x<<"\n"; cout << "Derived parameterized constructor\n";
} y=i;
Base(int i) cout << y<<"\n";
{ }};
cout<<"Base default constructor\n"; int main()
x=i; {
cout<<x<<"\n"; //Base b;
}}; Derived d1;
class Derived : public Base Derived d2(10);
{ return 0;
int y; }
Example
class Base
{
int x;
public:
Base()
{
cout<<"Base default constructor";
}
};

class Derived : public Base


{
int y;
public:
Derived()
{
cout<"Derived def. constructor";
}
Order of Constructor Call
class Base
{
Example
int x; :
public:
// parameterized constructor
Base(int i)
{
x = i;
cout<<"BaseParameterized Constructor\n";
}
};

class Derived : public Base


{
int y;
public:
// parameterized constructor
Note:
Constructors have a special job of initializing the object
properly. A Derived class constructor has access only to its own
class members, but a Derived class object also have inherited
property of Base class, and only base class constructor can
properly initialize base class members. Hence all the constructors
are called, else object wouldn't be constructed properly.
• Constructors and Destructors are never inherited and hence never
overridden.
01 Concept
• Also, assignment operator = is never inherited. It can be overloaded
but can't be inherited by sub class.
• They are inherited into the derived class.
• If you redefine a static member function in derived class, all the
0 Static other overloaded functions in base class are hidden.
2 Function • Static Member functions can never be virtual.

Derived class can inherit all base class methods except:


• Constructors, destructors and copy constructors of the base class.
0 Limitat
3 ion • Overloaded operators of the base class.
• The friend functions of the base class.
Calling base and derived class method using base
reference
#include <iostream> Example
using namespace std; :
class Foo
{
public:
int x;

virtual void printStuff()


{
cout<<"BaseFoo printStuff called"<<endl;
}
};

class Bar : public Foo


{
public:
int y;

void printStuff()
Calling base and derived class method using derived
reference
Example
:
#include <iostream>

class Base{
public:
void foo()
{
std::cout<<"base";
}
};
class Derived : public Base
{
public:
void foo()
{
std::cout<<"derived";
}
};
Advanced Functions: Inline, Friend,
Virtual function and Overriding
Inline Member Function
Inline functions are used in C++ to reduce the overhead of a normal function call.
A member function that is both declared and defined in the class member list is called an inline member
function.
The inline specifier is a hint to the compiler that inline substitution of the function body is to be preferred to the
usual function call implementation.

The advantages of using inline member functions are:


1. The size of the object code is considerably reduced.
2. It increases the execution speed, and
3. The inline member function are compact function calls.
Inline Member Function
Syntax: Syntax
class user_defined_name
{ Inline return_type function_name(parameters)
private: {
------------- ----------------
public: ----------------
inline return_type function_name(parameters); }
inline retrun_type function_name(parameters);
---------------
---------------
};
Inline function and classes
It is also possible to define the inline function inside the class.

All the functions defined inside the class are implicitly inline. Thus, all the restrictions of inline
functions are also applied here.

If you need to explicitly declare inline function in the class then just declare the function inside
the class and define it outside the class using inline keyword
#include <iostream>
using namespace std;
class operation inline void operation :: sum()
{ {
int a,b,add; add = a+b;
cout << "Addition of two numbers: " << a+b << "\n";
public: }
void get();
void sum(); int main()
}; {
inline void operation :: get() cout << "Program using inline function\n";
{ operation s;
cout << "Enter first value:"; s.get();
cin >> a; s.sum();
cout << "Enter second value:"; return 0;
cin >> b; }
}

Output:
Enter first value: 45 Enter second value: 15 Addition of two numbers: 60 Difference of two numbers: 30 Product of two numbers: 675 Division of two numbers: 3
Friend Function
1. The main concepts of the object oriented programming paradigm are data hiding and data encapsulation.
2. Whenever data variables are declared in a private category of a class, these members are restricted from
accessing by non – member functions.
3. The private data values can be neither read nor written by non – member functions.
4. If any attempt is made directly to access these members, the compiler will display an error message as
“inaccessible data type”.
5. The best way to access a private data member by a non – member function is to change a private data member
to a public group.
6. When the private or protected data member is changed to a public category, it violates the whole concept or
data hiding and data encapsulation.
7. To solve this problem, a friend function can be declared to have access to these data members.
8. Friend is a special mechanism for letting non – member functions access private data.
9. The keyword friend inform the compiler that it is not a member function of the class.
Friend Function
Granting Friendship to another Class
1. A class can have friendship with another class. Syntax

2. For Example, let there be two classes, first and second. If 01


the class first grants its friendship with the other class class second;forward declaration
second, then the private data members of the class first class first
are permitted to be accessed by the public members of the
class second. But on the other hand, the public member {
functions of the class first cannot access the private private:
members of the class second.
--------------
Friend Function
Two classes having the same Friend
1. A non – member function may have friendship with Syntax
one or more classes. 01 friend return_type
function_name(parameters);
2. When a function has declared to have friendship
with more than one class, the friend classes should have
Example
forward declaration.
3. It implies that it needs to access the private
02 friend return_type fname(first one,
second two)
members of both classes. {}

Note:
where friend is a keyword used as a function
modifier. A friend declaration is valid only
03 within or outside the class definition.
Friend Function
Syntax: Case 2:
class second;forward declaration
class first class sample
{ {
private: private:
-------------- int x;
public: float y;
friend return_type fname(first one, public:
second two); virtual void display();
}; virtual static int sum(); //error
class second }
{ int sample::sum()
private: {}
------------------
public:
friend return_type fname(first one,
second two);
};
Friend Function Example
class sample
{
private:
int x;
public:
void getdata();
friend void display(sample abc);
};
void sample::getdata()
{
cout<<"Enter a value for x\n"<<endl;
cin>>x;
}
void display(sample abc)
{
cout<<"Entered Number is "<<abc.x<<endl;
}

void main()
{
Friend Function Example
class first Example:
{
friend class second;
private:
int x;
public:
void getdata();
};

class second
{
public:
void disp(first temp);
};

void first::getdata()
{
cout<<"Enter a Number ?"<<endl;
cin>>x;
}
Friend Function Example
class second;//Forward Declaration
class first
{
private:
int x;
public:
void getdata();
void display();
friend int sum(first one,second two);
};
class second
{
private:
int y;
public:
void getdata();
void display();
friend int sum(first one,second two);
};
void first::getdata()
Virtual function
• Virtual Function is a function in base class, which is
overridden in the derived class, and which tells the Syntax
compiler to perform Late Binding on this function.
01 virtual return_type function_name (arg);
• Virtual Keyword is used to make a member function of
the base class Virtual. Virtual functions allow the most Example
specific version of a member function in an inheritance virtual void show()
hierarchy to be selected for execution. Virtual 02 {
functions make polymorphism possible. cout << "Base class\n";
Key: }
• Only the Base class Method's declaration needs the Note:
Virtual Keyword, not the definition.
We can call private function of derived class
• If a function is declared as virtual in the base class, it from the base class pointer with the help of
will be virtual in all its derived classes. 03 virtual keyword. Compiler checks for access
specifier only at compile time. So at run time
when late binding occurs it does not check
whether we are calling the private function or
public function.
Virtual function features
Case 1: Case 2:

class sample class sample


{ {
private: private:
int x; int x;
float y; float y;
public: public:
virtual void display(); virtual void display();
virtual int sum(); virtual static int sum(); //error
} }
virtual void sample::display() //Error int sample::sum()
{} {}
Virtual function features
Case 3: Case 4:

class sample class sample


{ {
private: private:
int x; int x;
float y; float y;
public: public:
virtual sample(int x,float y); virtual ~sample(int x,float y);
//constructor //invalid
void display(); void display();
int sum(); int sum();
} }
Virtual function features
Case 5: Case 6:

class sample_1 virtual void display() //Error, non member


{ function
private: {
int x; ----------------
float y; ----------------
public: }
virtual int sum(int x,float y); //error
};
class sample_2:public sample_1
{
private:
int z;
public:
virtual float sum(int xx,float yy);
};
(Pure) Virtual Function Example
class Point
{
protected:
float length,breath,side,radius,area,height;
};
class Shape: public Point
{
public:
virtual void getdata()=0;
virtual void display()=0;
};
class Rectangle:public Shape
{
public:
void getdata()
{
cout<<"Enter the Breadth Value:"<<endl;
cin>>breath;
cout<<"Enter the Length Value:"<<endl;
cin>>length;
}
void display()
{
area = length * breath;
cout<<"The Area of the Rectangle is:"<<area<<endl;
}
};

class Square:public Shape


{
public:
void getdata()
{
Difference in invocation for virtual and non virtual function
class Base
{ public:
void show()
{
cout << "Base Class";
}
};
class Derived:public Base
{ public:
void show()
{
cout << "Derived Class";
}
};
int main()
{
Base *b; //Base class pointer
Derived d; //Derived class object
b = &d;
b->show(); //Early Binding Occurs
}
Output: Base Class

class Base
{ public:
virtual void show()
Difference in invocation for virtual and non virtual function
Difference in invocation for virtual and non virtual function
#include<iostream>
using namespace std;
class Base {
public:
void foo()
{
std::cout << "Base::foo\n";
}
virtual void bar()
{
std::cout << "Base::bar\n";
}
};

class Derived : public Base {


public:
void foo()
{
std::cout << "Derived::foo\n";
}
void bar()
{
std::cout << "Derived::bar\n";
Override
#include <iostream>
using namespace std;

class Base {
public:

// user wants to override this in the derived class


virtual void func()
{
cout << "I am in base" << endl;
}
};

class derived : public Base {


public:

// did a mistake by putting an argument "int a"

void func(int a) override


{
cout << "I am in derived class" << endl;
}
};
Pure Virtual function
• Pure virtual Functions are virtual functions with no
definition. They start with virtual keyword and ends with Syntax
= 0. Here is the syntax for a pure virtual function.
01 virtual void f() = 0;
• Pure Virtual functions can be given a small definition in Example
the Abstract class, which you want all the derived classes class Base
to have. Still you cannot create object of Abstract class. {
• Also, the Pure Virtual function must be defined outside 02 public:
the class definition. If you will define it inside the class virtual void show() = 0;
definition, complier will give an error. Inline pure virtual // Pure Virtual Function
definition is Illegal. };
Note:
• Abstract Class is a class which contains atleast one Pure
We can call private function of derived class
Virtual function in it. Abstract classes are used to provide
from the base class pointer with the help of
an Interface for its sub classes. Classes inheriting an
Abstract Class must provide definition to the pure virtual 03 virtual keyword. Compiler checks for access
specifier only at compile time. So at run time
function, otherwise they will also become abstract class. when late binding occurs it does not check
whether we are calling the private function or
public function.
Pure Virtual function
class pet
{
private:
char name[5];
public:
virtual void getdata()=0;
virtual void display()=0;
};
class fish:public pet
{
private:
char environment[10];
char food[10];
public:
void getdata();
void display();
};
class dog: public pet
{
private:
char environment[10];
char food[10];
public:
void getdata();
Pure Virtual function
void dog::getdata()
{
cout<<"Enter the Dog Environment required"<<endl;
cin>>environment;
cout<<"Enter the Dog Food require"<<endl;
cin>>food;
}
void dog::display()
{
cout<<"Dog Environment="<<environment<<endl;
cout<<"Dog Food="<<food<<endl;
cout<<"---------------------------------------"<<endl;
}
void main()
{
pet *ptr;
fish f;
ptr=&f;
ptr->getdata();
ptr->display();
dog d;
ptr=&d;
ptr->getdata();
Abstract Class
• Abstract class cannot be instantiated, but pointers and references of Abstract class type
can be created.
• Abstract class can have normal functions and variables along with a pure virtual function.
• Abstract classes are mainly used for Upcasting, so that its derived classes can use its
interface.
• Classes inheriting an Abstract Class must implement all pure virtual functions, or else
they will become Abstract too.
Pure virtual function

//Abstract base class


class Base
{
public:
virtual void show() = 0; // Pure Virtual Function
};

class Derived:public Base


{
public:
void show()
{
cout << "Implementation of Virtual Function in Derived class\n";
}
};

int main()
{
Abstract Class
Abstract Class
• Abstract Class is a class which contains at least one Pure Virtual function(abstract method) in it.
• Abstract classes are used to provide an Interface for its sub classes.

Characteristics of Abstract Class


1. Abstract class cannot be instantiated, but pointers and references of Abstract class type can
be created.
2. Abstract class can have normal functions and variables along with a pure virtual function.
3. Abstract classes are mainly used for Upcasting, so that its derived classes can use its
interface.
4. Classes inheriting an Abstract Class must implement all pure virtual functions, or else
they will become Abstract too.
Abstract Class
Pure Virtual Functions
• Pure virtual Functions are virtual functions with no definition. They
start with virtual keyword and ends with = 0. Here is the syntax for a
pure virtual function,
virtual void funname() = 0;
Example 1
class Base //Abstract base class int main()
{ {
public: Base obj; //Compile Time Error
virtual void show() = 0; //Pure Virtual Function Base *b;
}; Derived d;
class Derived:public Base b = &d;
{ b->show();
public: }
void show()
{
cout <<“Implementation of Virtual Function in
Derived class”; Output : Implementation of Virtual Function in Derived class
}
}; In the above example Base class is abstract, with pure virtual
show() function, hence we cannot create object of base class.
Example2 int main() {
Square square;
// C++ program to calculate the area of a Circle circle;
square and a circle // Derived class
class Square : public Shape { cout << "Enter the length of the square: ";
#include <iostream> square.getDimension();
public:
using namespace std; float calculateArea() { cout << "Area of square: " <<
// Abstract class return dimension * dimension; square.calculateArea() << endl;
} cout << "\nEnter radius of the circle: ";
class Shape { circle.getDimension();
};
protected: // Derived class cout << "Area of circle: " <<
float dimension; class Circle : public Shape { circle.calculateArea() << endl;
public: return 0;
public: }
float calculateArea() {
void getDimension() { return 3.14 * dimension *
cin >> dimension; dimension;
} }
};
// pure virtual Function
Output
virtual float calculateArea() = Enter the length of the square: 4
0;
Area of square: 16
}; Enter radius of the circle: 5
Area of circle: 78.5
What will be the output of the following
program?
#include <iostream>
#include <string>
using namespace std;
class Exam
{
int a;
public:
virtual void score() = 0;
};
class FirstSemExam: public Exam
a) Class B
{
public:
b) Error
void score(){ c) Segmentation fault
cout<<“First Semester Exam"<<endl; d) No output
}
};
int main(int argc, char const *argv[])
For abstract class Exam object cannot be instantiated
{
Exam e;
e.score();
return 0;
}
Quiz

1. Which class supports run-time polymorphism?


a. Base class b. abstract class c. derived class d. subclass

2. Identify the syntax for pure virtual function

a. void area();

b. void area()=0;

c. void area()=1;

d. pure void area();

3. Can we create object for abstract class? State Yes/No.


No
4. Identify the incorrect statement with respect to abstract class

a. all functions must be pure virtual function

b. Incomplete type

c. foundation for derived class

d. supports run-time polymorphism

5. If there is an abstract method in a class then, ________________

a. Class may or may not be abstract class

b. Class is generic

c. Class must be abstract class

d. Class must be public


Practice Questions
1.Given an abstract base class Car with member variables and functions:
String name;
• //abstract methods
Price()
Discount()
totalseats()
You have to write a class Tata which extends the class Car and uses the member functions and variables to implement price, discount of 20%
and total seats.
2. Create an abstract class 'Bank' with an abstract method 'getBalance'. $100, $150 and $200 are deposited in banks A, B and C respectively.
'BankA', 'BankB' and 'BankC' are subclasses of class 'Bank', each having a method named 'getBalance'. Call this method by creating an object
of each of the three classes.
Interface
• An interface describes the behavior or capabilities of a C++ class
without committing to a particular implementation of that class.
• The C++ interfaces are implemented using abstract classes and these
abstract classes should not be confused with data abstraction which
is a concept of keeping implementation details separate from
associated data.
• A class is made abstract by declaring at least one of its functions
as pure virtual function.
• A pure virtual function is specified by placing "= 0" in its declaration
• Every method declared by an object specifies the method’s name, the
object/value it takes as parameters, and the method’s return value. this is
known as the operation Signature
• The set of all signatures defined by an object’s methods is called the
interface to the object .An object’s interface characterizes the complete
set of requests that can be sent to the object.
• An interface is like an abstract class that cannot be instantiated,
• Interface are better suited to situations in which your applications require
many possibly unrelated object types to provide certain functionality
• Explicitly implementing interface in a class enables us to define a set of
methods that are mandatory for that class.
Ex: Bank application (create account,deposit, withdraw)
Interface Example
• Fountain pen and ball point
pen are used for writing, they
are related entities. What
should be the abstract class for
these entities ?

• We can Write using pen but


we can also write with
charcoal. Over here what is
the common behaviour
between pen and charcoal
that can be abstracted?
class Box {
public:
// pure virtual function
virtual double getVolume() = 0;

private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
When to use Interface?
• Use an interface when an immutable contract is really intended .
• Interfaces are better suited in situations when your applications
require many possibly unrelated object types to provide certain
functionality.
• Interfaces are better in situations in which you do not need to inherit
implementation from a base class.
• Interfaces can be used for multiple inheritance.
Difference between abstract class and interface
Difference between abstract class
and interface
What is similar to interface in c++
A. methods
B. instance of class
C. pure abstract class
D. friend function
Which of the following is used to
implement the c++ interfaces?
• A. absolute variables
• B. abstract classes
• C. Constant variables
• D. default variables
18CSC202J- Object Oriented
Design and Programming

Unit III

UML Start Chart Diagram

10/7/2022 Sequence Diagram 99


Agenda :
1) To understand about behavioral diagram
2) To draw state chart diagram using Star UML .

10/7/2022 Sequence Diagram 100


Introduction
• To model dynamic aspect of a system.
• To model life time of a reactive system.
• To describe different states of an object during its life
time.
• Define a state machine to model states of an object.

10/7/2022 Sequence Diagram 101


State Diagram
• A state diagram is used to represent the condition of
the system or part of the system at finite instances of
time.
• It’s a behavioral diagram and it represents the
behavior using finite state transitions.
• State diagrams are also referred to as State
machines and state-chart Diagrams.

10/7/2022 Sequence Diagram 102


Difference between state chart and flowchart

• The basic purpose of a state diagram is to


portray various changes in state of the class
and not the processes or commands causing
the changes.

• However, a flowchart on the other hand


portrays the processes or commands that on
execution change the state of class or an
object of the class.

10/7/2022 Sequence Diagram 103


When to use State charts

So the main usages can be described as:


• To model object states of a system.
• To model reactive system. Reactive system consists of reactive
objects.
• To identify events responsible for state changes.
• Forward and reverse engineering.

10/7/2022 Sequence Diagram 104


• Before drawing a State chart diagram we must have clarified the
following points:
• Identify important objects to be analyzed.
• Identify the states.
• Identify the events.

10/7/2022 Sequence Diagram 105


Elements of Start Chart Diagram
▪ Initial State: This shows the starting point of the state chart diagram that is
where the activity starts.
▪ State: A state represents a condition of a modelled entity for which some
action is performed. The state is indicated by using a rectangle with
rounded corners and contains compartments.
▪ Composite state – We use a rounded rectangle to represent a composite
state also. We represent a state with internal activities using a composite
state.
▪ Transition: It is indicated by an arrow. Transition is a relationship between
two states which indicates that Event/ Action an object in the first state will
enter the second state and performs certain specified actions.
▪ Self transition – We use a solid arrow pointing back to the state itself to
represent a self transition. There might be scenarios when the state of the
object does not change upon the occurrence of an event. We use self
transitions to represent such cases.
• Final State-The end of the state chart diagram is represented by a solid
circle surrounded by a circle.
10/7/2022 Sequence Diagram 106
Symbols used in start chart diagram

10/7/2022 Sequence Diagram 107


Example – State Chart Diagram

10/7/2022 Sequence Diagram 108


Questions
1. Which of the statements state the name compartment?
a) The first compartment is the name compartment
b) It contains the state name; State names are optional and may be path names
c) The name compartment can never be omitted
d) State name compartment is the first compartment that contains state name, name
compartment may be omitted.

2. Start Chart diagram comes under the phase of


a) Analysis and Design
b) Design and Implementation
c) Testing and Deployment
d) Implementation and Testing

10/7/2022 Sequence Diagram 109


Activity diagram
Activity diagram
• Activity diagram is UML behavior diagram which
emphasis on the sequence and conditions of the flow
• It shows a sequence of actions or flow of control in a
system.
• It is like to a flowchart or a flow diagram.
• It is frequently used in business process modeling.
They can also describe the steps in a use case diagram.
• The modeled Activities are either sequential or
concurrent.
Benefits
• It illustrates the logic of an algorithm.
• It describes the functions performed in use cases.
• Illustrate a business process or workflow between
users and the system.
• It Simplifies and improves any process by descriptive
complex use cases.
• Model software architecture elements, such as method,
function, and operation.
Symbols and Notations
Activity
• Is used to illustrate a set of actions.
• It shows the non-interruptible action of objects.
Symbols and Notations
Action Flow
• It is also called edges and paths
• It shows switching from one action state to another.
It is represented as an arrowed line.
Symbols and Notations
Object Flow
• Object flow denotes the making and modification of
objects by activities.
• An object flow arrow from an action to an object
means that the action creates or influences the
object.
• An object flow arrow from an object to an action
indicates that the action state uses the object.
Symbols and Notations

Decisions and Branching


• A diamond represents a decision with alternate paths.
• When an activity requires a decision prior to moving on
to the next activity, add a diamond between the two
activities.
• The outgoing alternates should be labeled with a
condition or guard expression. You can also label one of
the paths "else."
Symbols and Notations
Decisions and Branching
• A diamond represents a decision with alternate paths.
• When an activity requires a decision prior to moving on
to the next activity, add a diamond between the two
activities.
• The outgoing alternates should be labeled with a
condition or guard expression. You can also label one of
the paths "else."
Symbols and Notations
Guards
• In UML, guards are a statement written next to a
decision diamond that must be true before moving
next to the next activity.
• These are not essential, but are useful when a
specific answer, such as "Yes, three labels are
printed," is needed before moving forward.
Symbols and Notations
Synchronization
• A fork node is used to split a single incoming flow into
multiple concurrent flows. It is represented as a straight,
slightly thicker line in an activity diagram.
• A join node joins multiple concurrent flows back into a
single outgoing flow.
• A fork and join mode used together are often referred to
as synchronization.
Symbols and Notations
Synchronization
Symbols and Notations
Time Event
• This refers to an event that stops the flow for a time;
an hourglass depicts it.
Symbols and Notations
Merge Event
• A merge event brings together multiple flows that are not
concurrent.

Final State or End Point


• An arrow pointing to a filled circle nested inside another
circle represents the final action state.
Symbols and Notations
Swimlane and Partition
• A way to group activities performed by the same
actor on an activity diagram or to group activities in
a single thread
Activity diagram
Activity Diagram with Swimlane
Activity Diagram with Swimlane
Practice Questions- MCQ
Which of the following Combines two concurrent activities and
re-introduces them to a flow where only one activity can be
performed at a time?
A. Joint symbol
B. Fork symbol
C. Decision symbol
D. Note symbol

Ans: A
Practice Questions- MCQ

In an Activity Diagram, organizing the activities into


groups is called ________
A. forking
B. joining
C. swimlane
D. synchronization

Ans: C
Practice questions
1. Identify all of the activities in this diagram.

2. Identify all of the object/data nodes in this diagram.

3. Identify all of the actions in this diagram.

4. Identify all of the decision nodes in this diagram.

5. Identify all of the fork nodes in this diagram.

6. Identify all of the join nodes in this diagram.

7. Identify a control flow in this diagram.

8. Identify a data flow in this diagram.

9. Can "Pick Order" and "Create Invoice" occur at the


same time?

10. Can "Record Order" and "Ship" occur at the same


time?
Thank you
Abstract Class
• Abstract class cannot be instantiated, but pointers and references of Abstract class type
can be created.
• Abstract class can have normal functions and variables along with a pure virtual function.
• Abstract classes are mainly used for Upcasting, so that its derived classes can use its
interface.
• Classes inheriting an Abstract Class must implement all pure virtual functions, or else they
will become Abstract too.
Pure virtual function
/Abstract base class Example:
class Base
{
public:
virtual void show() = 0; // Pure Virtual Function
};

class Derived:public Base


{
public:
void show()
{
cout << "Implementation of Virtual Function in Derived class\n";
}
};

int main()
State chart diagram
18CS202J OBJECT ORIENTED DESIGN AND PROGRAMMING

07-10-2022 Prepared by NWC Department 133


State diagram
• A state diagram is used to represent the condition of the system or
part of the system at finite instances of time. It’s
a behavioural diagram and it represents the behaviour using finite
state transitions. State diagrams are also referred to as State
machines and State-chart Diagrams.

07-10-2022 Prepared by NWC Department 134


Uses of state chart diagram
• State chart diagrams are useful to model reactive systems
-Reactive systems can be defined as a system that responds to external or internal events.
• State chart diagram describes the flow of control from one state to
another state.

07-10-2022 Prepared by NWC Department 135


Purpose
Following are the main purposes of using State chart diagrams:
To model dynamic aspect of a system.
To model life time of a reactive system.
To describe different states of an object during its life time.
Define a state machine to model states of an object.

07-10-2022 Prepared by NWC Department 136


Difference between state diagram and
flowchart
The basic purpose of a state diagram is to portray various changes in state of the
class and not the processes or commands causing the changes.

However, a flowchart on the other hand portrays the processes or commands that
on execution change the state of class or an object of the class.

07-10-2022 Prepared by NWC Department 137


When to use State charts
So the main usages can be described as:
To model object states of a system.
To model reactive system. Reactive system consists of reactive
objects.
To identify events responsible for state changes.
Forward and reverse engineering.

07-10-2022 Prepared by NWC Department 138


How to draw state charts
Before drawing a State chart diagram we must have clarified the following points:
✔ Identify important objects to be analysed.
✔ Identify the states.
✔ Identify the events.

07-10-2022 Prepared by NWC Department 139


Elements of state chart diagrams

• Initial State: This shows the starting point of the state chart diagram that is where
the activity starts.

07-10-2022 Prepared by NWC Department 140


Elements of state chart diagrams
• State: A state represents a condition of a modelled entity for which some action is
performed. The state is indicated by using a rectangle with rounded corners and
contains compartments

07-10-2022 Prepared by NWC Department 141


Elements of state chart diagrams
• Composite state – We use a rounded rectangle to represent a
composite state also. We represent a state with internal activities
using a composite state.

07-10-2022 Prepared by NWC Department 142


Elements of state chart diagrams
• Fork – We use a rounded solid rectangular bar to represent a Fork notation with
incoming arrow from the parent state and outgoing arrows towards the newly
created states. We use the fork notation to represent a state splitting into two or
more concurrent states.

07-10-2022 Prepared by NWC Department 143


Elements of state chart diagrams
• Join – We use a rounded solid rectangular bar to represent a Join notation with
incoming arrows from the joining states and outgoing arrow towards the common
goal state. We use the join notation when two or more states concurrently
converge into one on the occurrence of an event or events.

07-10-2022 Prepared by NWC Department 144


Elements of state chart diagrams
• Transition: It is indicated by an arrow. Transition is a relationship between two
states which indicates that Event/ Action an object in the first state will enter the
second state and performs certain specified actions.

07-10-2022 Prepared by NWC Department 145


Elements of state chart diagrams
• Transition – We use a solid arrow to represent the transition or change of control
from one state to another. The arrow is labelled with the event which causes the
change in state.

07-10-2022 Prepared by NWC Department 146


Elements of state chart diagrams
• Self transition – We use a solid arrow pointing back to the state itself to represent
a self transition. There might be scenarios when the state of the object does not
change upon the occurrence of an event. We use self transitions to represent such
cases.

07-10-2022 Prepared by NWC Department 147


Elements of state chart diagrams

• Final State: The end of the state chart diagram is represented by a solid circle
surrounded by a circle.

07-10-2022 Prepared by NWC Department 148


Example state chart for ATM card PIN Verification

07-10-2022 Prepared by NWC Department 149


Example state chart for order management system

07-10-2022 Prepared by NWC Department 150


Prepared by NWC Department 151

ACTIVITY DIAGRAM

18CSC202J
07-10-2022 Object Oriented Design and Programming
Activity Diagram
❑ Activity diagram is UML behavior diagram which emphasis on the
sequence and conditions of the flow
❑ It shows a sequence of actions or flow of control in a system.
❑ It is like to a flowchart or a flow diagram.
❑ It is frequently used in business process modeling. They can also describe
the steps in a use case diagram.
❑ The modeled Activities are either sequential or concurrent.

07-10-2022 Prepared by NWC Department 152


Benefits
◻ It illustrates the logic of an algorithm.
◻ It describes the functions performed in use cases.
◻ Illustrate a business process or workflow between users and the system.
◻ It Simplifies and improves any process by descriptive complex use cases.
◻ Model software architecture elements, such as method, function, and
operation.

07-10-2022 Prepared by NWC Department 153


Symbols and Notations
Activity
◻ Is used to illustrate a set of actions.
◻ It shows the non-interruptible action of objects.

07-10-2022 Prepared by NWC Department 154


Symbols and Notations
Action Flow
◻ It is also called edges and paths
◻ It shows switching from one action state to another. It is represented as an
arrowed line.

07-10-2022 Prepared by NWC Department 155


Symbols and Notations
Object Flow
◻ Object flow denotes the making and modification of objects by activities.
◻ An object flow arrow from an action to an object means that the action
creates or influences the object.
◻ An object flow arrow from an object to an action indicates that the action
state uses the object.

07-10-2022 Prepared by NWC Department 156


Symbols and Notations
Decisions and Branching
◻ A diamond represents a decision with alternate paths.
◻ When an activity requires a decision prior to moving on to the next
activity, add a diamond between the two activities.
◻ The outgoing alternates should be labeled with a condition or guard
expression. You can also label one of the paths "else."

07-10-2022 Prepared by NWC Department 157


Symbols and Notations
Guards
◻ In UML, guards are a statement written next to a decision diamond that
must be true before moving next to the next activity.
◻ These are not essential, but are useful when a specific answer, such as
"Yes, three labels are printed," is needed before moving forward.

07-10-2022 Prepared by NWC Department 158


Symbols and Notations
Synchronization
◻ A fork node is used to split a single incoming flow into multiple
concurrent flows. It is represented as a straight, slightly thicker line in an
activity diagram.
◻ A join node joins multiple concurrent flows back into a single outgoing
flow.
◻ A fork and join mode used together are often referred to as
synchronization.

07-10-2022 Prepared by NWC Department 159


Symbols and Notations
Synchronization

07-10-2022 Prepared by NWC Department 160


Symbols and Notations
Time Event
◻ This refers to an event that stops the flow for a time; an hourglass depicts
it.

07-10-2022 Prepared by NWC Department 161


Symbols and Notations
Merge Event
◻ A merge event brings together multiple flows that are not concurrent.

Final State or End Point


◻ An arrow pointing to a filled circle nested inside another circle represents
the final action state.

07-10-2022 Prepared by NWC Department 162


Symbols and Notations
Swimlane and Partition
◻ A way to group activities performed by the same actor on an activity
diagram or to group activities in a single thread

07-10-2022 Prepared by NWC Department 163


Activity Diagram

07-10-2022 Prepared by NWC Department 164


Activity Diagram with Swimlane

07-10-2022 Prepared by NWC Department 165


Activity Diagram without Swimlane

07-10-2022 Prepared by NWC Department 166


Prepared by NWC Department 167

State Chart and Activity Diagram


Scenarios

07-10-2022
Prepared by NWC Department 168

07-10-2022
07-10-2022 Prepared by NWC Department 169
07-10-2022 Prepared by NWC Department 170
07-10-2022 Prepared by NWC Department 171
State Chart Diagram

07-10-2022 Prepared by NWC Department 172


07-10-2022 Prepared by NWC Department 173
07-10-2022 Prepared by NWC Department 174
07-10-2022 Prepared by NWC Department 175
07-10-2022 Prepared by NWC Department 176
07-10-2022 Prepared by NWC Department 177
07-10-2022 Prepared by NWC Department 178
18CSC202J - OBJECT ORIENTED
DESIGN AND PROGRAMMING

Session 1

Topic :Generic - Templates :


Introduction
Templates-Introduction
• Allows functions and classes to operate with generic
types.
• Allows a function or class to work on many
different data types without being rewritten for each
one.
• Great utility when combined with multiple inheritance
and operator overloading
• The C++ Standard Library is based upon conventions
introduced by the Standard Template Library (STL)
Types of Templates
• Function Template
A function template behaves like a function
except that the template can have arguments of many
different types
• Class Template
A class template provides a specification for
generating classes based on parameters.
Class templates are generally used to
implement containers.
Function Template
• A function templates work in similar manner as function but with
one key difference.
• A single function template can work on different types at once
but, different functions are needed to perform identical task on
different data types.
• If you need to perform identical operations on two or more types
of data then, you can use function overloading. But better
approach would be to use function templates because you can
perform this task by writing less code and code is easier to
maintain.
Cont.
• A generic function that represents several functions performing
same task but on different data types is called function
template.
• For example, a function to add two integer and float numbers
requires two functions. One function accept integer types and
the other accept float types as parameters even though the
functionality is the same. Using a function template, a single
function can be used to perform both additions.
• It avoids unnecessary repetition of code for doing same task on
various data types.
Cont.
Why Function Templates?
• Templates are instantiated at compile-time with the
source code.
• Templates are used less code than overloaded C++
functions.
• Templates are type safe.
• Templates allow user-defined specialization.
• Templates allow non-type parameters.
Function Template
• A function template starts with keyword template
followed by template parameter/s inside <> which is
followed by function declaration.
• T is a template argument and class is a keyword.
• We can also use keyword typename instead of class.
• When, an argument is passed to some_function( ),
compiler generates new version of some_function()
to work on argument of that type.
Template Syntax
template <class T>
T some_function(T argument)
{
.... ... ....
}

The template type keyword specified can be either "class" or "


typename":
template<class T>
or
template<typename T>
Both are valid and behave exactly the same.
18CSC202J - OBJECT ORIENTED
DESIGN AND PROGRAMMING

Session 2

Topic :Example Program Function


Template, Class Template
Example program Function Templates
#include<iostream.h>
template <typename T>
T Sum(T n1, T n2) // Template function
{
T rs;
rs = n1 + n2;
return rs;
}
int main()
{
int A=10,B=20,C;
long I=11,J=22,K;
C = Sum(A,B);
cout<<"nThe sum of integer values : "<<C;
K = Sum(I,J);
cout<<"nThe sum of long values : "<<K;
}
More than One Template Argument
template<class T , class U>
void multiply(T a , U b)
{
cout<<"Multiplication= "<<a*b<<endl;
}
int main()
{
int a, b;
float x, y;
cin>>a>>b;
cin>>x>>y;
multiply(a,b); // Multiply two integer type data
multiply(x,y); // Multiply two float type data
multiply(a,x); // Multiply a float and integer type data
return 0;
}
Class Template
• Like function template, a class template is a
common class that can represent various similar
classes operating on data of different types.

• Once a class template is defined, we can create an


object of that class using a specific basic or
user-defined data types to replace the generic data
types used during class definition.
Syntax for Class Template
template <class T1, class T2, ...>
class classname
{
attributes;
methods;
};
Example Program
#include <iostream.h>
using namespace std;
const int MAX = 100; //size of array
template <class Type>
class Stack
{
private:
Type st[MAX]; //stack: array of any type
int top; //number of top of stack
public:
Stack() //constructor
{ top = -1; }
void push(Type var) //put number on stack
{ st[++top] = var; }
Type pop() //take number off stack
{ return st[top--]; }
};
Cont.
int main()
{
Stack<float> s1; //s1 is object of class Stack<float>
s1.push(1111.1F); //push 3 floats, pop 3 floats
s1.push(2222.2F);
s1.push(3333.3F);
cout << “1: “ << s1.pop() << endl;
cout << “2: “ << s1.pop() << endl;
cout << “3: “ << s1.pop() << endl;

Stack<long> s2; //s2 is object of class Stack<long>


s2.push(123123123L); //push 3 longs, pop 3 longs
s2.push(234234234L);
s2.push(345345345L);
cout << “1: “ << s2.pop() << endl;
cout << “2: “ << s2.pop() << endl;
cout << “3: “ << s2.pop() << endl;
return 0;
}
18CSC202J - OBJECT ORIENTED
DESIGN AND PROGRAMMING

Session 3

Topic :Class Template, Example


Program for Class and Function
Template
Class Templates with Multiple parameter
• We can use more than one generic data type in a
class template.
• Syntax:
template<class T1, class T2>
class classname
{
……
……
};
Example Program
int main()
template<class T1, classT2>
{
class Test
{ test<float, int> test1(1.23, 123);
T1 a; test<int, char> test2(100,’w’);
T2 b; test1.show();
} test2.show();
void show() return 0;
{ }
cout<<a;
Output:
cout<<b;
1.23
}
123
}; 100
w
Class Template Object
To create a class template object, you need to define the data
type inside a < > when creation.

Syntax:
className<dataType> classObject;

Example:
className<int> classObject;
className<float> classObject;
className<string> classObject;
Program
1. Program to display largest among two numbers
using function templates.
2. Program to swap data using function templates.
3. Program to add, subtract, multiply and divide two
numbers using class template.
Solution:1
#include <iostream> cout << "Enter two integers:\n";
cin >> i1 >> i2;
using namespace std;
cout << Large(i1, i2) <<" is larger." << endl;
template <class T> cout << "\nEnter two floating-point numbers:\n";
T Large(T n1, T n2) cin >> f1 >> f2;
{ cout << Large(f1, f2) <<" is larger." << endl;
return (n1 > n2) ? n1 : n2; cout << "\nEnter two characters:\n";
} cin >> c1 >> c2;
cout << Large(c1, c2) << " has larger ASCII value.";
int main() return 0;
{ }
int i1, i2;
float f1, f2;
char c1, c2;
Output
Enter two integers:
5
10
10 is larger.
Enter two floating-point numbers:
12.4
10.2
12.4 is larger.
Enter two characters:
z
Z
z has larger ASCII value.
Solution: 2
#include <iostream> cout << "\nf1 = " << f1 << "\nf2 = " << f2;
using namespace std; cout << "\nc1 = " << c1 << "\nc2 = " << c2;
template <typename T> Swap(i1, i2);
void Swap(T &n1, T &n2) Swap(f1, f2);
{ Swap(c1, c2);
T temp; cout << "\nAfter passing data to function template.\n";
temp = n1; cout << "i1 = " << i1 << "\ni2 = " << i2;
n1 = n2; cout << "\nf1 = " << f1 << "\nf2 = " << f2;
n2 = temp; cout << "\nc1 = " << c1 << "\nc2 = " << c2;
} return 0;
int main() }
{
int i1 = 1, i2 = 2;
float f1 = 1.1, f2 = 2.2;
char c1 = 'a', c2 = 'b';
cout << "Before passing data to function template.\n";
cout << "i1 = " << i1 << "\ni2 = " << i2;
Output
Before passing data to function template.
i1 = 1
i2 = 2
f1 = 1.1
f2 = 2.2
c1 = a
c2 = b

After passing data to function template.


i1 = 2
i2 = 1
f1 = 2.2
f2 = 1.1
c1 = b
c2 = a
T subtract()
Solution: 3 {
#include <iostream> return num1 - num2;
using namespace std; }
template <class T> T multiply()
class Calculator {
{ return num1 * num2;
private: T num1, num2; }
public: Calculator(T n1, T n2) T divide()
{ {
num1 = n1;
return num1 / num2;
num2 = n2;
}
}
void displayResult() };
{ int main()
cout << "Numbers are: " << num1 << " and " << num2 << "." ; {
cout << "Addition is: " << add() << endl; Calculator<int> intCalc(2, 1);
cout << "Subtraction is: " << subtract() << endl; Calculator<float> floatCalc(2.4, 1.2);
cout << "Product is: " << multiply() << endl; cout << "Int results:" << endl;
cout << "Division is: " << divide() << endl; intCalc.displayResult();
} cout << endl << "Float results:" << endl;
T add() floatCalc.displayResult();
{ return 0;
return num1 + num2;
}
Output
Int results:
Numbers are: 2 and 1.
Addition is: 3
Subtraction is: 1
Product is: 2
Division is: 2

Float results:
Numbers are: 2.4 and 1.2.
Addition is: 3.6
Subtraction is: 1.2
Product is: 2.88
Division is: 2
18CSC202J - OBJECT ORIENTED
DESIGN AND PROGRAMMING

Session 6

Topic :Exceptional Handling: try and


catch, multilevel exceptional
Introduction
• It is normal to commit mistakes in programming that
prompts unusual conditions called errors. These errors
are classified as:
• Syntax Errors - Errors that occur when you violate the
rules of writing C++ syntax, e.g, missing paranthesis
• Logical Errors - These errors solely depend on the
logical thinking of the programmers.
• Runtime Errors - Errors which occur during program
execution(run-time) after successful compilation are
called run-time errors, e.g, division by zero
• Semantic errors - Errors due to an improper use of
program statements
Introduction
• The errors that occur at run-time are known as
exceptions.
• They occur due to different conditions such as division
by zero, accessing an element out of bounds of an
array, unable to open a file, running out of memory and
so on
• Exception Handling in C++ is defined as a method that
takes care of a surprising condition like runtime errors.
• At whatever point a sudden situation happens, there is
a movement of the program control to a unique
function known as Handlers.
Exceptions

• Indicate problems that occur during a program’s


execution
• Occur infrequently
• Exceptions provide a way to transfer control from one
part of a program to another.
• A C++ exception is a response to an exceptional
circumstance that arises while a program is running,
such as an attempt to divide by zero.
Exception Handling

• Can resolve exceptions


• Allow a program to continue executing or
• Notify the user of the problem and
• Terminate the program in a controlled manner
• Makes programs robust and fault-tolerant
• Types
• Synchronous exception (out-of-range index,
overflow)
• Asynchronous exception (keyboard interrupts)
Types of Exception

Two types of exception:

Synchronous Exceptions
Asynchronous Exceptions
Synchronous Exceptions

• Occur during the program execution due to some fault in


the input data or technique that is not suitable to handle the
current class of data, within the program .

• For example:
• Errors such as out of range
• Overflow
• Underflow and so on
Asynchronous Exceptions

• Caused by events or faults unrelated (external) to the


program and beyond the control of the program.

• For example
• errors such as keyboard interrupts
• hardware malfunctions
• disk failure and so on

The exception handling mechanism of C++ is designed to


handle only synchronous exceptions within a program.
Exception levels

Exceptions can occur at many levels:


1. Hardware/operating system level.
• Arithmetic exceptions; divide by 0.
• Memory access violations; stack over/underflow.
2. Language level.
• Type conversion; illegal values, improper casts.
• Bounds violations; illegal array indices.
• Bad references; null pointers.
3. Program level.
• User defined exceptions.
Need of Exceptions

• Detect and report an “exceptional circumstance”


• Separation of error handling code from normal code
• That is, you will isolate your error handling code from
your ordinary code. The code will be more coherent
and simpler to keep up with.
• Functions/ Methods can handle any exception they
choose
• Grouping of Error types
Basic Keywords in Exception Handling

• Exception Handling in C++ falls around these three


keywords:
– Throw: when a program experiences an issue, it throws
an Exception. The throw keyword assists the program by
performing throw
– Catch: a program that utilises an exception handler to
catch an Exception. It is added to the part of a program
where you need to deal with the error
– Try: the try block recognises the code block for which
certain exceptions will be enacted. It ought to be
followed by one/more catch blocks
Exception Handling Mechanism

1. Find the problem (Hit the exception)


2. Inform that an error has occurred (Throw the
exception)
3. Receive the error information (Catch the exception)
4. Take corrective actions (Handle the exception)
C++ Standard Exceptions
C++ Standard Exceptions

Exception Description
std::exception An exception and parent class of all the
standard C++ exceptions.
std::bad_alloc This can be thrown by new.

std::bad_cast This can be thrown by dynamic_cast.

std::bad_exception This is useful device to handle unexpected


exceptions in a C++ program
std::bad_typeid This can be thrown by typeid.
C++ Standard Exceptions
Exception Description

std::logic_error An exception that theoretically can be detected by reading


the code.

std::domain_error This is an exception thrown when a mathematically


invalid domain is used

std::invalid_argument This is thrown due to invalid arguments.

std::length_error This is thrown when a too big std::string is created

std::out_of_range This can be thrown by the at method from for example a


std::vector and std::bitset<>::operator[]().
C++ Standard Exceptions

Exception Description
std::runtime_error An exception that theoretically can not be
detected by reading the code.

std::overflow_error This is thrown if a mathematical overflow


occurs.

std::range_error This is occured when you try to store a


value which is out of range.

std::underflow_error This is thrown if a mathematical underflow


occurs.
Exceptions : syntax
try {
// the protected code
} catch( Exception_Name exception1 ) {
// catch block
} catch( Exception_Name exception2 ) {
// catch block
} catch( Exception_Name exceptionN ) {
// catch block
}
• We have one try statement with many catch statement.
• The ‘ExceptionName’ is the name of the Exception for being
caught.
• The exception1, exception2, exception3 and exceptionN are
your defined names for referring to the exceptions.
Exceptions
Simple Exceptions : Example

#include<iostream> else
using namespace std; {
int main() throw(b);
{ }
int a,b; }
cin >> a>> b; catch(int i)
try {
{ cout <<“exception
if (b!=0) caught”;
{ }
cout<<“result (a/b)=”<<a/b; }
}
Nested try blocks

try
{ ……..
try
{
………
}
catch (type arg)
{
………
}
}
catch(type arg)
{ ……….
………..
}
Multiple Catch Exception
• Used when a user wants to handle different exceptions
differently.
• For this, a user must include catch statements with
different declaration.
Multiple Catch Exception

• It is possible to design a separate catch block for each


kind of exception
• Single catch statement that catches all kind of exceptions
• Syntax
catch(…)
{
…….
}
Note :
A better way to use this as a default statement along with
other catch statement so that it can catch all those exception
which are not handle by other catch statement
Multiple catch statement : Syntax
try {
……..
}
catch (type1 arg) {
………
}
catch (type2 arg) {
………
}
……..
catch(typeN arg) {
………..
}
Multiple Exceptions : Example
#include<iostream> catch(int i)
using namespace std; {
int main() {
int a,b;
cout <<“exception caught :
cin >> a>> b; Division by zero”;
try { }
if (b!=a) catch (char st)
{ {
float div = (float) a/b;
cout << “exception caught :
if(div <0)
throw ‘e’; Division is less than 1”;
cout<<div; }
} catch(…)
else {
throw b; cout << “Exception : unknown”;
}
catch(int i) }
{cout <<“exception caught”; }
}
Exceptions
throwing Exception
throwing Exception

• When an exception is detected, it is thrown using


throw statement in the try block
• It is also possible to have nested try-catch statement
• It cause the current exception to be thrown to the next
enclosing try/catch sequence and is caught by a catch
statement listed after that enclosing try block.
Re-throwing Exception
Throw Example

try
{
if(denominator == 0)
{
throw denominator;
}
result = numerator/denominator;
cout<<"\nThe result of division is:" <<result;
}
Handle Any Type of Exceptions (...)

• If you do not know the throw type used in


the try block, you can use the "three dots" syntax (...)
inside the catch block, which will handle any type of
exception.
Finally

• The application always executes any statements in the


finally part, even if an exception occurs in the try block.
• When any code in the try block raises an exception,
execution halts at that point.
• Once an exception handler is found, execution jumps to
the finally part.
• After the finally part executes, the exception handler is
called.
• If no exception occurs, the code in the finally block
executes in the normal order, after all the statements in
the try block.
Finally
Finally - Syntax

try
{
// statements that may raise an exception
}
__finally
{
// statements that are called even
//if there is an exception in the try block
}
Finally - Example

#include<iostream> Else {
using namespace std; throw(b);
int main() }
{ }
int a,b; catch(int i) {
cin >> a>> b; cout <<“exception caught”;
try{ }
if (b!=0) { __finally {
cout<<“result cout<<“Division”;
(a/b)=”<<a/b; }
} }
Exception Handling

Session 8

Topic : Exceptional Handling:


User defined exception
User Defined Exceptions

• We can define your own exceptions by inheriting and


overriding exception class functionality.
• User defined exception classes inherit exception class
provided by C++ and overrides it’s functionality
according to our needs.
• To use class exception, we must include exception
header using the pre-processor directive.
#include <exception>
Rules for User Defined Exceptions

• Always include exception header using pre-processor


directive at the very first step.
• The function which will return an exception string
should have a return type of char followed by *,
char* what()
{
// codes here
}
char is as return type because we will return a
string
• Should have a try and catch block.
User Defined Exceptions- Example
class MyCustomException : public std::exception {
public:
char * what () {
return "Custom C++ Exception";
}
};

int main() {
try {
throw MyCustomException();
} catch (MyCustomException mce) {
cout << "Caught MyCustomException" << endl;
cout << mce.what();
}
}
User Defined Exceptions

Example
• Let’s say that the password must consists of at least 6
characters.
• If we write a exception for this case, when the
program receives a password in length of 5 characters
it will throw an exception so that we could know the
password is not valid
User Defined Exceptions

Example
class BadLengthException : public exception {
public:
int N;
BadLengthException(N) {
this->N=N;
};
int what() {
return this->N;
}
}
User Defined Exceptions

• The BadLengthException inherited all properties from


the exception class.
• When this class is initialized, it takes the username
length and stores it in public variable N.
• When the catch block detected exception, it will dial
with the function what of our exception class to get
what is happened.
User Defined Exceptions

int main() {
int usernameLength;
cin>>usernameLength;
try {
if(usernameLength<5)
throw BadLengthException(usernameLength);
else
cout<<"Valid";
} catch(BadLengthException e) {
cout<<"Too short: "<<e.what();
}
return 0;
}
Passing Parameters to Custom Exceptions

• Custom exceptions can include parameters to


provide relevant information about the exception
and customize the error message. This can help
programmers to better handle the exception.
class MyCustomException : public std::exception {
private:
char * message;
public:
MyCustomException(char * msg) : message(msg) {}
char * what () {
return message; }
};
Passing Parameters to Custom Exceptions

int main() {
try {
throw MyCustomException("Custom C++
Exception");
} catch (MyCustomException mce) {
cout << "Caught MyCustomException" << endl;
cout << mce.what();
}
}
Output
Caught MyCustomException
Custom C++ Exception
Questions in Exceptions

What is the advantage of exception handling ?


1. Remove error-handling code from the software’s main line of
code.
2. A method writer can choose to handle certain exceptions and
delegate others to the caller.
3. An exception that occurs in a function can be handled anywhere in
the function call stack.
(A) Only 1
(B) 1, 2 and 3
(C) 1 and 3
(D) 1 and 2
Questions in Exceptions
Predict the output of the code?
class Base {};
class Derived: public Base {};
int main() {
Derived d;
try {
throw d;
} catch(Base b) {
cout<<"Caught Base Exception";
} catch(Derived d) {
cout<<"Caught Derived Exception";
}
return 0;
}
(A) Caught Derived Exception
(B) Caught Base Exception
(C) Compiler Error
(D) Run Time Error
Questions in Exceptions
Predict the output of the code? (A) default exception
int main() After Exception
{ (B) int exception
try After Exception
{ (C) int exception
throw 'a'; (D) default exception
}
catch (int param)
{
cout << "int exception\n";
}
catch (...)
{
cout << "default exception\n";
}
cout << "After Exception";
return 0;
}
Questions in Exceptions
Predict the output of the ((A) default exception
code? (B) int exception
(C) Compiler Error
int main()
(D) Run Time Error
{ try {
throw 10; Reason: The catch(…) must be the
} last catch block.
catch (...) {
cout << "default
exception\n";
}
catch (int param) {
cout << "int exception\n";
}
return 0;
}
Questions in Exceptions
Predict the output of the code? ((A) Outer Catch
int main() { (B) Inner Catch
(C) Inner Catch
try {
Outer Catch
try { (D) Compiler Error
throw 20;
} Reason: The statement ‘throw;’ is
catch (int n) { used to re-throw an exception.
cout << "Inner Catch\n";
throw; }
}
catch (int x){
cout << "Outer Catch\n";
}
return 0;
}
Questions in Exceptions
Which of the following is true about exception handling in
C++?
1) There is a standard exception class like Exception class in
Java.
2) All exceptions are unchecked in C++, i.e., compiler
doesn’t check if the exceptions are caught or not.
3) In C++, a function can specify the list of exceptions that it
can throw using comma separated list like following.
void fun(int a, char b) throw (Exception1, Exception2, ..)
(A) 1 and 3
(B) 1, 2 and 3
(C) 1 and 2
(D) 2 and 3
18CSC202J - OBJECT ORIENTED
DESIGN AND PROGRAMMING

Session 11

Topic : Dynamic Modelling: Package


Diagram, UML Component Diagram
Dynamic Modelling

The dynamic model is used to express and model the


behaviour of the system over time. It includes support
for activity diagrams, state diagrams, sequence diagrams
and extensions including business process modelling.
Package Diagram

• All the interrelated classes and interfaces of the system


when grouped together form a package.
• To represent all these interrelated classes and
interface UML provides package diagram.
• Package diagram helps in representing the various
packages of a software system and the dependencies
between them.
• It also gives a high-level impression of use case and
class diagram.
Package Diagram: purpose
• To provide static models of modules, their parts and their
relationships
• To present the architectural modelling of the system
• To group any UML elements
• To specify the logical distribution of classes
• To emphasize the logical structure of the system
• To offer the logical distribution of classes which is inferred
from the logical architecture of the system
Package Diagram: Uses
• To illustrate the functionality of a software
system.
• To illustrate the layered architecture of a
software system.
• The dependencies between these packages can
be adorned with labels / stereotypes to indicate
the communication mechanism between the
layers.
Notations
S.NO NAME SYMBOL DESCRIPTION

1 Package organize elements into


groups to provide better
structure for system
model.

2 Mode show only a subset of the


contained elements
according to some
criterion.
Example
Component Diagram

∙ A component diagram shows the physical view of the system


∙ A component is an autonomous unit within a system.
∙ We combine packages or individual entities to form
components.
∙ We can depict various components and their dependencies
using a component diagram.
∙ Component diagram contain: component package,
components, interfaces and dependency relationship.
Component Diagram: Purpose
• It shows the structural relationship between the components of
a system.
• It identifies the architectural perspective of the system as they
enable the designer to model the high level software
components with their interfaces to other components.
• It helps to organize source code into manageable chunks called
components.
• It helps to specify a physical database.
• It can be easily developed by architects and programmers.
• It enables to model the high level software components and
the interfaces to those components.
• The components and subsystem can be flexibly reused and
replaced.
Guidelines to Draw
• Based on the analysis of the problem description of the system,
identify the major subsystem.
• Group the individual packages and other logical entities in the
system to provide as separate components.
• Then identify the interfaces needed for components
interaction.
• If needed, identify the subprograms which are part of each of
the components and draw them along with their associated
components.
• Use appropriate notations to draw the complete component
diagram.
18CSC202J - OBJECT ORIENTED
DESIGN AND PROGRAMMING

Session 13

Topic : UML Deployment Diagram,


Examples
Guidelines to Draw: Deployment Diagram
• Identify the hardware components and processing units in the
target system.
• Analyze the software and find out the subsystem, parallel
execution of modules, server side components, client side
components, business logic components, backend database
servers and software and hardware mapping mechanism to
map the software components to be mapped with appropriate
hardware devices.
• Draw the hardware components and show the software
components inside them and also show the connectivity
between them.
Notations
S.NO NAME SYMBOL DESCRIPTION

A node represents a physical


1 Node component of the system.
Node is used to represent
physical part of a system like
server, network etc.
A structural relationship
2 Association describing a set of links
connected between objects.
Example
Example
1. online shopping UML diagrams
2. Ticket vending machine UML diagrams
3. Bank ATM UML diagrams
4. Hospital management UML diagrams
5. Digital imaging and communications in medicine
(DICOM) UML diagrams
6. Java technology UML diagrams
7. Application development for Android UML diagrams
UNIT -V
18CSC202J - OBJECT ORIENTED DESIGN AND
PROGRAMMING

Standard Template Library


What is stl???
• The Standard Template Library (STL) is a set of C++ template classes to provide
common programming data structures and functions such as lists, stacks, arrays,
etc.
• It is a library of container classes, algorithms, and iterators.
• It is a generalized library and so, its components are parameterized.
• A working knowledge of template classes is a prerequisite for working with STL.
Why use STL???
• STL offers an assortment of containers
• STL publicizes the time and storage complexity of its containers
• STL containers grow and shrink in size automatically
• STL provides built-in algorithms for processing containers
• STL provides iterators that make the containers and algorithms flexible and
efficient.
• STL is extensible which means that users can add new containers and new
algorithms such that:
– STL algorithms can process STL containers as well as user defined containers
– User defined algorithms can process STL containers as well user defined
containers
The C++ Standard Template Libraries
• In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended
C++ with a library of class and function templates which has come to be known as
the STL.
• In 1994, STL was adopted as part of ANSI/ISO Standard C++.
The C++ Standard Template Libraries

• STL had three basic components:


– Containers
Generic class templates for storing collection of data.
– Algorithms
Generic function templates for operating on containers.
– Iterators
Generalized ‘smart’ pointers that facilitate use of containers.
They provide an interface that is needed for STL algorithms to operate on STL
containers.
• String abstraction was added during standardization.
STL Containers

Sequence and Associative Containers


Containers

• Containers or container classes store objects and data.


• There are in total seven standard “first-class” container
classes and three container adaptor classes and only seven
header files that provide access to these containers or
container adaptors.
– Sequence Containers
– Container Adaptors
– Associative Containers
– Unordered Associative Containers
Sequence Containers
Topic : Sequence Container: Vector List
Sequence Containers: Vector

• Vectors are same as dynamic arrays with the ability to resize itself
automatically when an element is inserted or deleted, with their storage
being handled automatically by the container.
• Vector elements are placed in contiguous storage so that they can be
accessed and traversed using iterators. In vectors, data is inserted at the
end.
• Inserting at the end takes differential time, as sometimes there may be a
need of extending the array.
• Removing the last element takes only constant time because no resizing
happens. Inserting and erasing at the beginning or in the middle is linear in
time.
functions associated with the vector
// C++ program to illustrate the iterators in vector
#include <iostream>
#include <vector>

using namespace std;

int main()
{
vector<int> g1;
Output:
for (int i = 1; i <= 5; i++)
g1.push_back(i);
Output of begin and end: 1 2 3 4 5
Output of cbegin and cend: 1 2 3 4 5
cout << "Output of begin and end: "; Output of rbegin and rend: 5 4 3 2 1
for (auto i = g1.begin(); i != g1.end(); ++i) Output of crbegin and crend : 5 4 3 2 1
cout << *i << " ";

cout << "\nOutput of cbegin and cend: ";


for (auto i = g1.cbegin(); i != g1.cend(); ++i)
cout << *i << " ";

cout << "\nOutput of rbegin and rend: ";


for (auto ir = g1.rbegin(); ir != g1.rend(); ++ir)
cout << *ir << " ";

cout << "\nOutput of crbegin and crend : ";


for (auto ir = g1.crbegin(); ir != g1.crend(); ++ir)
cout << *ir << " ";

return 0;
}
functions associated with the vector
// C++ program to illustrate the capacity function in vector
#include <iostream>
#include <vector>

using namespace std;

int main()
{
vector<int> g1;

for (int i = 1; i <= 5; i++)


g1.push_back(i); Output:
Size : 5
cout << "Size : " << g1.size();
Capacity : 8
cout << "\nCapacity : " << g1.capacity();
cout << "\nMax_Size : " << g1.max_size(); Max_Size : 4611686018427387903
Size : 4
// resizes the vector size to 4 Vector is not empty
g1.resize(4); Vector elements are: 1 2 3 4
// prints the vector size after resize()
cout << "\nSize : " << g1.size();

// checks if the vector is empty or not


if (g1.empty() == false)
cout << "\nVector is not empty";
else
cout << "\nVector is empty";

// Shrinks the vector


g1.shrink_to_fit();
cout << "\nVector elements are: ";
for (auto it = g1.begin(); it != g1.end(); it++)
cout << *it << " ";

return 0;
}
functions associated with the vector
// C++ program to illustrate the element accesser in vector
#include <bits/stdc++.h>
using namespace std;

int main()
{
vector<int> g1;

for (int i = 1; i <= 10; i++)


g1.push_back(i * 10);
Output:
cout << "\nReference operator [g] : g1[2] = " << g1[2]; Reference operator [g] : g1[2] = 30
at : g1.at(4) = 50
cout << "\nat : g1.at(4) = " << g1.at(4); front() : g1.front() = 10
back() : g1.back() = 100
cout << "\nfront() : g1.front() = " << g1.front(); The first element is 10

cout << "\nback() : g1.back() = " << g1.back();

// pointer to the first element


int* pos = g1.data();

cout << "\nThe first element is " << *pos;


return 0;
}
functions associated with the vector
Sequence Container: List

• Lists are sequence containers that allow non-contiguous memory


allocation.
• As compared to vector, list has slow traversal, but once a position
has been found, insertion and deletion are quick.
• Normally, when we say a List, we talk about doubly linked list. For
implementing a singly linked list, we use forward list.
#include <iostream>
#include <list> cout << "\nList 2 (gqlist2) is : ";
#include <iterator> cout << "\nList 1 (gqlist1) is : ";
using namespace std;
//function for printing the elements in a list
showlist(gqlist1);
void showlist(list <int> g) showlist(gqlist2);
{ cout << "\ngqlist1.front() : " << gqlist1.front();
list <int> :: iterator it;
cout << "\ngqlist1.back() : " << gqlist1.back();
for(it = g.begin(); it != g.end(); ++it)
cout << '\t' << *it; cout << "\ngqlist1.pop_front() : ";
cout << '\n'; gqlist1.pop_front();
} showlist(gqlist1);
int main()
{ cout << "\ngqlist2.pop_back() : ";
list <int> gqlist1, gqlist2; gqlist2.pop_back();
for (int i = 0; i < 10; ++i) showlist(gqlist2);
{
gqlist1.push_back(i * 2);
cout << "\ngqlist1.reverse() : ";
gqlist2.push_front(i * 3); gqlist1.reverse();
} showlist(gqlist1);
cout << "\ngqlist2.sort(): ";
gqlist2.sort();
showlist(gqlist2);
return 0;
}
The output of the above program is :

List 1 (gqlist1) is : 0 2 4 6 8 10 12 14 16 18
List 2 (gqlist2) is : 27 24 21 18 15 12 9 6 3 0
gqlist1.front() : 0
gqlist1.back() : 18
gqlist1.pop_front() : 2 4 6 8 10 12 14 16 18
gqlist2.pop_back() : 27 24 21 18 15 12 9 6 3
gqlist1.reverse() : 18 16 14 12 10 8 6 4 2
gqlist2.sort(): 3 6 9 12 15 18 21 24 27
functions associated with the Lists
functions associated with the Lists
functions associated with the Lists
functions associated with the Lists
functions associated with the Lists
functions associated with the Lists
MCQ
• 1. In which classes we can define the list and vector classes?
A. Abstract classes
B. child classes
C. STL classes
D. String classes
• 2. Which of the following are the components of STL?
A. Algorithms
B. containers
C. function, iterators
D. All of these
• 3. Which of the following is to provide a different interface for
sequential containers?
A. container adopters
B. sequence containers
C. queue
D. Associative Containers
• 4. By STL how many components it has been kept?
A. 3
B. 4
C.1
D. unlimited
Sequence Containers: Deque
Double ended queues are sequence containers with the feature of expansion and
contraction on both the ends.
They are similar to vectors, but are more efficient in case of insertion and deletion of
elements. Unlike vectors, contiguous storage allocation may not be guaranteed.
Double Ended Queues are basically an implementation of the data structure double
ended queue. A queue data structure allows insertion only at the end and deletion
from the front.
This is like a queue in real life, wherein people are removed from the front and added
at the back. Double ended queues are a special case of queues where insertion and
deletion operations are possible at both the ends.
The functions for deque are same as vector, with an addition of push and pop
operations for both front and back.
Methods of Deque
#include <iostream>
#include <deque>
using namespace std;

void showdq(deque <int> g)


{
deque <int> :: iterator it;
for (it = g.begin(); it != g.end(); ++it)
cout << '\t' << *it;
cout << '\n';
}

int main() OUTPUT:


{
deque <int> gquiz; The deque gquiz is : 15 20 10 30
gquiz.push_back(10); gquiz.size() : 4
gquiz.push_front(20); gquiz.max_size() : 4611686018427387903
gquiz.push_back(30); gquiz.at(2) : 10
gquiz.push_front(15); gquiz.front() : 15
cout << "The deque gquiz is : "; gquiz.back() : 30
showdq(gquiz); gquiz.pop_front() : 20 10 30
gquiz.pop_back() : 20 10
cout << "\ngquiz.size() : " << gquiz.size();
cout << "\ngquiz.max_size() : " << gquiz.max_size();

cout << "\ngquiz.at(2) : " << gquiz.at(2);


cout << "\ngquiz.front() : " << gquiz.front();
cout << "\ngquiz.back() : " << gquiz.back();

cout << "\ngquiz.pop_front() : ";


gquiz.pop_front();
showdq(gquiz);

cout << "\ngquiz.pop_back() : ";


gquiz.pop_back();
showdq(gquiz);

return 0;
Methods of Deque
Sequence Containers: Array
The introduction of array class from C++11 has offered a better alternative for
C-style arrays. The advantages of array class over C-style array are :-
Array classes knows its own size, whereas C-style arrays lack this property. So
when passing to functions, we don’t need to pass size of Array as a separate
parameter.
With C-style array there is more risk of array being decayed into a pointer. Array
classes don’t decay into pointers
Array classes are generally more efficient, light-weight and reliable than C-style
arrays.
Operations on array
Array get() function in C++ STL
•The array::get() is a built-in function in C++ STL which returns a reference to the i-th element
of the array container.
•Syntax:
•get(array_name) Parameters: The function accepts two mandatory parameters which are
described below.
•i – position of an element in the array, with 0 as the position of the first element.
•arr_name – an array container.
•Return Value: The function returns a reference to the element at the specified position in the
array
•Time complexity: O(1)
// // C++ code to demonstrate working of array, to() and get()
#include<iostream>
#include<array> // for array, at()
#include<tuple> // for get()
using namespace std;
int main()
{
// Initializing the array elements
array<int,6> ar = {1, 2, 3, 4, 5, 6};

// Printing array elements using at()


cout << "The array elements are (using at()) : ";
for ( int i=0; i<6; i++) Output:
cout << ar.at(i) << " "; The array elements are (using at()) : 1 2 3 4 5 6
cout << endl; The array elements are (using get()) : 1 2 3 4 5 6
The array elements are (using operator[]) : 1 2 3 4
// Printing array elements using get() 5 6
cout << "The array elements are (using get()) : ";
cout << get<0>(ar) << " " << get<1>(ar) << " ";
cout << get<2>(ar) << " " << get<3>(ar) << " ";
cout << get<4>(ar) << " " << get<5>(ar) << " ";
cout << endl;

// Printing array elements using operator[]


cout << "The array elements are (using operator[]) : ";
for ( int i=0; i<6; i++)
cout << ar[i] << " ";
cout << endl;

return 0; }
Operations on array
// C++ code to demonstrate working of front() and back()
#include<iostream>
#include<array> // for front() and back()
using namespace std;
int main()
{
// Initializing the array elements
array<int,6> ar = {1, 2, 3, 4, 5, 6};
Output:
// Printing first element of array First element of array is : 1
cout << "First element of array is : "; Last element of array is : 6
cout << ar.front() << endl;

// Printing last element of array


cout << "Last element of array is : ";
cout << ar.back() << endl;

return 0;

}
Operations on array
// C++ code to demonstrate working of size() and max_size()
#include<iostream>
#include<array> // for size() and max_size()
using namespace std;
int main()
{
// Initializing the array elements
array<int,6> ar = {1, 2, 3, 4, 5, 6}; Output:
The number of array elements is : 6
// Printing number of array elements Maximum elements array can hold is : 6
cout << "The number of array elements is : ";
cout << ar.size() << endl;

// Printing maximum elements array can hold


cout << "Maximum elements array can hold is : ";
cout << ar.max_size() << endl;

return 0;

}
Operations on array
swap() :- The swap() swaps all elements of one array with other.

for (int i=0; i<6; i++)


// C++ code to demonstrate working of swap() cout << ar1[i] << " ";
#include<iostream> cout << endl;
#include<array> // for swap() and array // Swapping ar1 values with ar
using namespace std; ar.swap(ar1);
int main()
{ // Printing 1st and 2nd array after swapping
cout << "The first array elements after swapping are : ";
// Initializing 1st array for (int i=0; i<6; i++)
array<int,6> ar = {1, 2, 3, 4, 5, 6}; cout << ar[i] << " ";
cout << endl;
// Initializing 2nd array cout << "The second array elements after swapping are : ";
array<int,6> ar1 = {7, 8, 9, 10, 11, 12}; for (int i=0; i<6; i++)
cout << ar1[i] << " ";
// Printing 1st and 2nd array before swapping cout << endl;
cout << "The first array elements before swapping are : "; return 0;
for (int i=0; i<6; i++) }
cout << ar[i] << " ";
cout << endl;
cout << "The second array elements before swapping are : ";
Output:
The first array elements before swapping are : 1 2 3 4 5 6
The second array elements before swapping are : 7 8 9 10 11 12
The first array elements after swapping are : 7 8 9 10 11 12
The second array elements after swapping are : 1 2 3 4 5 6
Operations on array
// C++ code to demonstrate working of empty() and fill()
#include<iostream>
#include<array> // for fill() and empty()
using namespace std;
int main()
{
array<int,6> ar; // Declaring 1st array
array<int,0> ar1; // Declaring 2nd array
ar1.empty()? cout << "Array empty":
cout << "Array not empty";
cout << endl; // Checking size of array if it is empty
// Filling array with 0
ar.fill(0); Output:
// Displaying array after filling Array empty
cout << "Array after filling operation is : "; Array after filling operation is : 0 0 0 0 0 0
for ( int i=0; i<6; i++)
cout << ar[i] << " ";
return 0;
}
MCQ

1.Which of the following does not support any insertion or deletion?


a) Array
b) Vector
c) Dequeue
d) List

2) Which of the following header file is required to use deque container in


C++?
a)<queue>
b)<deque>
c)<dqueue>
d)<cqueue>

3)What is the correct output of the given code snippets?

a)10 20 30
b)Garbage Value
c)Syntax error
d)Runtime error
4.Which of the following class template are based on arrays?
a) vector
b) list
c) dequeue
d) both vector & dequeue
Topic : STL Stack
STL Stack
• Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new element is
added at one end and (top) an element is removed from that end only.

• Stack uses an encapsulated object of either vector or deque (by default) or list (sequential container class)
as its underlying container, providing a specific set of member functions to access its elements.

Stack Syntax:-
• For creating a stack, we must include the <stack> header file in our code. We then use this syntax to define
the std::stack:

• template <class Type, class Container = deque<Type> > class stack;Type – is the Type of element contained
in the std::stack. It can be any valid C++ type or even a user-defined type.
Example:
#include <iostream>
#include <stack>
using namespace std;
int main() {
OUTPUT : 22 21
stack<int> stack;
stack.push(21);
stack.push(22);
stack.push(24);
stack.push(25);

stack.pop();
stack.pop();
while (!stack.empty()) {
cout << stack.top() <<" ";
stack.pop();
}
}
// CPP program to demonstrate working of STL stack
#include <iostream>
#include <stack>
using namespace std;

void showstack(stack <int> s)


{
while (!s.empty())
{
cout << '\t' << s.top();
s.pop();
}
cout << '\n';
}

int main ()
{ Output:
stack <int> s;
s.push(10);
The stack is : 1 5 20 30 10
s.push(30); s.size() : 5
s.push(20);
s.push(5);
s.top() : 1
s.push(1); s.pop() : 5 20 30 10
cout << "The stack is : ";
showstack(s);

cout << "\ns.size() : " << s.size();


cout << "\ns.top() : " << s.top();

cout << "\ns.pop() : ";


s.pop();
showstack(s);

return 0;
}
List of functions of Stack
stack::top() top() function is used to
reference the top(or the newest) // Application of top() function
#include <iostream>
element of the stack.
#include <stack>
Syntax : using namespace std;
stackname.top()
int main()
Parameters: No value is needed to {
pass as the parameter. int sum = 0;
Return Value: Direct reference to the stack<int> mystack;
mystack.push(1);
top element of the stack mystack.push(8);
container. mystack.push(3);
mystack.push(6);
mystack.push(2);
OUTPUT : 20 // Stack becomes 1, 8, 3, 6, 2
Time Complexity: O(n) while (!mystack.empty()
sum = sum + mystack.top();
Auxiliary Space: O(n) mystack.pop();
}
cout << sum;
return 0;
}
1. What is the Standard Template Library?
a) Set of C++ template classes to provide common programming data structures and functions
b) Set of C++ classes
c) Set of Template functions used for easy data structures implementation
d) Set of Template data structures only.
Answer: a
STL expanded as Standard Template Library is set of C++ template classes to provide common
programming data structures and functions.

2. How many components STL has?


a) 1
b) 2
c) 3
d) 4
Answer : d

3. What are Container Adaptors?


a) Containers that implements data structures which can be accessed sequentially
b) Containers that implements sorted data structures for fast search in O(logn)
c) Containers that implements unsorted(hashed) data structures for quick search in O(1)
d) Containers that provide a different interface for sequential containers.
Answer: d
Container Adaptors is the subset of Containers that provides a different interface for sequential containers.
Topic :Associative Containers: Map,
Multimap
Associative Containers: Map, Multimap

• STL components are now part of standard c++


library defined in namespace std

• The standard template library (STL) contains


– Containers
– Algorithms
– Iterators
Containers supported by STL
Containers are objects that hold data
Associative containers

• They are designed to support direct access to


elements using keys
• Not sequential
• There are four types
– Set
– Multiset
– Map
– Multimap
• Store data in a structure called tree which
facilitates fast searching, deletion and insertion
• Slow for random access and inefficient for sorting
Associative Container

• Associative containers implement sorted data


structures that can be quickly searched (O(log n)
complexity).
• Set collection of unique keys, sorted by keys
• map collection of key-value pairs, sorted by keys,
keys are unique

• Multiset collection of keys, sorted by keys


• Multimap collection of key-value pairs, sorted by
keys
Associative containers

• Set and Multiset


– Store number of items and provide operations
for manipulating them using the values as keys
– Difference between set and multiset
• Multiset allows duplicates , but set does not allow
– Map and multimap
• Used to store pairs of items – one called the key
and the other called the value
– Difference between map and multimap
• Map allows only one key for a given value while
multimap permits multiple keys
Member Functions &Element Access
• Here are following points to be noted related to various functions
we used in the above example −
• The push_back( ) member function inserts value at the end of the
vector, expanding its size as needed.
• The size( ) function displays the size of the vector.
• The function begin( ) returns an iterator to the start of the vector.
• The function end( ) returns an iterator to the end of the vector.
• Accessing elements
• at(g) – Returns a reference to the element at position ‘g’ in the
vector
• front() – Returns a reference to the first element in the vector
• back() – Returns a reference to the last element in the vector
Other functions
• empty : This method returns true if the list is empty else returns
false.
• size : This method can be used to find the number of elements
present in the list.
• front and back : front() is used to get the first element of the list
from the start while back() is used to get the first element of the list
from the back.
• swap: Swaps two list, if there is exception thrown while swapping
any element, swap() throws exception. Both lists which are to be
swapped must be of the same type, i.e you can’t swap list of an
integer with list of strings.
• reverse: This method can be used to reverse a list completely.
• sort: sort method sorts the given list. It does not create new sorted
list but changes the position of elements within an existing list to
sort it.
24
Algorithms

• Retrieve or Non-mutating Algorithms


• Mutating Algorithms
• Sorting Algorithms
• Set Algorithms
• Relational Algorithms
Non Mutating Algorithms
• Adjacent_find –adj pairs
• Count-occurrence of a value
• Count_if—no.of elements that matches a predicate
• Equal-if two ranges are equal
• Find-first occurrence of a value
• Find_end
• Find_first_of()
• Find_if()- find the elements that matches a predicate
• For_each()- apply an operation to each element
• Mismatch()
• Search_ch()
• Search_n()
Mutating Algorithms

• Copy()
• Copy_backward()
Algorithms : find()
• InputIterator find (InputIterator first, InputIterator last, const T& val);
• The find() algorithm looks for an element matching val between start and
end.
• If an element matching val is found, the return value Is an iterator that points
to that element. Otherwise, the return value is an iterator that points to end.
#include <iostream>
#include <algorithm>
using namespace std;
int main () {
int myints[] = { 10, 20, 30, 40 };
int * p = find (myints, myints+4, 30);
if (p != myints+4) cout << "Element found in myints: " << *p << '\n';
else cout << "Element not found in myints\n“;
return 0; }
Find() Algorithm
#include <vector>
#include <algorithm>
#include <iostream>
int key;
int arr[] = { 12, 3, 17, 8, 34, 56, 9 }; // standard C array
vector<int> v(arr, arr+7); // initialize vector with C array
vector<int>::iterator iter;
cout << ”enter value :”;
cin >> key;
iter=find(v.begin(),v.end(),key); // finds integer key in v
if (iter != v.end()) // found the element
cout << ”Element ” << key << ” found” << endl;
else
cout << ”Element ” << key << ” not in vector v” << endl;
Find_If() Algorithm

#include <vector>
#include <algorithm>
#include <iostream>
Bool mytest(int n) { return (n>21) && (n <36); };
int arr[] = { 12, 3, 17, 8, 34, 56, 9 }; // standard C array
vector<int> v(arr, arr+7); // initialize vector with C array
vector<int>::iterator iter;
iter=find_if(v.begin(),v.end(),mytest);
// finds element in v for which mytest is true
if (iter != v.end()) // found the element
cout << ”found ” << *iter << endl;
else
cout << ”not found” << endl;
Algorithm: count()
#include <iostream>
• count() returns the number of elements in
the given range that are equal to given #include <algorithm>
value. #include <vector>
• Syntax for count is: using namespace std;
• count(first ,last ,value) : This will return int main ()
number of the element in range defined {
• by iterators first and last ( excluded ) int values[] = {5,1,6,9,10,1,12,5,5,5,1,8,9,7,46};
which are equal ( == ) the value int count_5 = count(values, values+15, 5);
/* now count_5 is equal to 4 */
vector<int> v(values, values+15);
int count_1 = count(v.begin(), v.end(), 1);
/* now count_1 is equal to */
return 0;
}
Count_If() Algorithm

#include <vector>
#include <algorithm>
#include <iostream>
Bool mytest(int n) { return (n>14) && (n <36); };
int arr[] = { 12, 3, 17, 8, 34, 56, 9 }; // standard C
array
vector<int> v(arr, arr+7); // initialize vector with C
array
int n=count_if(v.begin(),v.end(),mytest);
// counts element in v for which mytest is true
cout << ”found ” << n << ” elements” << endl;
Algorithms : search
• This function is used to perform searches for a given sequence in a
given range. There are two variations of the search():

• search(first1 ,last1 ,first2 ,last2) : This function searches for the


sequence defined by first2 and last2 in the range first1 an
last1(where last1 is excluded). If there is a match an iterator to the d
first element of the sequence in the range [first1,last1] is returned,
else iterator to last1 is returned.
• search(first1 ,last1 ,first2 ,last2 ,cmp_functions) : Here
cmp_function is used to decide how to check the equality of two
elements, it is useful for non-numeric elements like strings and
objects.

7
Algorithms : Search Example 1
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

int main()
{
int inputs1[] = { 1,2,3,4,5,6,7,8};
int inputs2[] = { 2,3,4};
vector<int> v1(inputs1, inputs1+9);
vector<int> v2(inputs2, inputs2+3);

vector<int>::iterator i ,j;

i = search(v1.begin(), v1.end(), v2.begin(), v2.end());

/* now i points to the second element in v1 */

j = search(v1.begin()+2, v1.end(), v2.begin(), v2.end());

/* j now points to the end of v1 as no sequence is equal to 2,3,4 in


[v1.begin()+2 ,v1.end()] */
}

8
Algorithms : sort()
• This function of the STL, sorts the contents of the given range.
There are two version of sort() :
• sort(start_iterator, end_iterator ) : sorts the range defined by
iterators start_iterator and end_iterator in ascending order.
• sort(start_iterator, end_iterator, compare_function) : this also
sorts the given range but you can define how the sorting should be
done by compare_function.

9
Algorithms : sort() Example 1
#include<iostream> v1.push_back(5);
#include<algorithm> v1.push_back(1);
#include<vector>
using namespace std; /* now the vector v1 is 8,4,5,1 */
vector<int>::iterator i, j;
bool compare_function(int i, int j)
{ i = v1.begin(); // i now points to beginning of the vector v1
return i > j; // return 1 if i>j else 0 j = v1.end(); // j now points to end of the vector v1
}
bool compare_string(string i, string j) sort(i,j); //sort(v1.begin() , v1.end() ) can also be used
{ /* now the vector v1 is 1,4,5,8 */
return (i.size() < j.size());
} /* use of compare_function */

int a2[] = { 4,3,6,5,6,8,4,3,6 };


int main()
sort(a2,a2+9,compare_function); // sorts a2 in descending order
{
int arr[5] = {1,5,8,4,2}; /* here we have used compare_function which uses operator(>),
sort(arr , arr+5); that result into sorting in descending order */
// sorts arr[0] to arr[4] in ascending order
/* now the arr is 1,2,4,5,8 */ /* compare_function is also used to sort
non-numeric elements such as*/
vector<int> v1;
string s[]={"a" , "abc", "ab" , "abcde"};
v1.push_back(8);
v1.push_back(4); sort(s,s+4,compare_string);
/* now s is "a","ab","abc","abcde" */
}

10
Algorithm: merge()
Combines the elements in the sorted ranges [first1,last1) and [first2,last2), into a new
range beginning at result with all its elements sorted.
Syntax: OutputIterator merge (InputIterator1 first1, InputIterator1 last1, InputIterator2
first2, InputIterator2 last2, OutputIterator result);

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main () {
int first[] = {5,10,15,20,25};
int second[] = {50,40,30,20,10};
vector<int> v(10);
sort (first,first+5);
sort (second,second+5);
merge (first,first+5,second,second+5,v.begin());
cout << "The resulting vector contains:";
for (std::vector<int>::iterator it=v.begin(); it!=v.end(); ++it)
cout << ' ' << *it; std::cout << '\n'; return 0; }
for_each
#include <iostream>
#include <algorithm>
using namespace std;
void in_to_cm(double); //declaration Syntax :
int main() Function for_each (InputIterator first,
{ //array of inches values InputIterator last, Function fn);
double inches[] = { 3.5, 6.2, 1.0, 12.75, 4.33
};
//output as centimeters
for_each(inches, inches+5, in_to_cm); The for_each() algorithm allows
cout << endl; you to do something to every item
return 0; in a container. You write your own
}
void in_to_cm(double in) //convert and
function to determine what that
display as centimeters “something” is. Your function can’t
{ change the elements in the
cout << (in * 2.54) << ‘ ‘; container, but it can use or display
} their values.
The output looks like this:
8.89 15.748 2.54 32.385 10.9982}

11
Transform()
#include <iostream>
#include <algorithm> The transform() algorithm does something to
using namespace std; every item in a container, and places the
int main() resulting values in a different container (or
{ //array of inches values the same one).
double inches[] = { 3.5, 6.2, 1.0, 12.75, 4.33 }; Again, a user-written function determines
double centi[5]; what will be done to each item. The return
double in_to_cm(double); //prototype type of this function must be the same as that
//transform into array centi[] of the destination container.
transform(inches, inches+5, centi, in_to_cm);
for(int j=0; j<5; j++) //display array centi[]
cout << centi[j] << ‘ ‘;
cout << endl;
Syntax:
return 0;
} OutputIterator transform (InputIterator
double in_to_cm(double in) //convert inches to first1, InputIterator last1, OutputIterator
centimeters result, UnaryOperation op);
{
return (in * 2.54); //return result
}
Maps

• Associative container that associates


objects of type Key with objects of type
Data
– Sorted according to keys

• Map
– Stores (key, object) pairs
– Unimodal: duplicate keys not allowed
– AKA: table, associative array
The STL Map Template

• map()
• map(const key_compare& comp)
• pair<iterator, bool> insert(const value_type&
x)
– Inserts x into the map
• iterator insert(iterator pos, const value_type&
x)
– Inserts x into the map, using pos as a hint to where it will be
inserted
• void insert(iterator, iterator)
– Inserts a range into the map
STL Map Template
• void erase(iterator pos)
– Erases the element pointed to by pos
• size_type erase(const key_type& k)
– Erases the element whose key is k
• void erase(iterator first, iterator last)
– Erases all elements in a range
• iterator find(const key_type& k)
– Finds an element whose key is k.
• data_type& operator[](const key_type& k)
– Returns a reference to the object that is associated
with a particular key.
– If the map does not already contain such an
object, operator[] inserts the default object
data_type()
Map Usage Example

#include <iostream>
#include<iterator>
#include <map>
#include <algorithm>
#include<cstring>

using namespace std;

map<const char*, int> months;


map<const char*, int>::iterator cur;

int main() {
months["january"] = 31;
months["february"] = 28;
months["march"] = 31;
months["april"] = 30;
months["may"] = 31;
months["june"] = 30;
months["july"] = 31;
months["august"] = 31;
months["september"] = 30;
months["october"] = 31;
Example Maps
#include <iostream>
#include <map>

using namespace std;

int main ()
{
map<int,string> m;
m.insert(pair<int,string>(5,"ABCD"));
m.insert(pair<int,string>(6,"EFGH"));
m.insert(pair<int,string>(7,"IJKL"));
cout << m.at(5)<<endl ;
cout << m.at(6) <<endl;
// prints value associated with key
5,6

/* note that the parameters in the above at() are the keys not the index */

cout << m[7]<<endl ; // prints value associated with key 7


Multi Set Example
#include<iostream>
#include <set>
using namespace std;
int main()
{
// multiset declare
multiset<int> s;
// Elements added to set
s.insert(12);
s.insert(10);
s.insert(2);
s.insert(10); // duplicate added
s.insert(90);
s.insert(85);
s.insert(75);
s.insert(90);
s.insert(95);
s.insert(45);
s.insert(80);
s.insert(45);
// Iterator declared to traverse
// set elements
Function Objects
• Functors (Function Objects or Functionals) are simply put object + ().
• In other words, a functor is any object that can be used with () in the
manner of a function.
• This includes normal functions, pointers to functions, and class objects
for which the () operator (function call operator) is overloaded, i.e.,
classes for which the function operator()() is defined.
• Sometimes we can use a function object when an ordinary function
won't work. The STL often uses function objects and provides several
function objects that are very helpful.
• Function objects are another example of the power of generic
programming and the concept of pure abstraction. We could say that
anything that behaves like a function is a function. So, if we define an
object that behaves as a function, it can be used as a function.
Function Objects
#include <iostream>
#include<vector>>
#include <algorithm>
using namespace std;
class InCm {
public:
void operator()(double in)
{
cout << (in * 2.54) << " ";
}
};
int main()
{
vector<double> inches;
inches.push_back(3.5);
inches.push_back(7);

InCm in_to_cm;
Advantages of function object

• Function object are "smart functions."

• Each function object has its own type.

• Function objects are usually faster than


ordinary functions.
MCQ
• Which container can have the same keys?
a) map
b) multimap
c) unordered map
d) set
Answer: b
• Which container is used to keep priority based elements?
a) queue
b) stack
c) set
d) priority queue
Answer: d
MCQ
• How many components STL has?
a) 1
b) 2
c) 3
d) 4
Answer: d
Explanation: STL has four components namely Algorithms, Containers, Functors and Iterators.
▪ Which of the following is correct about map and multimap?
a) Map can have same keys whereas multimap cannot
b) Implementation of maps and multimap are different
c) Multimap can have same keys whereas the map cannot
d) Average search time of map is greater than multimap
Answer: c
MCQ

• Which header is need to be used with function


objects?
a) <function>
b) <functional>
c) <funct>
d) <functionstream>
Answer: b
Explanation: <functional> header is need to be
used with function objects.
Topic :STL Iterators
STL Iterators

• Are used to point at the memory addresses of STL containers.


• They are primarily used in sequence of numbers, characters etc.
• They reduce the complexity and execution time of program.
// C++ code to demonstrate the working of iterator, begin() and end()

#include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors
using namespace std;

int main()
{
vector<int> ar = { 1, 2, 3, 4, 5 };
Output:
// Declaring iterator to a vector The vector elements are : 1 2 3 4 5
vector<int>::iterator ptr;

// Displaying vector elements using begin() and end()


cout << "The vector elements are : ";

for (ptr = ar.begin(); ptr < ar.end(); ptr++)


cout << *ptr << " ";

return 0;
}
advance() :- This function is used to increment the iterator position till the specified number mentioned in its
arguments.

// C++ code to demonstrate the working of advance()


#include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors
using namespace std;
int main()
{
vector<int> ar = { 1, 2, 3, 4, 5 };

// Declaring iterator to a vector


vector<int>::iterator ptr = ar.begin(); Output:
The position of iterator after advancing is : 4
// Using advance() to increment iterator position
// points to 4
advance(ptr, 3);

// Displaying iterator position


cout << "The position of iterator after advancing is : ";
cout << *ptr << " ";

return 0;

}
// C++ code to demonstrate the working of next() and prev()
#include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors
using namespace std;
int main()
{
vector<int> ar = { 1, 2, 3, 4, 5 };

// Declaring iterators to a vector


vector<int>::iterator ptr = ar.begin();
vector<int>::iterator ftr = ar.end();

// Using next() to return new iterator Output:


// points to 4 The position of new iterator using next() is : 4
auto it = next(ptr, 3);
The position of new iterator using prev() is : 3
// Using prev() to return new iterator
// points to 3
auto it1 = prev(ftr, 3);

// Displaying iterator position


cout << "The position of new iterator using next() is : ";
cout << *it << " ";
cout << endl;

// Displaying iterator position


cout << "The position of new iterator using prev() is : ";
cout << *it1 << " ";
cout << endl;

return 0;
}
inserter() :- This function is used to insert the elements at any position in the container. It accepts 2 arguments, the
container and iterator to position where the elements have to be inserted.
// C++ code to demonstrate the working of inserter()
#include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors
using namespace std;
int main()
{
vector<int> ar = { 1, 2, 3, 4, 5 };
vector<int> ar1 = {10, 20, 30};

// Declaring iterator to a vector Output:


vector<int>::iterator ptr = ar.begin();
The new vector after inserting elements is : 1 2 3 10 20 30 4 5
// Using advance to set position
advance(ptr, 3);

// copying 1 vector elements in other using inserter()


// inserts ar1 after 3rd position in ar
copy(ar1.begin(), ar1.end(), inserter(ar,ptr));

// Displaying new vector elements


cout << "The new vector after inserting elements is : ";
for (int &x : ar)
cout << x << " ";

return 0;
}
Topic : STL Algorithm
Function Objects
STL Algorithms

• Are used to point at the memory addresses of STL containers.


• They are primarily used in sequence of numbers, characters etc.
• They reduce the complexity and execution time of program.
STL ALgorithms

• STL has an ocean of algorithms, for all < algorithm > library functions
• Some of the most used algorithms on vectors and most useful one’s in
Competitive Programming are mentioned as follows :
– sort(first_iterator, last_iterator) – To sort the given vector.
– reverse(first_iterator, last_iterator) – To reverse a vector.
– *max_element (first_iterator, last_iterator) – To find the maximum element of a
vector.
– *min_element (first_iterator, last_iterator) – To find the minimum element of a
vector.
– accumulate(first_iterator, last_iterator, initial value of sum) – Does the summation of
vector elements
// Reversing the Vector
// A C++ program to demonstrate working of sort(), reverse() reverse(vect.begin(), vect.end());
#include <algorithm>
#include <iostream> cout << "\nVector after reversing is: ";
#include <vector> for (int i=0; i<6; i++)
#include <numeric> //For accumulate operation cout << vect[i] << " ";
using namespace std;
cout << "\nMaximum element of vector is: ";
int main() cout << *max_element(vect.begin(), vect.end());
{
// Initializing vector with array values cout << "\nMinimum element of vector is: ";
int arr[] = {10, 20, 5, 23 ,42 , 15}; cout << *min_element(vect.begin(), vect.end());
int n = sizeof(arr)/sizeof(arr[0]);
vector<int> vect(arr, arr+n); // Starting the summation from 0
cout << "\nThe summation of vector elements is: ";
cout << "Vector is: "; cout << accumulate(vect.begin(), vect.end(), 0);
for (int i=0; i<n; i++)
cout << vect[i] << " "; return 0;
}
// Sorting the Vector in Ascending order
sort(vect.begin(), vect.end());

cout << "\nVector after sorting is: ";


Output:
for (int i=0; i<n; i++) Vector before sorting is: 10 20 5 23 42 15 Vector after sorting
cout << vect[i] << " "; is: 5 10 15 20 23 42 Vector before reversing is: 5 10 15 20 23 42
Vector after reversing is: 42 23 20 15 10 5 Maximum element
of vector is: 42
Minimum element of vector is: 5
The summation of vector elements is: 115
count(first_iterator, last_iterator,x) – To count the occurrences of x in vector.
find(first_iterator, last_iterator, x) – Points to last address of vector ((name_of_vector).end()) if element is not
present in vector.

// C++ program to demonstrate working of count() and find()


#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main()
{
// Initializing vector with array values
int arr[] = {10, 20, 5, 23 ,42, 20, 15};
int n = sizeof(arr)/sizeof(arr[0]);
vector<int> vect(arr, arr+n);
Output:
cout << "Occurrences of 20 in vector : "; Occurrences of 20 in vector: 2
// Counts the occurrences of 20 from 1st to Element found
// last element
cout << count(vect.begin(), vect.end(), 20);

// find() returns iterator to last address if


// element not present
find(vect.begin(), vect.end(),5) != vect.end()?
cout << "\nElement found":
cout << "\nElement not found";

return 0;
}
merge() in C++ STL

• C++ offers in its STL library a merge() which is quite


useful to merge sort two containers into
a single container.
It is defined in header “algorithm“. It is implemented in
two ways.
• Syntax 1 : Using operator “<"
// C++ code to demonstrate the working of merge() implementation 1

#include <bits/stdc++.h>
using namespace std;

int main()
{
// initializing 1st container
vector<int> arr1 = { 1, 4, 6, 3, 2 };
Output:
// initializing 2nd container
vector<int> arr2 = { 6, 2, 5, 7, 1 }; The container after merging initial containers
// declaring resultant container
is : 1 1 2 2 3 4 5 6 6 7
vector<int> arr3(10);

// sorting initial containers


sort(arr1.begin(), arr1.end());
sort(arr2.begin(), arr2.end());

// using merge() to merge the initial containers


merge(arr1.begin(), arr1.end(), arr2.begin(), arr2.end(), arr3.begin());

// printing the resultant merged container


cout << "The container after merging initial containers is : ";

for (int i = 0; i < arr3.size(); i++)


cout << arr3[i] << " ";
return 0;
}
search() in c++ STL
• std::search is defined in the header file <algorithm> and used to find out the presence of a subsequence
satisfying a condition (equality if no such predicate is defined) with respect to another sequence.
• It searches the sequence [first1, last1) for the first occurrence of the subsequence defined by [first2, last2), and
returns an iterator to its first element of the occurrence, or last1 if no occurrences are found.
• It compares the elements in both ranges sequentially using operator== (version 1) or based on any given
predicate (version 2). A subsequence of [first1, last1) is considered a match only when this is true for all the
elements of [first2, last2). Finally, std::search returns the first of such occurrences.
• It can be used in either of the two versions, as depicted below :
1. For comparing elements using ==
2. For comparison based on a predicate (or condition)
vector2 is present at index

1. For comparing elements using ==


// C++ program to demonstrate the use of std::search
ForwardIterator1 search (ForwardIterator1 first1, ForwardIterator1 #include <iostream>
last1, ForwardIterator2 first2, ForwardIterator2 last2); #include <vector>
#include <algorithm>
using namespace std;
int main()
{
•first1: Forward iterator to beginning of first container to be searched
int i, j;
into.
// Declaring the sequence to be searched into
last1: Forward iterator to end of first container to be searched into.
vector<int> v1 = { 1, 2, 3, 4, 5, 6, 7 };
first2: Forward iterator to the beginning of the subsequence of second // Declaring the subsequence to be searched for
container to be searched for. vector<int> v2 = { 3, 4, 5 };
last2: Forward iterator to the ending of the subsequence of second // Declaring an iterator for storing the returning pointer
container to be searched for. vector<int>::iterator i1;
// Using std::search and storing the result in
•Returns: an iterator to the first element of the first occurrence of [first2, // iterator i1
last2) in [first1, last1), or last1 i1 = std::search(v1.begin(), v1.end(), v2.begin(), v2.end());
if no occurrences are found. // checking if iterator i1 contains end pointer of v1 or not
if (i1 != v1.end()) {
cout << "vector2 is present at index " << (i1 - v1.begin());
} else {
cout << "vector2 is not present in vector1";
}
return 0;
}
Output:
vector2 is present at index 2
For comparison based on a predicate (or condition) :
// C++ program to demonstrate the use of std::search
• ForwardIterator1 search (ForwardIterator1 first1, // with binary predicate
ForwardIterator1 last1, ForwardIterator2 first2, #include <iostream>
ForwardIterator2 last2, BinaryPredicate pred); #include <vector>
#include <algorithm>
• All the arguments are same as previous template, just one using namespace std;
more argument is added // Defining the BinaryPredicate function
bool pred(int i, int j)
Output:
vector1 elements are greater than vector2 starting from position
{
• pred: Binary function that accepts two elements as 3
if (i > j)
arguments (one of each of the two containers, in the same
{return 1;}
order), and returns a value convertible to bool. The
else
returned value indicates whether the elements are
{return 0;}
considered to match in the context of this function. The
}
function shall not modify any of its arguments. This can
int main()
either be a function pointer or a function object.
{
int i, j;
• Returns: an iterator, to the first element of the first // Declaring the sequence to be searched into
occurrence of [first2, last2) satisfying a predicate, in [first1, vector<int> v1 = { 1, 2, 3, 4, 5, 6, 7 };
last1), or last1 if no occurrences are found. // Declaring the subsequence to be compared to based
// on predicate
vector<int> v2 = { 3, 4, 5 };
// Declaring an iterator for storing the returning pointer
vector<int>::iterator i1;
// Using std::search and storing the result in
// iterator i1 based on predicate pred
i1 = std::search(v1.begin(), v1.end(), v2.begin(), v2.end(), pred);
// checking if iterator i1 contains end pointer of v1 or not
if (i1 != v1.end()) {
cout << "vector1 elements are greater than vector2 starting "<< "from position " << (i1 - v1.begin());
} else {
cout << "vector1 elements are not greater than vector2 "<< "elements consecutively.";
}
return 0;
}
for_each() in STL
// for_each example
#include <iostream> // std::cout
•Apply function to range #include <algorithm> // std::for_each
•Applies function fn to each of the elements in the range [first,last). #include <vector> // std::vector
void myfunction (int i) { // function:
•The behavior of this template function is equivalent to: std::cout << ' ' << i;
}
struct myclass { // function object type:
void operator() (int i) {std::cout << ' ' << i;}
} myobject;
int main ()
Output:
{ myvector contains: 10 20 30
std::vector<int> myvector; myvector contains: 10 20 30
myvector.push_back(10);
myvector.push_back(20);
• Parameters myvector.push_back(30);
first, last std::cout << "myvector contains:";
✔ Input iterators to the initial and final positions in a sequence. The range used is
[first,last), which contains all the elements between first and last, including the for_each (myvector.begin(), myvector.end(), myfunction);
element pointed by first but not the element pointed by last. std::cout << '\n';
Fn
// or:
✔ Unary function that accepts an element in the range as argument.
This can either be a function pointer or a move constructible function object. std::cout << "myvector contains:";
Its return value, if any, is ignored. for_each (myvector.begin(), myvector.end(), myobject);
std::cout << '\n';
return 0;
}
Functors in C++
Function objects
• Consider a function that takes only one argument.
• However, while calling this function we have a lot more information that
we would like to pass to this function, but we cannot as it accepts only one
parameter. What can be done?
• One obvious answer might be global variables.
• However, good coding practices do not advocate the use of global
variables and say they must be used only when there is no other
alternative.
• Functors are objects that can be treated as though they are a function or
function pointer.
• Functors are most commonly used along with STLs.
The functor allows an instance object of some class to be called
as if it were an ordinary function.
•Let us consider a function that takes one argument. We can use
this function as function object to do some task on a set of data
#include <iostream> Output
#include <algorithm>
using namespace std;
int square(int x)
{

return x*x; //return square of x


}
int main()
{
int data[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

transform(data, data+10, data, square);// array name, elements, name, square


and store

for (int i = 0; i<10; i++)


cout << data[i] << endl;
}
// A C++ program uses transform() in STL to add 1 to all elements of arr[]
#include <bits/stdc++.h>
using namespace std;

int increment(int x) { return (x+1); }

int main()
{
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]); Output:
2 3 4 5 6
// Apply increment to all elements of
// arr[] and store the modified elements
// back in arr[]
transform(arr, arr+n, arr, increment);

for (int i=0; i<n; i++)


cout << arr[i] << S" ";

return 0;
}
Topic : Streams and Files
Learning Objectives

• C++ I/O streams.


• Reading and writing sequential files.
• Reading and writing random access files.

CPSC 231 D.H. C++ File Processing 120


C++ Files and Streams
• C++ views each files as a sequence of bytes.
• Each file ends with an end-of-file marker.
• When a file is opened, an object is created
and a stream is associated with the object.
• To perform file processing in C++, the header
files <iostream.h> and <fstream.h> must be
included.
• <fstream.> includes <ifstream> and
<ofstream>

CPSC 231 D.H. C++ File Processing 121


Creating a sequential file
// Fig. 14.4: fig14_04.cpp D&D p.708
// Create a sequential file
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
int main()
{
// ofstream constructor opens file
ofstream outClientFile( "clients.dat", ios::out );

if ( !outClientFile ) { // overloaded ! operator


cerr << "File could not be opened" << endl;
exit( 1 ); // prototype in stdlib.h
}

125
Sequential file
cout << "Enter the account, name, and balance.\n"
<< "Enter end-of-file to end input.\n? ";
int account;
char name[ 30 ];
float balance;

while ( cin >> account >> name >> balance ) {


outClientFile << account << ' ' << name
<< ' ' << balance << '\n';
cout << "? ";
}

return 0; // ofstream destructor closes file


}

126
How to open a file in C++ ?

Ofstream outClientFile(“clients.dat”, ios:out)


OR
Ofstream outClientFile;
outClientFile.open(“clients.dat”, ios:out)

127
File Open Modes

ios:: app - (append) write all output to the end of file


ios:: ate - data can be written anywhere in the file
ios:: binary - read/write data in binary format
ios:: in - (input) open a file for input
ios::out - (output) open afile for output
ios: trunc -(truncate) discard the files’ contents if
it exists

128
File Open Modes contd…..

ios:nocreate - if the file does NOT exists, the open operation fails
ios:noreplace - if the file exists, the open operation fails

129
How to close a file in C++?

The file is closed implicitly when a destructor for the


corresponding object is called
OR
by using member function close:
outClientFile.close();

130
Reading and printing a sequential file
// Reading and printing a sequential file
#include <iostream.h>
#include <fstream.h>
#include <iomanip.h>
#include <stdlib.h>
void outputLine( int, const char *, double );
int main()
{
// ifstream constructor opens the file
ifstream inClientFile( "clients.dat", ios::in );

if ( !inClientFile ) {
cerr << "File could not be opened\n";
exit( 1 );
}

131
int account;
char name[ 30 ];
double balance;

cout << setiosflags( ios::left ) << setw( 10 ) << "Account"


<< setw( 13 ) << "Name" << "Balance\n";

while ( inClientFile >> account >> name >> balance )


outputLine( account, name, balance );

return 0; // ifstream destructor closes the file


}

void outputLine( int acct, const char *name, double bal )


{
cout << setiosflags( ios::left ) << setw( 10 ) << acct
<< setw( 13 ) << name << setw( 7 ) << setprecision( 2 )
<< resetiosflags( ios::left )
<< setiosflags( ios::fixed | ios::showpoint )
<< bal << '\n';
}
132
File position pointer

<istream> and <ostream> classes provide member functions for


repositioning the file pointer (the byte number of the next byte in
the file to be read or to be written.)
These member functions are:
seekg (seek get) for istream class
seekp (seek put) for ostream class

133
Examples of moving a file pointer

inClientFile.seekg(0) - repositions the file get pointer to the beginning of the file
inClientFile.seekg(n, ios:beg) - repositions the file get pointer to the n-th byte of the file
inClientFile.seekg(m, ios:end) -repositions the file get pointer to the m-th byte from the end of file
nClientFile.seekg(0, ios:end) - repositions the file get pointer to the end of the file
The same operations can be performed with <ostream> function member seekp.

134
Updating a sequential file

Data that is formatted and written to a sequential file cannot be


modified easily without the risk of destroying other data in the
file.
If we want to modify a record of data, the new data may be longer
than the old one and it could overwrite parts of the record
following it.

135
Problems with sequential files

Sequential files are inappropriate for so-called “instant access”


applications in which a particular record of information must be
located immediately.
These applications include banking systems, point-of-sale systems,
airline reservation systems, (or any data-base system.)

136
Random access files

Instant access is possible with random access files.

Individual records of a random access file can be accessed directly (and


quickly) without searching many other records.

137
Example of a Program that Creates a Random Access File

// Fig. 14.11: clntdata.h


// Definition of struct clientData used in
// Figs. 14.11, 14.12, 14.14 and 14.15.
#ifndef CLNTDATA_H
#define CLNTDATA_H
struct clientData {
int accountNumber;
char lastName[ 15 ];
char firstName[ 10 ];
float balance;
};
#endif
138
Creating a random access file

// Creating a randomly accessed file sequentially


#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include "clntdata.h"
int main()
{
ofstream outCredit( "credit1.dat", ios::out);
if ( !outCredit ) {
cerr << "File could not be opened." << endl;
exit( 1 );
}

139
clientData blankClient = { 0, "", "", 0.0 };

for ( int i = 0; i < 100; i++ )


outCredit.write
(reinterpret_cast<const char *>( &blankClient ),
sizeof( clientData ) );
return 0;
}

140
<ostream> membEr function write

The <ostream> member function write outputs a fixed number of bytes


beginning at a specific location in memory to the specific stream. When
the stream is associated with a file, the data is written beginning at the
location in the file specified by the “put” file pointer.

141
Writing data randomly to a random file
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include "clntdata.h"
int main()
{
ofstream outCredit( "credit.dat", ios::ate );

if ( !outCredit ) {
cerr << "File could not be opened." << endl;
exit( 1 );
}

142
cout << "Enter account number "<< "(1 to 100, 0 to end
input)\n? ";
clientData client;
cin >> client.accountNumber;

while ( client.accountNumber > 0 && client.accountNumber


<= 100 )
{
cout << "Enter lastname, firstname, balance\n? ";
cin >> client.lastName >> client.firstName>>
client.balance;

143
outCredit.seekp( ( client.accountNumber - 1 ) *sizeof(
clientData ) );
outCredit.write(
reinterpret_cast<const char *>( &client ),
sizeof( clientData ) );

cout << "Enter account number\n? ";


cin >> client.accountNumber;
}

return 0;
}
144
Reading data from a random file

#include <iostream.h>
#include <iomanip.h>
#include <fstream.h>
#include <stdlib.h>
#include "clntdata.h"
void outputLine( ostream&, const clientData & );
int main()
{
ifstream inCredit( "credit.dat", ios::in );
if ( !inCredit ) {
cerr << "File could not be opened." << endl;
exit( 1 );
}
145
cout << setiosflags( ios::left ) << setw( 10 ) << "Account"<< setw( 16 ) << "Last Name"
<< setw( 11 )
<< "First Name" << resetiosflags( ios::left )<< setw( 10 ) << "Balance" << endl;
clientData client;
inCredit.read( reinterpret_cast<char *>( &client ),
sizeof( clientData ) );

CPSC 231 D.H. C++ File Processing 146


while ( inCredit && !inCredit.eof() ) {
if ( client.accountNumber != 0 )
outputLine( cout, client );
inCredit.read( reinterpret_cast<char *>( &client ),
sizeof( clientData ) );
}
return 0;
}

147
void outputLine( ostream &output, const clientData &c )
{
output << setiosflags( ios::left ) << setw( 10 )<< c.accountNumber <<
setw( 16 ) << c.lastName
<< setw( 11 ) << c.firstName << setw( 10 )<< setprecision( 2 ) <<
resetiosflags( ios::left )
<< setiosflags( ios::fixed | ios::showpoint )<< c.balance << '\n';
}

CPSC 231 D.H. C++ File Processing 148


The <istream> function read

inCredit.read (reinterpret_cast<char *>(&client),sizeof(clientData));

The <istream> function inputs a specified (by sizeof(clientData))


number of bytes from the current position of the specified stream
into an object.

149
Topic : Files

150
Learning Objectives

• Reading and writing sequential files.


• Reading and writing random access files.

151
files
• A file is a collection of related data stored in a particular area
on the disk.
• A program typically involves either
i. data transfer between the console unit and the program (or)
Ii. Data transfer between the program and a disk file.
The stream that supplies data to the program is known as input
stream.
The stream that receives data from the program is known as
output stream.

152
Disk files
read data (input stream)
data input
program
data output
write data (output stream)
Disk files

153
Classes for the file stream operations
A set of classes that define the file handling methods in c++
includes ( defined in iostream.h and fstream.h) derived from
fstreambase
ifstream input stream
ofstream output stream
fstream file stream

154
Opening and closing a file :
Before using a file, we have to,
•Give a suitable name for the file
•Think about data type and structure
•Purpose of the file
•Opening method:
A file can be opened in two ways,
i.Using the constructor function of the class. It is useful when we
use only one file in the stream.
ii.Using the member function open() of the class, when we want to
manage multiple files using one stream.
155
Opening files using constructor:
Step1: create the input stream using ifstream and output stream
using ofstream.
Step 2: initialize the file object with the desired filename.
Eg: ofstream outfile(“result”); this stmt opens the file “results”
for output and attaches at to the output stream outfile.
Eg : ifstream infile(“data”); this stmt declares infile as an
ifstream object and attaches it to the file data for input.
Eg: outfile.close(); disconnects file “result” from outfile.
Eg: infile.close(); disconnects file “data” from infile.

156
Streams and Files
Working with single file- creating file with constructor functions

158
Output:
Enter item name : disk
Enter item cost : 500

Item name : disk


Item cost : 500

159
Opening files using open()
g.f : file_stream_class stream object
fstream fin;
stream_object.open(“file_name”);
fin.open(“DATA”)

160
Stream_object.open(“filename”,mode);
The mode specifies the purpose of the file.
The file can be opened in the absence of the mode by using the
default values in the absence of actual values.

161
File Open Modes
ios:: app - (append) write all output to the end of file
ios:: ate - data can be written anywhere in the file
ios:: binary - read/write data in binary format
ios:: in - (input) open a file for input
ios::out - (output) open a file for output
ios: trunc -(truncate) discard the files contents if it exists
ios::nocreate – open files if the file does not exists
ios :: noreplace – opens the file is the file already exists

Eg : fout.open(“DATA”, ios::app|ios :: nocreate) the mode can


combine two or more parameters using the bitwise OR operator.
162
C++ Files and Streams
• C++ views each files as a sequence of bytes.
• Each file ends with an end-of-file marker.
• When a file is opened, an object is created and a stream is
associated with the object.
• To perform file processing in C++, the header files <iostream.h>
and <fstream.h> must be included.
• <fstream> includes <ifstream> and <ofstream>

163
How to open and close a file in C++ ?

164
165
Output:
contents of the country file
united states of america
united kingdom
south korea
contents of capital file
Washington
London
seoul

166
Detecting end_of_file:
It prevents further attempt to read data from the file.
while(fin) when fin is a ifstream object which returns o if any
error occurs in the file operation including the end of file condition.
Here the while loop is terminated when fin returns the value o on
reaching the file end_of_file condition.
if(fin1.eof()!=0)
{
exit(1)
}
eof () is a member function of ios class . Here it returns a
non-zero value if the end-of-file condition is encountererd and zero
otherwise
167
Reading from two file simultaneously

168
output:
capital of united states of America
washington
capital of united kingdom
london
capital of south korea
seoul

169
Functions for manipulation of file pointers
Each file has two associated pointers known as file pointers.
i.input pointer or get pointer used for reading from the file
ii.output pointer or put pointer used for writing into the file
OUTPUT POINTER (open for writing only)

H E L L O W O R L D

INPUT POINTER ( when we open for reading only) OUTPUT POINTER ( open in
append mode)
170
File position pointer
<istream> and <ostream> classes provide member functions for repositioning the file pointer (the byte number
of the next byte in the file to be read or to be written.)
These member functions are:
seekg (seek get) for istream class moves input pointer to a specified location
seekp (seek put) for ostream class moves output pointer to a specified location
tellg (tell get) gives the current position of the input pointer
tellp( tell put) gives the current position of the output pointer

seekg(offset,reposition)
seekp(offset,refposition)

The parameter offset represents the no.of.bytes the file pointer is to be moved from the location specified by
the parameter of the reposition

The ref position takes one of the following three constants defined in the ios class

ios::beg start of the file


ios ::cur current position of the pointer
ios::end end of the file 171
fout.seekg(0,ios::beg) – go to start or repositions the file get pointer to the
beginning of the file
fout.seekg(0,ios::cur) – stay at the current position
fout.seekg(0, ios::end) - repositions the file get pointer to the end of the file
fout.seekg(n, ios::beg) – move to the n+1-th byte in the file
fout.seekg(m, ios::cur) – go forward by m-th byte from the current position
fout.seekg(0, ios::end) - repositions the file get pointer to the end of the file
fout.seekg(-m,ios::cur)-go backward by m bytes from the current position
fout.seekg(-m,ios::end) – go backward by m bytes from the end

The same operations can be performed with <ostream> function member


seekp
172
Creating a sequential file

173
Reading and printing a sequential file

// Reading and printing a sequential file


#include <iostream.h>
#include <fstream.h>
#include <iomanip.h>
#include <stdlib.h>
void outputLine( int, const char *, double );
int main()
{
// ifstream constructor opens the file
ifstream inClientFile( "clients.dat", ios::in );

if ( !inClientFile ) {
cerr << "File could not be opened\n";
exit( 1 );
} 174
int account;
char name[ 30 ];
double balance;

cout << setiosflags( ios::left ) << setw( 10 ) << "Account"


<< setw( 13 ) << "Name" << "Balance\n";

while ( inClientFile >> account >> name >> balance )


outputLine( account, name, balance );

return 0; // ifstream destructor closes the file


}

void outputLine( int acct, const char *name, double bal )


{
cout << setiosflags( ios::left ) << setw( 10 ) << acct
<< setw( 13 ) << name << setw( 7 ) << setprecision( 2 )
<< resetiosflags( ios::left )
<< setiosflags( ios::fixed | ios::showpoint )
<< bal << '\n';
}
175
Updating a sequential file
Data that is formatted and written to a sequential file cannot be modified easily without the risk
of destroying other data in the file.

If we want to modify a record of data, the new data may be longer than the old one and it could
overwrite parts of the record following it.

Sequential files are inappropriate for so-called “instant access” applications in which a particular
record of information must be located immediately.

These applications include banking systems, point-of-sale systems, airline reservation systems,
(or any data-base system.)

Instant access is possible with random access files.

Individual records of a random access file can be accessed directly (and quickly) without
searching many other records. 176
Example of a Program that Creates a Random Access File

177
clientData blankClient = { 0, "", "", 0.0 };

for ( int i = 0; i < 100; i++ )


outCredit.write
(reinterpret_cast<const char *>( &blankClient ),
sizeof( clientData ) );
return 0;
}

178
<ostream> member function write

The <ostream> member function write outputs a fixed number of bytes


beginning at a specific location in memory to the specific stream. When
the stream is associated with a file, the data is written beginning at the
location in the file specified by the “put” file pointer.

179
Writing data randomly to a random file
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include "clntdata.h"
int main()
{
ofstream outCredit( "credit.dat", ios::ate );

if ( !outCredit ) {
cerr << "File could not be opened." << endl;
exit( 1 );
}

180
cout << "Enter account number "<< "(1 to 100, 0 to end
input)\n? ";
clientData client;
cin >> client.accountNumber;

while ( client.accountNumber > 0 && client.accountNumber


<= 100 )
{
cout << "Enter lastname, firstname, balance\n? ";
cin >> client.lastName >> client.firstName>>
client.balance;

181
outCredit.seekp( ( client.accountNumber - 1 ) *sizeof(
clientData ) );
outCredit.write(
reinterpret_cast<const char *>( &client ),
sizeof( clientData ) );

cout << "Enter account number\n? ";


cin >> client.accountNumber;
}

return 0;
}
182
Reading data from a random file

#include <iostream.h>
#include <iomanip.h>
#include <fstream.h>
#include <stdlib.h>
#include "clntdata.h"
void outputLine( ostream&, const clientData & );
int main()
{
ifstream inCredit( "credit.dat", ios::in );
if ( !inCredit ) {
cerr << "File could not be opened." << endl;
exit( 1 );
}
183
cout << setiosflags( ios::left ) << setw( 10 ) << "Account"<< setw( 16 ) << "Last Name"
<< setw( 11 )
<< "First Name" << resetiosflags( ios::left )<< setw( 10 ) << "Balance" << endl;
clientData client;
inCredit.read( reinterpret_cast<char *>( &client ),
sizeof( clientData ) );

184
while ( inCredit && !inCredit.eof() ) {
if ( client.accountNumber != 0 )
outputLine( cout, client );
inCredit.read( reinterpret_cast<char *>( &client ),
sizeof( clientData ) );
}
return 0;
}

185
void outputLine( ostream &output, const clientData &c )
{
output << setiosflags( ios::left ) << setw( 10 )<< c.accountNumber <<
setw( 16 ) << c.lastName
<< setw( 11 ) << c.firstName << setw( 10 )<< setprecision( 2 ) <<
resetiosflags( ios::left )
<< setiosflags( ios::fixed | ios::showpoint )<< c.balance << '\n';
}

186
The <istream> function read

inCredit.read (reinterpret_cast<char *>(&client),sizeof(clientData));

The <istream> function inputs a specified (by sizeof(clientData))


number of bytes from the current position of the specified stream
into an object.

187
STREAMS
C++ uses the concept of istream and ostream classes to
implement its I/O operations with the console and disk files.
C++ streams : - stream acts as an interface between the program
and the input-output device.
A stream is a sequence of bytes.
It acts as a source from which the data can be obtained or as a
destination to which output data can be sent .
• The source stream that provides data to the
program is called the input stream.
• The destination stream that receives output
from the program is called the output stream.
• A program extracts the bytes from an input
stream and inserts bytes into an output
stream
• Input stream connected to the standard input
device(keyboard)
• Output stream connected to the standard
output device(screen)
• ios is the baseclass for the istream(input stream) and ostream
(output stream) is the base class for iostream(input/output
stream).
• The class ios is declared as the virtual base class so that only
one copy of its members are inherited by the iostream.
C++ stream classes
Class name contents
ios(general • Contains basic facilities that are used by all other
input/output stream input and output classes
classes) • It also contains a pointer to buffer object(stream buf
object)
• Declares constants and functions for formatted I/O
operations
istream(Input stream) • Inherits the properties of ios
• Declares input functions such as get(),getline() &
read()
• Contains overloaded extraction operator >>
ostream(output • Inherits the properties of ios
stream) • Declares output functions such as put(),write()
• Contains overloaded insertion operator <<

iostream(input/output • Inherits the properties of istream and ostream


stream) through multiple inheritance and contains all the
input and output functions
Stream, buf • Provides an interface to physical devices through
buffers
• It acts as a base for filebuf class used in files
Streams and Files
• FSTREAM:
It provides support for simultaneous input and output
operations.
• Inherits all the functions from istream and ostream classes
through iostream.

File Operations
• Opening and Closing a file
• A file can be opened in two ways
• Using the constructor of the class
• Using the member function open() of the class
Opening file using constructor
• File name is used to initialize the file stream object.
1. Create a file stream object to manage the stream using the appropriate
class. The class ofstream is used to create the output stream and class
ifstream to create the input stream.
2. Initialize the file object with the desired filename.
General format
• Streamclass_name file_objectname (“filename”);
• Ofstream outfile (“results”);
• ifstream infile (“results”);
Read and write operations on files
Operation Console File stream

READ Cin>>name; File_objectname>>name;

WRITE Cout<<salary; File_objectname<<salary;


#include<iostream.h>
#include<fstream.h>
int main() output
{
char name[10]; File object name
float sal;
ofstream outfile(“employee”);
for(int i=0;i<3;i++)
{
cout<<“Enter name and salary of employee”<<i+1; Write Mode
cin>>name>>sal;
outfile<<name<<sal;
input
}
outfile.close();
ifstream inpfile(“employee”);
for(i=0;i<3;i++)
{
inpfile>>name; Read Mode
inpfile>>sal;
cout<<“employee”<<i+1;
cout<<name<<Sal;
}
inpfile.close();
}
Output
Enter name and salary of employee 1: Dev 25000
Enter name and salary of employee 2: Aditya 45000
Enter name and salary of employee 3: Sarthak 60000
Employee 1: Dev 25000
Employee 2: Aditya 45000
Employee 3: Sarthak 60000
Opening file using member function
File position pointer
• Both istream and ostream provide member functions for
repositioning the file-position pointer.
Member Explanation
Functions
tellg() Current position of get pointer
tellp() Current position of put pointer
seekg() Moves get pointer to a specified location (input)
seekp() Moves put pointer to a specified location (output)

• Argument seek direction


Seek Directions Explanation
ios::beg Offset counted from the beginning of the stream
ios::cur Offset counted from the current stream
ios::end Offset counted from the end of the stream
Examples of positioning the “get” file-position pointer

• //position to the nth byte of fileobject (assumes ios::beg) – default


• fileobject.seekg(n);

• //position n bytes forward in fileobject


• fileobject.seekg(n, ios::cur);

• //position n bytes back from end of fileobject


• fileobject.seekg(n, ios::end);

• //position at end of fileobject


• fileobject.seekg(0, ios::end);
#include<iostream.h>
#include<fstream.h>
int main()
{ Reads in binary

streampos begin,end;
ifstream myfile(“example.bin”, ios::binary);
begin=myfile.tellg(); //current pos of the file
myfile.seekg(0, ios::end); // moves ptr to the end of file
end=myfile.tellg();
myfile.close();
cout<<“Size is:”<<(end-begin)<<“bytes”;
return 0;
Output
} Size is: 40 bytes
Error Handling in file I/O
• Stream State Flag

• To check errors and to ensure smooth processing C++ file


stream inherit ‘stream-state’ members from the ios class that
store the information on the status of a file that is being
currently used.
Failure in i/p & o/p operations

unused unused unused unused Hard Invalid R/W eof


error op fail

Error that cannot be recovered Beyond end of file


Name Meaning

eofbit 1 when end-of-file is encountered, 0 otherwise

failbit 1 when a non-fatal I/O error has occurred, 0 otherwise

Badbit 1 when a fatal I/O error has occurred, 0 otherwise

goodbit 0 value

• Error Handling Functions


Function Meaning
Int bad() Returns non-zero value if an invalid operation, 0 otherwise
Int eof() Returns non-zero(true) value if end-of-file is encountered
while reading, 0 otherwise
Int fail() Returns non-zero(true) when an input or output operation has
failed, 0 otherwise
Int good() Returns non-zero (true)if no error has occurred, 0 otherwise
Clear() Resets the error state so further operations can be attempted
Error handling situations in files
1. Open a non existent file in read mode.
2. Open a read only file in ios::out mode.
3. Open a file with invalid name.
4. Read beyond eof.
5. Write more data In a file stored on disk when no sufficient
disk space is available.
6. Manipulate data stored in an unopened file.
7. No file is converted with the stream object.
8. Media errors which may occur while reading/writing data.

You might also like