C++ I/O and Variable Fundamentals
C++ I/O and Variable Fundamentals
Session 1
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
• 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.
Program is divided into small parts Program is divided into small parts
called ‘Functions’ called ‘Objects’
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.
• I/O Operation
• Data types
• Variable
• Static
• Constant
• Pointer
• Type conversion
I/O Operation
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.
• 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
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=∑
How to use it
• P=∑//assign address of another variable
• cout<<∑ //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=∑ 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 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
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
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.
public :
void Write ( )
function definition
const ;
};
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.
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)
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.
class Rectangle
main()
{ {
private: Rectangle r1;
Rectangle r2;
int width;
int length; r1.set(5, 8);
public: cout<<r1.area()<<endl;
};
80
Another Example
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
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
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
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.
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
• 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.
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.
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
operations
Class Attributes
Person
/ age : Date
Class Attributes (Cont’d)
Person
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
SmokeAlarm
Responsibilities
• 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.
Student Instructor
Association Relationships (Cont’d)
We can indicate the multiplicity of an association by adding
multiplicity adornments to the line denoting the association.
Student Instructor
1..*
Association Relationships (Cont’d)
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.
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)
next
LinkedListNode
previous
Association Relationships (Cont’d)
We can model objects that contain other objects by way of
special associations called aggregations and compositions.
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
– 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
• #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.
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;
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.
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.
• 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.
• 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.
#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:
• 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>
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.
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
10/6/2022 2
CONSTRUCTORS
• It is very common for some part of an object to require
initialization before it can be used.
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 do not have return types, not even void and they
cannot return values.
10/6/2022 6
• Constructors cannot be virtual.
10/6/2022 7
CONSTRUCTOR TYPES
10/6/2022 8
DEFAULT CONSTRUCTOR
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.
10/6/2022 11
DEFAULT CONSTRUCTOR
10/6/2022 13
PARAMETERIZED CONSTRUCTOR
OUTPUT
10
20
30
10/6/2022 14
PARAMETERIZED CONSTRUCTOR
10/6/2022 15
COPY CONSTRUCTOR
10/6/2022 16
COPY CONSTRUCTOR
10/6/2022 17
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;
};
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
10/6/2022 25
Polymorphism
10/6/2022 26
POLYMORPHISM
Types of Polymorphism
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
Case 3
/ /default argument declaration
#include <iostream>
void main ( )
{
void sum (int a ,int b ,int c= 5 , int d = 8);
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?
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?
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<<i;
}
A(int x=0)
{
i=x; cout<<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.
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
10/6/2022 65
10/6/2022 66
Binary Operator Overloading:-
#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
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 ______ .
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
a. Zero
b. One
c. Two
d. None of these.
10/6/2022 78
MCQ Questions
a. Zero
b. One
c. Two
d. None of these.
10/6/2022 79
MCQ Questions
10/6/2022 80
MCQ Questions
10/6/2022 81
MCQ Questions
10/6/2022 82
MCQ Questions
10/6/2022 83
Session 11
10/6/2022 84
Interaction Diagram
• Interaction diagrams are used to observe the dynamic
behavior of a system.
– Sequence diagram
– Collaboration diagram.
10/6/2022 86
How to Draw an Interaction Diagram?
• The purpose of interaction diagrams is to capture the dynamic aspect of
a system.
10/6/2022 87
Sequence Diagram
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 :
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
10/6/2022 95
Self Message
10/6/2022 96
Reply Message
• Reply messages are used to show the message being sent from the
receiver to the sender.
• The interaction moves forward only when a reply message is sent by the
receiver.
10/6/2022 97
Found Message
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
9/27/2022 109
Benefits of a Sequence Diagram
10/6/2022 111
Session 12
UML Collaboration
Diagram
10/6/2022 112
Collaboration diagram
10/6/2022 115
Example
Following diagram represents the sequencing over student management system:
10/6/2022 116
Example
10/6/2022 117
Drawbacks of a collaboration diagram
Collaboration diagrams can become complex when too many objects are
present within the system.
9/27/2022 118
MCQ’s
10/6/2022 119
Conversion of Sequence to Collaboration
Diagram
10/6/2022 120
Conversion of Sequence to Collaboration
Diagram
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.
10/6/2022 121
Session 13
10/6/2022 122
Inheritance
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
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 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.
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
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.
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
Student
Multiple Inheritance
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
• 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
A. Multiple
B. Multilevel
C. Hierarchical
D. Single
A. Multiple
B. Multilevel
C. Hierarchical
D. Single
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.
class C : access_specifier A
{
// Body of Class C
}; // Derived Class
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.
Points to Remember
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.
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
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 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 Base {
public:
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.
a. void area();
b. void area()=0;
c. void area()=1;
b. Incomplete type
b. Class is generic
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
Ans: A
Practice Questions- MCQ
Ans: C
Practice questions
1. Identify all of the activities in this diagram.
int main()
State chart diagram
18CS202J OBJECT ORIENTED DESIGN AND PROGRAMMING
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.
• Initial State: This shows the starting point of the state chart diagram that is where
the activity starts.
• Final State: The end of the state chart diagram is represented by a solid circle
surrounded by a circle.
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 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
Session 1
Session 2
Session 3
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
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
Synchronous Exceptions
Asynchronous Exceptions
Synchronous Exceptions
• For example:
• Errors such as out of range
• Overflow
• Underflow and so on
Asynchronous Exceptions
• For example
• errors such as keyboard interrupts
• hardware malfunctions
• disk failure and so on
Exception Description
std::exception An exception and parent class of all the
standard C++ exceptions.
std::bad_alloc This can be thrown by new.
Exception Description
std::runtime_error An exception that theoretically can not be
detected by reading the code.
#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
try
{
if(denominator == 0)
{
throw denominator;
}
result = numerator/denominator;
cout<<"\nThe result of division is:" <<result;
}
Handle Any Type of Exceptions (...)
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
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
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
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
Session 11
Session 13
• 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>
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 << " ";
return 0;
}
functions associated with the vector
// C++ program to illustrate the capacity function in vector
#include <iostream>
#include <vector>
int main()
{
vector<int> g1;
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;
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;
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};
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;
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;
return 0;
}
Operations on array
swap() :- The swap() swaps all elements of one array with other.
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;
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);
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.
• 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():
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;
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 */
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
• 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>
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>
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 */
InCm in_to_cm;
Advantages of function object
#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;
return 0;
}
advance() :- This function is used to increment the iterator position till the specified number mentioned in its
arguments.
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 };
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};
return 0;
}
Topic : STL Algorithm
Function Objects
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());
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);
return 0;
}
merge() in C++ STL
#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);
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);
return 0;
}
Topic : Streams and Files
Learning Objectives
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;
126
How to open a file in C++ ?
127
File Open Modes
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++?
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;
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
135
Problems with sequential files
136
Random access files
137
Example of a Program that Creates a Random Access File
139
clientData blankClient = { 0, "", "", 0.0 };
140
<ostream> membEr function write
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;
143
outCredit.seekp( ( client.accountNumber - 1 ) *sizeof(
clientData ) );
outCredit.write(
reinterpret_cast<const char *>( &client ),
sizeof( clientData ) );
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 ) );
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';
}
149
Topic : Files
150
Learning Objectives
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
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
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
173
Reading and printing a sequential file
if ( !inClientFile ) {
cerr << "File could not be opened\n";
exit( 1 );
} 174
int account;
char name[ 30 ];
double balance;
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.)
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 };
178
<ostream> member function write
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;
181
outCredit.seekp( ( client.accountNumber - 1 ) *sizeof(
clientData ) );
outCredit.write(
reinterpret_cast<const char *>( &client ),
sizeof( clientData ) );
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
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 <<
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
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
goodbit 0 value