0% found this document useful (0 votes)
11 views120 pages

Oops Notes Final

The document provides a comprehensive overview of Object-Oriented Programming (OOP) and its comparison with Procedural Programming. It highlights key concepts of OOP such as classes, objects, encapsulation, abstraction, polymorphism, inheritance, dynamic binding, and message passing, along with their significance in programming. Additionally, it discusses data types in C++, including built-in, user-defined, and derived data types, along with rules for defining variables and constants.

Uploaded by

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

Oops Notes Final

The document provides a comprehensive overview of Object-Oriented Programming (OOP) and its comparison with Procedural Programming. It highlights key concepts of OOP such as classes, objects, encapsulation, abstraction, polymorphism, inheritance, dynamic binding, and message passing, along with their significance in programming. Additionally, it discusses data types in C++, including built-in, user-defined, and derived data types, along with rules for defining variables and constants.

Uploaded by

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

OBJECT ORIENTED PROGRAMMING LANGUAGE – USA20201J

Unit – 1
Comparison of Procedural and Object Oriented Programming

Procedural Programming

Procedural Programming can be defined as a programming model which is


derived from structured programming, based upon the concept of calling
procedure. Procedures, also known as routines, subroutines or functions, simply
consist of a series of computational steps to be carried out. During a program’s
execution, any given procedure might be called at any point, including by other
procedures or itself.
Languages used in Procedural Programming:
FORTRAN, ALGOL, COBOL,

Object-Oriented Programming

Object-oriented programming can be defined as a programming model


which is based upon the concept of objects. Objects contain data in the form of
attributes and code in the form of methods. In object-oriented programming,
computer programs are designed using the concept of objects that interact with
the real world. Object-oriented programming languages are various but the most
popular ones are class-based, meaning that objects are instances of classes,
which also determine their types.
Languages used in Object-Oriented Programming:
Java, C++, C#, Python,
PHP, JavaScript, Ruby, Perl,
Objective-C, Dart, Swift, Scala.

Procedural Programming vs Object-Oriented Programming

Below are some of the differences between procedural and object-oriented


programming:
Procedural Oriented Programming Object-Oriented Programming
In procedural programming, the program In object-oriented programming, the
is divided into small parts program is divided into small parts
called functions. called objects.

Procedural programming follows a top- Object-oriented programming follows


down approach. a bottom-up approach.
There is no access specifier in procedural Object-oriented programming has access
programming. specifiers like private, public, protected,
etc.
Adding new data and functions is not Adding new data and function is easy.
easy.
Procedural programming does not have Object-oriented programming provides
any proper way of hiding data so it is less data hiding so it is more secure.
secure.
In procedural programming, overloading Overloading is possible in object-
is not possible. oriented programming.
In procedural programming, there is no In object-oriented programming, the
concept of data hiding and inheritance. concept of data hiding and inheritance is
used.

In procedural programming, the function In object-oriented programming, data is


is more important than the data. more important than function.
Procedural programming is based on Object-oriented programming is based
the unreal world. on the real world.
Procedural programming is used for Object-oriented programming is used for
designing medium-sized programs. designing large and complex programs.
Procedural programming uses the Object-oriented programming uses the
concept of procedure abstraction. concept of data abstraction.
Code reusability absent in procedural Code reusability present in object-
programming, oriented programming.
Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.

Features / Basic Concepts of OOPs


TABLE OF CONTENT:
1. Introduction
2. Class
3. Objects
4. Encapsulation
5. Abstraction
6. Polymorphism
7. Inheritance
8. Dynamic Binding
9. Message Passing

Object-oriented programming – As the name suggests uses objects in


programming. Object-oriented programming aims to implement real-world
entities like inheritance, hiding, polymorphism, etc in programming.
The main aim of OOP is to bind together the data and the functions that
operate on them so that no other part of the code can access this data except that
function.
Characteristics of an Object Oriented Programming language

Class:
The building block of C++ that leads to Object-Oriented programming is a Class.
It is a user-defined data type, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class. A
class is like a blueprint for an object.
● A Class is a user-defined data-type which has data members and member
functions.
● Data members are the data variables and member functions are the
functions used to manipulate these variables and together these data
members and member functions define the properties and behaviour of the
objects in a Class.
● In the above example of class Car, the data member will be speed limit,
mileage etc and member functions can apply brakes, increase speed etc.
We can say that a Class in C++ is a blue-print representing a group of objects
which shares some common properties and behaviors.
Object:
An Object is an identifiable entity with some characteristics and behaviour.
An Object is an instance of a Class. When a class is defined, no memory is
allocated but when it is instantiated (i.e. an object is created) memory is allocated.
classperson
{
charname[20];
intid;
public:
voidgetdetails(){}
};

intmain()
{
person p1; // p1 is a object
}

Object take up space in memory and have an associated address like a record in
pascal or structure or union in C.
When a program is executed the objects interact by sending messages to one
another.
Each object contains data and code to manipulate the data. Objects can interact
without having to know details of each other’s data or code, it is sufficient to
know the type of message accepted and type of response returned by the objects.

Encapsulation:
In normal terms, Encapsulation is defined as wrapping up of data and
information under a single unit. In Object-Oriented Programming, Encapsulation
is defined as binding together the data and the functions that manipulate them.

Encapsulation also leads to data abstraction or hiding. As using encapsulation


also hides the data. In the above example, the data of any of the section like sales,
finance or accounts are hidden from any other section.
Abstraction:
Data abstraction refers to providing only essential information about the data
to the outside world, hiding the background details or implementation.

● Abstraction using Classes: We can implement Abstraction in C++ using


classes. The class helps us to group data members and member functions
using available access specifiers. A Class can decide which data member will
be visible to the outside world and which is not.
● Abstraction in Header files: One more type of abstraction in C++ can be
header files. For example, consider the pow() method present in math.h
header file. Whenever we need to calculate the power of a number, we
simply call the function pow() present in the math.h header file and pass the
numbers as arguments without knowing the underlying algorithm according
to which the function is actually calculating the power of numbers.

Polymorphism:
The word polymorphism means having many forms. In simple words, we
can define polymorphism as the ability of a message to be displayed in more than
one form.
A person at the same time can have different characteristic. Like a man at the
same time is a father, a husband, an employee. So the same person posses
different behaviour in different situations. This is called polymorphism.

An operation may exhibit different behaviours in different instances. The


behaviour depends upon the types of data used in the operation.
C++ supports operator overloading and function overloading.
● Operator Overloading: The process of making an operator to exhibit
different behaviours in different instances is known as operator overloading.
● Function Overloading: Function overloading is using a single function name
to perform different types of tasks.
Polymorphism is extensively used in implementing inheritance.
Example: Suppose we have to write a function to add some integers, sometimes
there are 2 integers; sometimes there are 3 integers. We can write the Addition
Method with the same name having different parameters; the concerned method
will be called according to parameters.

Inheritance:
The capability of a class to derive properties and characteristics from another
class is called Inheritance. Inheritance is one of the most important features of
Object-Oriented Programming.

● Sub Class: The class that inherits properties from another class is called Sub
class or Derived Class.
● Super Class:The class whose properties are inherited by sub class is called
Base Class or Super class.
● Reusability: Inheritance supports the concept of “reusability”, i.e. when we
want to create a new class and there is already a class that includes some of
the code that we want, we can derive our new class from the existing class.
By doing this, we are reusing the fields and methods of the existing class.
Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.
Dynamic Binding:
In dynamic binding, the code to be executed in response to function call is
decided at runtime. C++ has virtual functions to support this.

Message Passing:
Objects communicate with one another by sending and receiving
information to each other. A message for an object is a request for execution of a
procedure and therefore will invoke a function in the receiving object that
generates the desired results. Message passing involves specifying the name of
the object, the name of the function and the information to be sent.

I/O Operation in C++


C++ comes with libraries that provide us with many ways for performing input
and output. In C++ input and output are performed in the form of a sequence of
bytes or more commonly known as streams.
● Input Stream: If the direction of flow of bytes is from thedevice(for example,
Keyboard) to the main memory then this process is called input.
● Output Stream: If the direction of flow of bytes is opposite, i.e. from main
memory to device( display screen ) then this process is called output.
Header files available in C++ for Input/Output operations are:
1. iostream: iostream stands for standard input-output stream. This header file
contains definitions of objects like cin, cout, cerr, etc.
2. iomanip: iomanip stands for input-output manipulators. The methods
declared in these files are used for manipulating streams. This file contains
definitions of setw, setprecision, etc.
3. fstream: This header file mainly describes the file stream. This header file is
used to handle the data being read from a file as input or data being written
into the file as output.
4. bits/stdc++: This header file includes every standard library. In programming
contests, using this file is a good idea, when you want to reduce the time
wasted in doing chores; especially when your rank is time sensitive. To know
more about this header file refer this article.

Datatypes in C++
1. Primary(Built-in) Data Types:
character
integer
floating point
boolean
double floating point
void
wide character

2.User Defined Data Types:

Structure
Union
Class
Enumeration

3.Derived Data Types:


Array
Function
Pointer

1.User Define Data type

The data types that are defined by the user are called the derived datatype
or user-defined derived data type.

Class:
The building block of C++ that leads to Object Oriented
programming is a Class. It is a user defined data type, which holds its own
data members and member functions, which can be accessed and used by
creating an instance of that class. A class is like a blueprint for an object.

Structure:
A structure is a user defined data type in C/C++. A
structure creates a data type that can be used to group items of possibly
different types into a single type.
Syntax
struct address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};
Union:

union is a user defined data type. In union, all members


share the same memory location. For example in the following C program,
both x and y share the same location. If we change x, we can see the
changes being reflected in y.

Syntax

union address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};

Enumeration:

Enumeration (or enum) is a user defined data type in C.


It is mainly used to assign names to integral constants, the names
make a program easy to read and maintain.

Syntax

enum week
{
Mon,
Tue,
Wed,
Thur,
Fri,
Sat,
Sun
};
2.Built in Data Type

Data types in C++ is mainly divided into two types: Primitive Data
Types: These data typesare built-in or predefined data types and can be
used directly by the user to declare variables. example: int, char , float,
bool etc.
:
These data types are built-in or predefined data types and can be
used directly by the user to declare variables. example: int, char , float,
bool etc.

Integer: Keyword used for integer data types is int. Integers typically
requires 4 bytes of memory space and ranges from -2147483648 to
2147483647.
Character: Character data type is used for storing characters.
Keyword used for character data type is char. Characters typically requires
1 byte of memory space and ranges from -128 to 127 or 0 to 255.
Boolean: Boolean data type is used for storing boolean or logical
values. A boolean variable can store either true or false. Keyword used for
boolean data type is bool.
FloatingPoint:Floating Point data type is used for storing single
precision floating point values or decimal values. Keyword used for floating
point data type is float. Float variables typically requires 4 byte of memory
space.
Double Floating Point: Double Floating Point data type is used for
storing double precision floating point values or decimal values. Keyword
used for double floating point data type is double. Double variables
typically requires 8 byte of memory space.
void: Void means without any value. void datatype represents a
valueless entity. Void data type is used for those function which does not
returns a value.

3.Derived data types

1. Array
2. Function
3. Pointer
Array
An array is simply a collection of variables of the
same data type that are referenced by a common name. In other words,
when elements of linear structures are represented in the memory by
means of contiguous memory locations, these linear structures are called
arrays.

An array stores a list of finite number (n) of


homogeneous data elements (i.e., data elements of the same type). The
number n is called length or size or range of an array.
Syntax

type array_name[array_size];

Example

Int arr[10];

Functions
A function declaration tells the compiler about a function's
name, return type, and parameters. A function definition provides the
actual body of the function. The C++ standard library provides numerous
built-in functions that your program can call.
Function prototype or function interface is a declaration of
a function that specifies the function's name and type signature (arity, data
types of parameters, and return type), but omits the function body.

Syntax

Function name ()
{
--------
--------
}

Pointers

& symbol is used to get the address of the variable. * symbol is


used to get the value of the variable that the pointer is pointing to. If a
pointer in C is assigned to NULL, it means it is pointing to nothing. Two
pointers can be subtracted to know how many elements are available
between these two pointers.

The actual data type of the value of all pointers, whether


integer, float, character, or otherwise, is the same, a long hexadecimal
number that represents a memory address. The only difference
between pointers of different data types is the data type of the variable or
constant that the pointer points to.

Syntax

Int *a

Variables
A variable is a name of memory location. It is used to store data. Its value can be
changed and it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily
identified.
Syntax
data_type variable_name;
Example

int x;
float y;
char z;

Rules for defining variables


A variable can have alphabets, digits and underscore.
A variable name can start with alphabet and underscore only. It can't start with
digit.
No white space is allowed within variable name.
A variable name must not be any reserved word or keyword e.g. char, float etc.

Constant

The const keywords used to define the constant value that cannot change
during program execution. It means once we declare a variable as the constant in
a program, the variable's value will be fixed and never be changed. If we try to
change the value of the const type variable, it shows an error message in the
program.

Use const keywords with different parameters:

o Use const variable


o Use const with pointers
o Use const pointer with variables
o Use const with function arguments
o Use const with class member functions
o Use const with class data members
o Use const with class objects

Const variable
It is a const variable used to define the variable values that never be changed
during the execution of a program. And if we try to modify the value, it throws an
error.

Syntax:
const data_type variable_name;
Example
Const int a= 10;
Example Program
#include <iostream>
#include <conio.h>
using namespace std;
int main ()
{
// declare the value of the const
const int num = 25;
num = num + 10;
return 0;
}

Type Conversion in C++


The conversion of one data type into another in the C++ programming
language. Type conversion is the process that converts the predefined data type
of one variable into an appropriate data type. The main idea behind type
conversion is to convert two different data type variables into a single data type
to solve mathematical and logical expressions easily without any data loss.

For example, we are adding two numbers, where one variable is of int type
and another of float type; we need to convert or typecast the int variable into a
float to make them both float data types to add them.

Type conversion can be done in two ways in C++, one is implicit type
conversion, and the second is explicit type conversion. Those conversions are
done by the compiler itself, called the implicit type or automatic type conversion.
The conversion, which is done by the user or requires user interferences called
the explicit or user define type conversion. Let's discuss the implicit and explicit
type conversion in C++.
Implicit Type Conversion

The implicit type conversion is the type of conversion done automatically by the
compiler without any human effort. It means an implicit conversion automatically
converts one data type into another type based on some predefined rules of the
C++ compiler. Hence, it is also known as the automatic type conversion.

For example:

int x = 20;
short int y = 5;
int z = x + y;

Explicit type conversion

Conversions that require user intervention to change the data type of one
variable to another, is called the explicit type conversion. In other words, an
explicit conversion allows the programmer to manually changes or typecasts the
data type from one variable to another type. Hence, it is also known as
typecasting. Generally, we force the explicit type conversion to convert data from
one type to another because it does not follow the implicit conversion rule.

The explicit type conversion is divided into two ways:

Explicit conversion using the cast operator


Explicit conversion using the assignment operator

Example Program

#include <iostream>
using namespace std;
int main ()
{
float f2 = 6.7;
// use cast operator to convert data from one type to another
int x = static_cast <int> (f2);
cout << " The value of x is: " << x;
return 0;
}

Operators in C++
An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations. C++ is rich in built-in operators and
provide the following types of operators −

● Arithmetic Operators
● Relational Operators
● Logical Operators
● Bitwise Operators
● Assignment Operators

Arithmetic Operators

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give 200

/ Divides numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after B % A will give 0


an integer division

++ Increment operator, increases integer A++ will give 11


value by one

-- Decrement operator, decreases integer A-- will give 9


value by one

Relational Operators

Operator Description Example

== Checks if the values of two operands are (A == B) is not true.


equal or not, if yes then condition
becomes true.

!= Checks if the values of two operands are (A != B) is true.


equal or not, if values are not equal then
condition becomes true.

> Checks if the value of left operand is (A > B) is not true.


greater than the value of right operand,
if yes then condition becomes true.

< Checks if the value of left operand is less (A < B) is true.


than the value of right operand, if yes
then condition becomes true.

>= Checks if the value of left operand is (A >= B) is not true.


greater than or equal to the value of
right operand, if yes then condition
becomes true.

<= Checks if the value of left operand is less (A <= B) is true.


than or equal to the value of right
operand, if yes then condition becomes
true.

Logical Operators
Operator Description Example

&& Called Logical AND operator. If both the (A && B) is false.


operands are non-zero, then condition
becomes true.

|| Called Logical OR Operator. If any of the (A || B) is true.


two operands is non-zero, then condition
becomes true.

! Called Logical NOT Operator. Use to !(A && B) is t


reverses the logical state of its operand.
If a condition is true, then Logical NOT
operator will make false.

Bitwise Operators
Operator Description Example Operator Description

& Binary AND Operator (A & B) will give 12 & Binary AND Operator
copies a bit to the which is 0000 1100 copies a bit to the
result if it exists in result if it exists in
both operands. both operands.

| Binary OR Operator (A | B) will give 61 which | Binary OR Operator


copies a bit if it exists is 0011 1101 copies a bit if it exists
in either operand. in either operand.

^ Binary XOR Operator (A ^ B) will give 49 which ^ Binary XOR Operator


copies the bit if it is set is 0011 0001 copies the bit if it is set
in one operand but not in one operand but not
both. both.

~ Binary Ones (~A ) will give -61 which ~ Binary Ones


Complement Operator is 1100 0011 in 2's Complement Operator
is unary and has the complement form due to is unary and has the
effect of 'flipping' bits. a signed binary number. effect of 'flipping' bits.

Assignment Operators
Operator Description Example

= Simple assignment operator, Assigns values C = A + B will assign value of A + B into


from right side operands to left side C
operand.

+= Add AND assignment operator, It adds right C += A is equivalent to C = C + A


operand to the left operand and assign the
result to left operand.

-= Subtract AND assignment operator, It C -= A is equivalent to C = C - A


subtracts right operand from the left
operand and assign the result to left
operand.

*= Multiply AND assignment operator, It C *= A is equivalent to C = C * A


multiplies right operand with the left
operand and assign the result to left
operand.

/= Divide AND assignment operator, It divides C /= A is equivalent to C = C / A


left operand with the right operand and
assign the result to left operand.

%= Modulus AND assignment operator, It takes C %= A is equivalent to C = C % A


modulus using two operands and assign the
result to left operand.

Misc Operators
Sr.No Operator & Description

1 sizeof
sizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’ is
integer, and will return 4.
2 Condition ? X : Y
Conditional operator (?). If Condition is true then it returns value of X otherwise
returns value of Y.
3 ,
Comma operator causes a sequence of operations to be performed. The value of the
entire comma expression is the value of the last expression of the comma-separated
list.
4 . (dot) and -> (arrow)
Member operators are used to reference individual members of classes, structures,
and unions.
5 Cast
Casting operators convert one data type to another. For example, int(2.2000) would
return 2.
6 &
Pointer operator & returns the address of a variable. For example &a; will give actual
address of the variable.
7 *
Pointer operator * is pointer to a variable. For example *var; will pointer to a variable
var.

Control Structure / Control Statement


A control structure is a block of programming that analyzes
variables and chooses a direction in which to go based on given parameters.
The term flow control details the direction the program takes

Types of Control Structure

1.Branching
2.Looping

Branching statement
if statement
if..else statements
if-else-if ladder
nested if statements
switch statements

If Statement:

The if statement selects and executes the statement(s) based on a


given condition. If the condition evaluates to True then a given set of
statement(s) is executed.

If the condition evaluates to False, then the given set of statements is


skipped and the program control passes to the statement following the if
statement.
Syntax
if (condition)
{
statement 1;
statement 2;
statement 3;
}
Example
if (mark>40)
{
Cout<<”PASS”;
}
If-else Statement:

The if-else statement comprises two parts, namely, if and else.


The if statement alone tells us that if a condition is true it will execute a
block of statements and if the condition is false he else statement ll be
execute . We can use the else statement with if statement to execute a
block of code when the condition is false
Syntax
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Example
if(x>y)
cout<<”X is greater”;
else
cout<<”y is greater”;

Nested if-else Statement:

A nested if-else statement contains one or more if-else statements.


Nested if statements means an if statement inside another if statement.
Syntax
if (condition1)
{
// Executes when condition1
is true
if (condition2)
{
// Executes when
condition2 is true
}
Else{}
}
Example
if (a>b)
{
if (a>c)
cout<<”a is largest”;
}
else //nested if-else
statement within else
{
if (b>c)
cout<<”b is largest”;
else
cout<<”c is largest”;
}

if-else-if ladder

The if-else-if staircase, has an if-else statement within the outermost


else statement. The inner else statement can further have other if-else
statements. As soon as one of the conditions controlling the if is true, the
statement associated with that if is executed, and the rest of the ladder is
bypassed
Syntax
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
Example
char ch;
cout<<"Enter an alphabet:";
cin>>ch;
if( (ch>='A') && (ch<='Z'))
cout <<"The alphabet is in upper
case";
else if ( (ch>=' a') && (ch<=' z' ) )
cout<<"The alphabet is in lower
case";
else
cout<<"It is not an alphabet";
return 0;
}

The switch Statement:


The switch statement selects a set of statements from the available
sets of statements. The switch statement tests the value of an expression
in a sequence and compares it with the list of integers or character
constants.
Syntax
switch(expression)
{
case <constant1>: statement1;
[break;]
case <constant2>: statement2;
[break;]
case <constant3>: statement3;
[default: statement4;]
[break;]
}
Statement5;
Example
cin>>x;
int x;
switch(x)
{
case l: cout<<"Option1 is
selected";
break;
case 2: cout<<"Option2 is
selected";
break;
case 3: cout<<"Option3 is
selected";
break;
case 4: cout<<"Option4 is
selected;
break;
default: cout<<"Invalid option!";
}
Example Program
#include <iostream>
using namespace std;
int main () {
int num;
cout<<"Enter a number to check grade:";
cin>>num;
if (num <0 || num >100)
{
cout<<"wrong number";
}
else if(num >= 0 && num < 50){
cout<<"Fail";
}
else if (num >= 50 && num < 60)
{
cout<<"D Grade";
}
else if (num >= 60 && num < 70)
{
cout<<"C Grade";
}
else if (num >= 70 && num < 80)
{
cout<<"B Grade";
}
else if (num >= 80 && num < 90)
{
cout<<"A Grade";
}
else if (num >= 90 && num <= 100)
{
cout<<"A+ Grade";
}
}

Looping
A loop statement allows us to execute a statement or group of
statements multiple times and following is the general from of a loop
statement in most of the programming languages
C++ while and do...while Loop. Loops are used in programming to
repeat a specific block of code. ... In computer programming, loop repeats a
certain block of code until some end condition is met.

Types of Loop
1.Entry control Loop
i)For Loop
ii)While Loop
2.Exit Control Loop
i) Do while Loop

for Loop

1. The initialization statement is executed only once at the beginning.


2. Then, the test expression is evaluated.
3. If the test expression is false, for loop is terminated. But if the test
expression is true, codes inside body of for loop is executed and
update expression is updated.
4. Again, the test expression is evaluated and this process repeats until
the test expression is false.

Syntax

for(initializationStatement;
testExpression;increment/decre
ment)

// codes

}
Example

for(i=0;i<=5;i++)

Cout<<” SRM IST”


}

while Loop

● The while loop evaluates the test expression.


● If the test expression is true, codes inside the body of while loop is
evaluated.
● Then, the test expression is evaluated again. This process goes on
until the test expression is false.
● When the test expression is false, while loop is terminated.

Syntax
while
(testExpression)
{
// codes
}
Example
I=0;
while (i<=5)
{
Cout<<” SRM IST”
i++;
}
Do While Loop

The do...while loop is a variant of the while loop with one important
difference. The body of do...while loop is executed once before the test
expression is checked.

● The codes inside the body of loop is executed at least once. Then, only
the test expression is checked.
● If the test expression is true, the body of loop is executed. This
process continues until the test expression becomes false.
● When the test expression is false, do...while loop is terminated.
Syntax

do
{
// codes;
}
while
(testExpression);
Example
do
{
Cout<<”SRM IST “;
}
while (i<=5);

Example Program

#include <stdio.h>
int main()
{
int sum=0;
for(inti=1;i<=50;i++)
{
sum=sum+i;
}
printf("Sum=%d",sum);
return 0; }
Functions
A function is a group of statements that together perform a task.
Every C++program has at least one function, which is main(), and all the
most trivial programs can define additional functions. ...
A function declaration tells the compiler about afunction's name, return
type, and parameters.
Syntax:

return-type function-name(parameter1, parameter2, ...)

// function-body

● return-type: suggests what the function will return. It can be int, char,
some pointer or even a class object. There can be functions which
does not return anything, they are mentioned with void.
● Function Name: is the name of the function, using the function name
it is called.
● Parameters: are variables to hold values of arguments passed while
function is called. A function may or may not contain parameter list.
● Function body: is the part where the code statements are written.

Declaring, Defining and Calling a Function

#include < iostream>


using namespace std;
int sum (int x, int y); ------- //declaring the function
int main()
{
int a = 10;
int b = 20;
int c = sum (a, b); ------- calling the function
cout<< c;
}
int sum (int x, int y) ------- defining the function
{
return (x + y);
}
Calling a Function
Functions are called by their names. If the function is without argument,
it can be called directly using its name. But for functions with arguments,
we have two ways to call them,

1. Call by Value
2. Call by Reference

Call by Value

In this calling technique we pass the values of arguments which are


stored or copied into the formal parameters of functions. Hence, the
original values are unchanged only the parameters inside function changes.
Example
void calc(int x);

int main()

int x = 10;

calc(x);

printf("%d", x);

void calc(int x)

x = x + 10 ;

Call by Reference

In this we pass the address of the variable as arguments. In this case


the formal parameter can be taken as a reference or a pointer, in both the
case they will change the values of the original variable
Example
void calc(int *p);

int main()

int x = 10;

calc(&x); // passing address of x as argument

printf("%d", x);

void calc(int *p)

*p = *p + 10;

Main Function

The main( ) function in a C++ program is typically a non value


returning function (a void function). A void function does not return a value
to its caller. the main function is "called" by the operating system when the
user runs the program.

When a C++ program is executed, the execution control goes directly


to the main() function. Every C++ program have a main() function.

Syntax:

Void main

---------
-----------

Default arguments

In C++ programming, you can provide default values for function


parameters. The idea behind default argument is simple. If a function is
called by passingargument/s, those arguments are used by the function.
But if the argument/s are not passed while invoking a function then,
the default values are used.
C++ User-defined Function Types
● Function with no argument and no return value.
● Function with no argument but return value.
● Function with argument but no return value.
● Function with argument and return value.

C++ Recursion
When function is called within the same function, it is known as recursion
in C++. The function which calls the same function, is known as recursive function.
A function that calls itself, and doesn't perform any task after function call,
is known as tail recursion. In tail recursion, we generally call the same function
with return statement.
Syntax:
recursionfunction()
{
recursionfunction(); //calling self function
}
Example

#include<iostream>
using namespace std;
int main()
{
int factorial(int);
int fact,value;
cout<<"Enter any number: ";
cin>>value;
fact=factorial(value);
cout<<"Factorial of a number is: "<<fact<<endl;
return 0;
}
int factorial(int n)
{
if(n<0)
return(-1); /*Wrong value*/
if(n==0)
return(1); /*Terminating condition*/
else
{
return(n*factorial(n-1));
}
}
Inline Function
C++ inline function is powerful concept that is commonly used with classes.
If a function is inline, the compiler places a copy of the code of that function at
each point where the function is called at compile time.
Any change to an inline function could require all clients of the function to
be recompiled because compiler would need to replace all the code once again
otherwise it will continue with old functionality.
To inline a function, place the keyword inline before the function name and
define the function before any calls are made to the function. The compiler can
ignore the inline qualifier in case defined function is more than a line.
A function definition in a class definition is an inline function definition,
even without the use of the inline specifier.
Example Program
#include <iostream>
using namespace std;
inline int Max(int x, int y)
{
return (x > y)? x : y;
}
int main()
{
cout<< "Max (20,10): " << Max(20,10) << endl;
cout<< "Max (0,200): "<< Max(0,200) << endl;
cout<< "Max (100,1010): " << Max(100,1010) << endl;
return 0; }
Class and object
Class

C++ Classes and Objects. Class: The building block of C++ that
leads to Object Oriented programming is a Class. It is a user defined data
type, which holds its own data members and member functions, which
can be accessed and used by creating an instance of that class.

Syntax

Class class_name

Example

Class bca

Structure of the class .


● A Class is a user defined data-type which has data members and
member functions.
● Data members are the data variables and member functions are the
functions used to manipulate these variables and together these data
members and member functions defines the properties and behavior
of the objects in a Class.
● In the above example of class Car, the data member will be speed
limit, mileage etc and member functions can be apply brakes, increase
speed etc
Object
An object is an instantiation of a class. In terms of variables, a class
would be the type, and an object would be the variable. In the class-based
object-oriented programming paradigm, "object" refers to a
particular instance of a class where the object can be a combination of
variables, functions, and data structures..

Syntax

Class_name object-name

Example

Bca aa;
Member function Definition
There are 2 ways to define a member function:
● Inside class definition
● Outside class definition
Inside class

class bca
{
public :
int a,b,c:;
sum() // function definition
{
c=a+b;
}
};

Outside class

class bca
{
public :
int a,b,c:;
sum() // function Declaration
};
void bca :: sum() // function definition
{
c=a+b;
}
To define a member function outside the class definition we have to
use the scope resolution :: operator along with class name and function
name.

Array of object

● Like array of other user-defined data types, an array of type class can also
be created.
● The array of type class contains the objects of the class as its individual
elements.
● Thus, an array of a class type is also known as an array of objects.
● An array of objects is declared in the same way as an array of any built-in
data type.

Syntax

class class-name

datatype var1;

datatype varN;

method1();

method2();

methodN();

};

class-name obj[ size ];

Example

Class aaa

Void main()

Aaa a1[5] // array of object

Example program

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
Classemp
{
inteid;
doublehra, pf, da, cca, nf, bp;
charename[10];
public:
void getdata()
{
cout<<”enter name of the employee:”<<endl;
gets(name);
cout<<”enter employee id:”<<endl;
cin>>eid;
cout<<”enter employee basic pay:”<<endl;
cin>>bp;
}
void allow()
{
hra=(bp*10)/100;
pf=(bp*12)/100;
da=(bp*11)/100;
cca=(bp*8)/100;
np=(bp+hra+da+cca)-pf;
}
Void putdata();
{
cout<<”employee name is:”<<ename<<endl;
cout<<”employee id is:”<<eid<<endl;
cout<<”employee basic pay is:”<<bp<<endl;
cout<<”\nhra=”<<hra<<”\n da=”<<da<<”\n pf=”<<pf<<”\n cca=”<<cca;
cout<<”\n net pay of employee is:”<<np<<endl;
}
};
void main()
{
clrscr();
int n;
emp e[100];
cout<<”\n \t Arrays Of Objects”;
cout<<”\n enter number of employees:”<<endl;
cin>>n;
for(inti=0;i<n;i++)
{
cout<<”entering the details of employee:”<<i+1<<endl;
e[i].getdata();
e[i].allow();
}
clrscr();
for(inti=0;i<n;i++)
{
cout<<”displaying details of employee:”<<i+1<<endl;
e[i].putdata();
cout<<endl;
}
getch();
}

UNIT – 2
Constructor and Destructorin C++
● Constructor has same name as the class itself.
● Constructors don't have return type.
● A constructor is automatically called when an object is created.
● If we do not specify a constructor, C++ compiler generates a
default constructor for us (expects no parameters and has an empty body).
Uses

The 'calling part' is performed automatically whenever a new Object of


the class is created. Constructors can be used for efficient memory
management, which is not possible with functions. Destructor can
be used to destroy the constructors when not needed.
Syntax:
Class classname
public:

class Name()

{
//set fields and call methods
}
Example
Class bca
{
Bca ()
{
Cout << “Welcome;
}
};
Void main()
{
Bca b; // Constructor will call Automatically
}
Constructor overloading
Constructor overloading in C++ programming is same as
function overloading. When we create more that one constructors in a class with
different number of parameters or different types of parameters or different
order of parameters, it is called as constructor overloading
Example program
#include <iostream>
using namespace std;
class Room
{
private:
double length;
double breadth;
public:
Room()
{
length = 6.9;
breadth = 4.2;
}
Room(double l, double b)
{
length = l;
breadth = b;
}
Room(double len)
{
length = len;
breadth = 7.2;
}
double calculateArea()
{
return length * breadth;
}
};
int main()
{
Room room1, room2(8.2, 6.6), room3(8.2);
cout<< "Area of room = " << room3.calculateArea() << endl;
return 0;
}
Types of Constructor

Constructors are of three types:

Default Constructor.
Parameterized Constructor.
Copy Constructor.
Default Constructor.
Default Constructors: Default constructor is the constructor which
doesn't take any argument. It has no parameters. .
Default constructor for a class as a constructor that can be called
with no arguments (this includes a constructor whose parameters all have
default arguments)
Syntax:

constructor_name ( ) ; // Declaration

class_name :: class_name ( ) //Defination

{
------ // Body of the constructor
}

Example Program
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
return 0;
}
Parameterized constructor
An object is declared in a parameterized constructor, the initial
values have to be passed as arguments to the constructor function. The
normal way of object declaration may not work. Theconstructors can be
called explicitly or implicitly.

Syntax

constructor_name (int x, int y ) ; // Declaration

class_name :: class_name (int x, int y ) //Defination

{
------ // Body of the constructor
}
Example program
#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000);
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}
Copy Constructor

Generally in a constructor the object of its own class can’t be passed


as a value parameter. But the classes own object can be passed as a
reference parameter.

Such constructor having reference to the object of its own class is


known as copy constructor. It creates a new object as a copy of an existing
object.

Syntax

class class_name{
public:
class_name(class_name & obj)
{
// obj is same class another object
// Copy Constructor code
}
//... other Variables & Functions
}
Example
Main ()
{
class_name object1(params);
Method 1 - Copy Constrcutor
class_name object2(object1);
Method 2 - Copy Constrcutor
class_name object3 = object1;
}
Destructor

A destructor is a member function with the same name as its class


prefixed by a ~ (tilde).
A destructor is a special method called automatically during the
destruction of an object. Actions executed in the destructor include the
following: Recovering the heap space allocated during the lifetime of an
object.
Basically Constructor is used to initialize the objects (at the time of
creation), and they are automatically invoked. This saves us from the
garbage values assigned to data members; during initializing.

Syntax:
Class class_name
{
public:
~class_name() //Destructor
{
}
}:
Example
Class bca
{
public:
~bca() //Destructor
{
}
}:
Types of overloading in C++ are:
o Function overloading
o Operator overloading

Function /Method Overloading


FUNCTION OVERLOADING
Function overloading is a feature in C++ where two or more functions can
have the same name but different parameters. Function overloading can be
considered as an example of polymorphism feature in C++

Two or more functions having same name but different argument(s)


are known as overloaded functions.

Rules

● The same function name is used for more than one function definition
● The functions must differ either by the arity or types of their parameters
Types
● Different number of parameter
● Different types of parameter
● Different parameter with different return values

Example :Different number of parameter


Class aaa
sum(int a, Int b) // same function name & different parameter
{
}
Sum(int x, int y, int z)
{
}
Example Program
#include <iostream>
class Addition
{
public:
int sum(int num1,int num2) // Two argument
{
return num1+num2;
}
int sum(int num1,int num2, int num3) // Three argument
{
return num1+num2+num3;
}
};
int main(void)
{
Addition obj;
cout<<obj.sum(20, 15);
cout<<obj.sum(81, 100, 10);
return 0;
}
Example :Different Types of parameter
Class aaa
Sum(int a, int b) // same function name & different parameter
{
}
sum(float x,int z)
{
}
Example Program
#include <iostream>
class Addition
{
public:
int sum(int num1,int num2) // Both arguments are integer
{
return num1+num2;
}
float sum(float num3,int num4) // one float , one integer
{
return num3+num4;
}
};
int main(void)
{
Addition obj;
cout<<obj.sum(20, 15);
cout<<obj.sum(81.50, 100);
return 0;
}
Different parameter with different return values
Example

Class aaa
Int Sum(int a, Int b) // Integer return type
{
}
float Sum(float x, int y) // Float return type
{
}
Example program
#include <iostream>
class Add
{
public:
int sum(int num1,int num2) // Integer return type
{
return num1+num2;
}
float sum(float num3,int num4) // Float return type
{
return num3+num4;
}
};
int main(void)
{
Addition obj;
cout<<obj.sum(20, 15);
cout<<obj.sum(81.50, 100);
return 0;
}
Operator Overloading

Operator overloading is a compile-time polymorphism in which the


operator is overloaded to provide the special meaning to the user-defined data
type. Operator overloading is used to overload or redefines most of the operators
available in C++. It is used to perform the operation on the user-defined data type.
For example, C++ provides the ability to add the variables of the user-defined
data type that is applied to the built-in data types.

Operator that cannot be overloaded are as follows:

o Scope operator (::)


o Sizeof
o member selector(.)
o member pointer selector(*)
o ternary operator(?:)
Syntax of Operator Overloading

return_type class_name : : operator op(argument_list)


{
// body of the function.
}

Rules for Operator Overloading


Existing operators can only be overloaded, but the new operators cannot
be overloaded.
The overloaded operator contains atleast one operand of the user-defined
data type.
We cannot use friend function to overload certain operators. However, the
member function can be used to overload those operators.
When unary operators are overloaded through a member function take no
explicit arguments, but, if they are overloaded by a friend function, takes
one argument.
When binary operators are overloaded through a member function takes
one explicit argument, and if they are overloaded through a friend function
takes two explicit arguments.

Types of Operator overloading

Unary Operator overloading


Binary Operator overloading

Unary operator overloading

The unary operators operate on a single operand and following are the examples
of Unary operators −
●The increment (++) and decrement (--) operators.
● The unary minus (-) operator.
● The logical not (!) operator
Syntax

Return_Type classname :: operator op(Argument list)


{
Function Body
}
Example Program

#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test(): num(8){}
void operator ++()
{
num = num+2;
}
void Print() {
cout<<"The Count is: "<<num;
}
};
int main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();
return 0;
}
Binary Operator Overloading

Binary Operator Overloading in the C++ programming language. An operator


which contains two operands to perform a mathematical operation is called the
Binary Operator Overloading. It is a polymorphic compile technique where a
single operator can perform various functionalities by taking two operands from
the programmer or user. There are multiple binary operators like +, -, *, /, etc.,
that can directly manipulate or overload the object of a class.

Syntax

return_type :: operator binary_operator_symbol (arg)


{
// function definition
}

Example Program

#include <iostream>
using namespace std;
class A
{

int x;
public:
A(){}
A(int i)
{
x=i;
}
void operator+(A);
void display();
};

void A :: operator+(A a)
{

int m = x+a.x;
cout<<"The result of the addition of two objects is : "<<m;

}
int main()
{
A a1(5);
A a2(4);
a1+a2;
return 0;
}
UNIT -3

1 -Inheritance
Inheritance is the process of creating new classes, called derived classes,
from existing classes or base classes. The derived class inherits all the
capabilities of the base class.An inherited class is called a subclass of its parent
class or super class.

Inheritance is a mechanism in which one class acquires the property of


another class. For example, a child inherits the traits of his/her parents.
With inheritance, we can reuse the fields and methods of the existing class.

Sub Class: The class that inherits properties from another class is called
Sub class or Derived Class.
Super Class: The class whose properties are inherited by sub class is called
Base Class or Super class.

Syntax

class subclass_name : access_mode base class_name


{
//body of subclass
};
Example
Class A
{
-------
};
class B : public A
{
-------
};
Types of Inheritance

!.Single Inheritance

2. Multilevel Inheritance

3. Multiple Inheritance

4. Hierarchical Inheritance

5. Hybrid Inheritance

Single Inheritance

(One base class -One derived class)

Single Inheritance have One base class and One derived class C++ single
inheritance only one class can be derived from the base class. Based on the
visibility mode used or access specify used while deriving, the properties of the
base class are derived. Accesses specify can be private, protected or public.

Diagram

Example

Class A // base class

{ ..........
};

Class B: acess_specifier A // derived class

{ ...........

};

Example Program

#include<iostream>
using namespace std;
class aa
{
public:
void add()
{
int a=5,b=6,c;
c=a+b;
cout<<c;
}
};
class bb:public aa
{
public:
void sub()
{
int d=5, e=4, f;
f=d-e;
cout<<f;
}
};
int main()
{
bb obj;
obj.add();
obj.sub();
return 0;
};
Multilevel Inheritance
(One Base - One Derived - One or more than One Intermediate class)

Multilevel Inheritance in C++ Programming. When a class is derived from a


class which is also derived from another class, i.e. a class having more than one
parent classes, such inheritance is called Multilevel Inheritance. The level of
inheritance can be extended to any number of level depending upon the relation.

Diagram

class A // base class


{ ...........
};
class B : acess_specifier A // derived class
{ ...........
};
class C : access_specifier B // derived from derived class B
{ ...........
};
Example Program

#include<iostream>
using namespace std;
class aa
{
public:
void add()
{
int a=5,b=6,c;
c=a+b;
cout<<c;
}
};
class bb:public aa
{
public:
void sub()
{
int d=5, e=4, f;
f=d-e;
cout<<f;
}
};
class cc:public bb
{
public:
void mul()
{
int g=5,h=6,i;
i=g*h;
cout<<i;
}
};
int main()
{
cc obj;
obj.add();
obj.sub();
obj.mul();
return 0;
};
Multiple Inheritance
More than One base class -One derived class

Multiple Inheritance in C++ Multiple Inheritance is a feature of C++ where a


class can inherit from more than one classes. The constructors
of inherited classes are called in the same order in which they are inherited

Diagram

Syntax

class A
{..........
};
class B
{ ...........
};
class C : acess_specifier A , access_specifier B // derived class from A and B
{...........
};
Example Program
#include<iostream>
using namespace std;
class aa
{
public:
void add()
{
int a=3,b=6,c;
c=a+b;
cout<<c;
}
};
class bb
{
public:
void sub()
{
int d=5, e=4, f;
f=d-e;
cout<<f;
}
};
class cc
{
public:
void mul()
{
int g=2,h=3,i;
i=g*h;
cout<<i;
}
};
class dd:publicaa,publicbb,public cc
{
public:
void div()
{
int j=6,k=2,l;
l=j/k;
cout<<l;
}
};
int main()
{
dd obj;
obj.add();
obj.sub();
obj.mul();
obj.div();
return 0;
}

Difference between Multilevel and Multiple Inheritance

● Multilevel inheritance : Inheritance of characters by a child from father


and father inheriting characters from his father (grandfather)
● Multiple inheritance : Inheritance of characters by a child from mother and
father

Hierarchical Inheritance

One base class - More than One Derived class

Several classes are derived from common base class it is


called hierarchical inheritance.

In C++ hierarchical inheritance, the feature of the base class is inherited


onto more than one sub-class.

Diagram

Syntax
class A // base class
{..............
};
class B : access_specifier A // derived class from A
{ ...........
};
class C : access_specifier A // derived class from A
{ ...........
};
class D : access_specifier A // derived class from A
{ ...........
};
Example Program
using namespace std;
class aa
{
public:
void add()
{
int a=3,b=6,c;
c=a+b;
cout<<c;
}
};
class bb:public aa
{
public:
void sub()
{
int d=5, e=4, f;
f=d-e;
cout<<f;
}
};
class cc:public aa
{
public:
void mul()
{
int g=2,h=3,i;
i=g*h;
cout<<i;
}
};
class dd:public aa
{
public:
void div()
{
int j=6,k=2,l;
l=j/k;
cout<<l;
}
};
int main()
{
bb ob;
ob.add();
ob.sub();
cc abc;
abc.add();
abc.mul();
dd obj;
obj.add();
obj.div();
return 0;
};
Hybrid Inheritance
Combination of More than One type of Inheritance
C++ hybrid inheritance is combination of two or more types of inheritance.
It can also be called multi path inheritance.
The hybrid combination of single inheritance and multiple inheritance.
Hybrid inheritance is used in a situation where we need to apply more than one
inheritance in a program.
Diagram
Syntax
class A
{ .........
};
class B : public A
{ ..........
};
class C
{ ...........
};
class D : public B, public C
{ ...........
};
Example Program
#include<iostream>
using namespace std;
class aa
{
public:
void add()
{
int a=3,b=6,c;
c=a+b;
cout<<c;
}
};
class bb : public aa
{
public:
void sub()
{
int d=5, e=4, f;
f=d-e;
cout<<f;
}
};
class cc
{
public:
void mul()
{
int g=2,h=4,i;
i=g*h;
cout<<i;
}
};
class dd : public bb, public cc
{
public:
void div()
{
int j=4,k=2,l;
l=j/k;
cout<<l;
}
};
int main()
{
dd obj;
obj.add();
obj.sub();
obj.mul();
obj.div();
return 0;
};
Constructor in an Inheritance
Constructor is a class member function with the same name as the class.
The main job of the constructor is to allocate memory for class objects.
Constructor is automatically called when the object is created.
Multiple Inheritance is a feature of C++ where a class can derive from
several(two or more) base classes. The constructors of inherited classes are
called in the same order in which they are inherited.

Syntax
class S: public A1, virtual A2
{
….
};
Here,
A2(): virtual base constructor
A1(): base constructor
S(): derived constructor
Example Program-Constructor with inheritance

#include<iostream>
using namespace std;
class A1
{
public:
A1()
{
cout<< "Constructor of the base class A1 \n";
}

};

class A2
{
public:
A2()
{
cout<< "Constructor of the base class A2 \n";
}

};

class S: public A1, virtual A2


{
public:
S(): A1(), A2()
{
cout<< "Constructor of the derived class S \n";
}
};

// Driver code
int main()
{
S obj;
return 0;
}

Friend Function
Function is defined as a friend function in C++, then the protected and private
data of a class can be accessed using the function.

By using the keyword friend compiler knows the given function is a friend
function.

For accessing the data, the declaration of a friend function should be done inside
the body of a class starting with the keyword friend.

o A global function
o A member function of another class
Syntax
class class_name
{
friend data_type function_name(argument/s); // syntax of friend function.
};

Characteristics of a Friend function:

o The function is not in the scope of the class to which it has been declared
as a friend.
o It cannot be called using the object as it is not in the scope of that class.
o It can be invoked like a normal function without using the object.
o It cannot access the member names directly and has to use an object name
and dot membership operator with the member name.
o It can be declared either in the private or the public part.

Advantages of Friend Functions


A friend function is able to access members without the need of inheriting
the class.
The friend function acts as a bridge between two classes by accessing their
private data.
It can be used to increase the versatility of overloaded operators.
It can be declared either in the public or private or protected part of the
class.
Disadvantages of Friend Functions

Friend functions have access to private members of a class from outside


the class which violates the law of data hiding.
Friend functions cannot do any run-time polymorphism in their members.
Example Program
#include <iostream>
using namespace std;
class Box
{
private:
int length;
public:
Box(): length(0) { }
friend int printLength(Box); //friend function
};
int printLength(Box b)
{
b.length += 10;
return b.length;
}
int main()
{
Box b;
cout<<"Length of box: "<< printLength(b)<<endl;
return 0;
}

Virtual Base class


Virtual base class is used in situation where a derived have multiple copies
of base class.
Two or more objects are derived from a common base class, we can
prevent multiple copies of the base class being present in an object derived from
those objects by declaring the base class as virtual when it is being inherited.
Such a base class is known as virtual base class. This can be achieved by
preceding the base class’ name with the word virtual.
Syntax
class A
{
}
class B: Virtual public A //virtual base class
{
}
class C: Virtual public A // virtual base class
{
{
}
class D: public B, public C
{
}
Example Program :

#include<iostream.h>
#include<conio.h>
class ClassA
{
public:
int a;
};
class ClassB : virtual public ClassA
{
public:
int b;
};
class ClassC : virtual public ClassA
{
public:
int c;
};
classClassD : public ClassB, public ClassC
{
public:
int d;
};

void main()
{
ClassD obj;
obj.a = 10; //Statement 1
obj.a = 100; //Statement 2
obj.b = 20;
obj.c = 30;
obj.d = 40;
cout<< "\n A : "<< obj.a;
cout<< "\n B : "<< obj.b;
cout<< "\n C : "<< obj.c;
cout<< "\n D : "<< obj.d;

Output :
A : 100
B : 20
C : 30
D : 40

Abstract class and Pure virtual Function

An abstract class is a class that is designed to be specifically used as a base


class. An abstract class contains at least one pure virtual function. You declare a
pure virtual function by using a pure specifier ( = 0 ) in the declaration of a virtual
member function in the class declaration.
A class that is declared using “abstract” keyword is known as abstract class.
It can have abstract methods(methods without body) as well as concrete
methods (regular methods with body).
An abstract class cannot be instantiated, which means you are not allowed
to create an object of it.
An abstract class is mostly used to provide a base for subclasses to
extend and implement the abstract methods and override or use the
implemented methods in abstract class.
Pure virtual Function

A pure virtual function or pure virtual method is a virtual function that is


required to be implemented by a derived class if the derived class is not abstract.
Classes containing pure virtual methods are termed "abstract" and they cannot
be instantiated directly.

A subclass of an abstract class can only be instantiated directly if all


inherited pure virtual methods have been implemented by that class or a parent
class.

Example
Class student /*abstract class*/
{
Virtual void sum()=0; /*pure virtual function*/
};
Example
class Test // abstract class
{
public:
virtual void show() = 0;
};
Pure virtual function is also known as abstract class.

● We can't create an object of abstract class b'coz it has partial


implementation of methods.
● Abstract function doesn't have body
● We must implement all abstract functions in derived class.

Example Program

#include<iostream.h>
#include<conio.h>
class BaseClass //Abstract class
{
public:
virtual void Display1()=0; //Pure virtual function or abstract function
virtual void Display2()=0; //Pure virtual function or abstract function
void Display3()
{
cout<<"\n\tThis is Display3() method of Base Class";
}
};
class DerivedClass : public BaseClass
{
public:
void Display1()
{
cout<<"\n\tThis is Display1() method of Derived Class";
}
void Display2()
{
cout<<"\n\tThis is Display2() method of Derived Class"
};
void main()
{

DerivedClass D;

D.Display1(); // This will invoke Display1() method of Derived Class

D.Display2(); // This will invoke Display2() method of Derived Class

D.Display3(); // This will invoke Display3() method of Base Class

}
Virtual Function

A virtual function is a member function that you expect to be redefined in


derived classes. When you refer to a derived class object using a pointer or a
reference to the base class, you can call a virtual function for that object and
execute the derived class's version of the function.
Uses
virtual functions when you want to override a certain behavior (read
method) for your derived class rather than the one implemented for the base
class and you want to do so at run-time through a pointer to the base class.
Rules for calling virtual Function

1. When a virtual function in a base class is a created, there must be definition of


a virtual function in the base class.
2. They cannot be static member.
3. They can be friend function to another class.
4. They are accessed using object pointer.
5. A base pointer can serve as a pointer to derived object since it is type
compatible where as a derived object pointer variable to base object.

Syntax
class class- name
{
public:
virtual function-name()
{
}
};
Example
class bca
{
public:
virtual sum() // virtual function
{
}
};
Example program

#include <iostream>
using namespace std;
class Base
{
public:
virtual void print()
{
cout<< "Base Function" << endl;
}
};
class Derived : public Base
{
public:
void print()
{
cout<< "Derived Function" << endl;
}
};
int main()
{
Derived derived1;
Base* base1 = &derived1;
base1->print();
return 0;
}
Output
Derived Function

This Pointer

C++ this Pointer. Every object in C++ has access to its own address through
an important pointer called this pointer. This pointer is an implicit parameter
to all member functions. ... Friend functions do not have a this pointer, because
friends are not members of a class.

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.

Uses

1. Each object gets its own copy of the data member.


2. 2. All access the same function definition as present in the code
segment.

The ‘this’ pointer is passed as a hidden argument to all non-static


member function calls and is available as a local variable within the body of all
non-static functions.

‘this’ pointer is a constant pointer that holds the memory address of the
current object. ‘this’ pointer is not available in static member functions as static
member functions can be called without any object (with class name).
The this pointer holds the address of current object, in simple words you
can say that this pointer points to the current object of the class
Example Program:
#include <iostream.h>
class B;
class A
{
private:
int numA;
public:
A(): numA(12) { }
friend int add(A, B);
};
class B
{
private:
int numB;
public:
B(): numB(1) { }
friend int add(A , B);
};
int add(A objectA, B objectB)
{
return (objectA.numA + objectB.numB);
}
int main()
{
A objectA;
B objectB;
cout<<"Sum: "<< add(objectA, objectB);
return 0;
}
Inline Function
Inline function is powerful concept that is commonly used with classes. If
a function is inline, the compiler places a copy of the code of that function at each
point where the function is called at compile time.
Any change to an inline function could require all clients of the function to
be recompiled because compiler would need to replace all the code once again
otherwise it will continue with old functionality.
To inline a function, place the keyword inline before the function name and
define the function before any calls are made to the function. The compiler can
ignore the inline qualifier in case defined function is more than a line.
A function definition in a class definition is an inline function definition, even
without the use of the inline specifier.
1. If a function contains a loop. (for, while, do-while)
2. if a function has static variables.
3. Whether a function recurses.
4. If the return statement is absent from the function body and the return
type of the function is not void.
5. Whether a function uses a goto or switch statement.

Syntax
inline return_type function_name(parameters)
{
// function code?
}
Example Program
#include <iostream>
using namespace std;
inline int add(int a, int b)
{
return(a+b);
}
int main()
{
cout<<"Addition of 'a' and 'b' is:"<<add(2,3);A
return 0;

Advantages of inline function

o In the inline function, we do not need to call a function, so it does not cause
any overhead.
o It also saves the overhead of the return statement from a function.
o It does not require any stack on which we can push or pop the variables as
it does not perform any function calling.
o An inline function is mainly beneficial for the embedded systems as it
yields less code than a normal function.

DisAdvantages of inline function

o If we use many inline functions, then the binary executable file also
becomes large.
o The use of so many inline functions can reduce the instruction cache hit
rate, reducing the speed of instruction fetch from the cache memory to
that of the primary memory.
o It also increases the compile-time overhead because whenever the
changes are made inside the inline function, then the code needs to be
recompiled again to reflect the changes; otherwise, it will execute the old
functionality.
o Sometimes inline functions are not useful for many embedded systems
because, in some cases, the size of the embedded is considered more
important than the speed.

UNIT -4

Files

Introduction to files

Files are used to store data in a storage device permanently. File handling
provides a mechanism to store the output of a program in a file and to perform
various operations on it.

A stream is an abstraction that represents a device on which operations of


input and output are performed. A stream can be represented as a source or
destination of characters of indefinite length depending on its usage.files are
mainly dealt by using three classes fstream, ifstream, ofstream.

● ofstream: This Stream class signifies the output file stream and is applied
to create files for writing information to files
● ifstream: This Stream class signifies the input file stream and is applied for
reading information from files
● fstream: This Stream class can be used for both read and write from/to
files.

C++ provides us with the following operations in File Handling:

● Creating a file: open()


● Reading data: read()
● Writing new data: write()
● Closing a file: close()

Class for file stream operations


1. ios:-

● ios stands for input output stream.


● This class is the base class for other classes in this class hierarchy.
● This class contains the necessary facilities that are used by all the other
derived classes for input and output operations.

2. istream:-
● istream stands for input stream.
● This class is derived from the class ‘ios’.
● This class handle input stream.
● The extraction operator(>>) is overloaded in this class to handle input streams
from files to the program execution.
● This class declares input functions such as get(), getline() and read().

3. ostream:-
● ostream stands for output stream.
● This class is derived from the class ‘ios’.
● This class handle output stream.
● The insertion operator(<<) is overloaded in this class to handle output streams
to files from the program execution.
● This class declares output functions such as put() and write().

4. streambuf:-
● This class contains a pointer which points to the buffer which is used to
manage the input and output streams.

5. fstreambase:-
● This class provides operations common to the file streams. Serves as a base
for fstream, ifstream and ofstream class.
● This class contains open() and close() function.

6. ifstream:-
● This class provides input operations.
● It contains open() function with default input mode.
● Inherits the functions get(), getline(), read(), seekg() and tellg() functions from
the istream.

7. ofstream:-
● This class provides output operations.
● It contains open() function with default output mode.
● Inherits the functions put(), write(), seekp() and tellp() functions from the
ostream.

8. fstream:-
● This class provides support for simultaneous input and output operations.
● Inherits all the functions from istream and ostream classes through iostream.
9. filebuf:-
● Its purpose is to set the file buffers to read and write.
● We can also use file buffer member function to determine the length of the
file.

Opening a File

1. First is bypassing the file name in constructor at the time of object creation.

2. Second is using the open() function.

Syntax

void open(const char* file_name,ios::openmode mode);

Files Open Mode

● “r”- This mode specifies it is open for reading.


If the file does not exist, fopen() returns NULL.

● “rb”– This mode specifies it is open for reading in binary mode.


If the file does not exist, fopen() returns NULL.

● “w”– This mode specifies it is Open for writing. If the file exists, its contents
are overwritten.
If the file does not exist, it will be created.

● “wb”- This mode specifies it is Open for writing in binary mode.


If the file exists, its contents are overwritten. If the file does not exist, it will be
created.

● “a” – This mode specifies it is Open for append. Data is added to the end of
the file.
If the file does not exist, it will be created.

● “ab” – This mode specifies it is Open for append in binary mode. Data is
delivered to the end of the file.
If the file does not exist, it will be created.

● “r+” – This mode specifies it is Open for both reading and writing.
If the file does not exist, fopen() returns NULL.

● “rb+” – This mode specifies it is Open for both reading and writing in binary
mode.
If the file does not exist, fopen() returns NULL.

●“w+”– This mode specifies it is Open for both reading and writing.
If the file exists, its contents are overwritten. If the file does not exist, it will be
created.

●“wb+”- This mode specifies it is open for both reading and writing in binary
mode.
If the file exists, its contents are overwritten. If the file does not exist, it will be
created.

● “a+” – This mode specifies it is open for both reading and appending.
If the file does not exist, it will be created.

● “ab+” – This mode specifies it is Open for both reading and appending in
binary mode.
If the file does not exist, it will be created.

in Opens the file to read(default for ifstream)

out Opens the file to write(default for ofstream)

binary Opens the file in binary mode

app Opens the file and appends all the outputs at the end

ate Opens the file and moves the control to the end ofthe file

trunc Removes the data in the existing file

nocreate Opens the file only if it already exists

noreplace Opens the file only if it does not already exi


Example
fstream myfile;

myfile.open(“newfile.txt”, ios::out);

myfile.open(“myfile.txt”, ios::out | ios::app );

Default Open Modes :

● ifstream ios::in
● ofstream ios::out
● fstream ios::in | ios::out

Example Program Opening/Creating File

#include<iostream>
#include <fstream>
using namespace std;
int main()
{
fstream myfile;
myfile.open("myfile",ios::out);
if(!myfile)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
myfile.close(); // Step 4: Closing file
}
return 0;
}
Output
Writing to a File

First create a new file “myfile_write” using open() function since we


wanted to send output to the file so, we use ios::out. As given in the program,
information typed inside the quotes after Insertion Pointer “<<” got passed to the
output file.

While doing C++ programming, you write information to a file from your
program using the stream insertion operator (<<) just as you use that operator to
output information to the screen. The only difference is that you use
an ofstream or fstream object instead of the cout object.

Example Program
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream myfile;
myfile.open("myfile_write.txt",ios::out);
if(!myfile)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
myfile<<"Learning File handling"; //Writing to file
myfile.close();
}
return 0;
}
Output

Reading a file
You read information from a file into your program using the stream
extraction operator (>>) just as you use that operator to input information from
the keyboard. The only difference is that you use an ifstream or fstream object
instead of the cin object.
To read a file we need to use ‘in’ mode with syntax ios::in. In the above
example, we print the content of the file using extraction operator >>. The output
prints without any space because we use only one character at a time, we need to
use getline() with a character array to print the whole line as it is.
Example Program
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream myfile;
myfile.open("myfile_write.txt",ios::in);
if(!myfile)
cout<<"No such file";
}
else
{
char ch; while (!myfile.eof())
{
myfile>>ch;
cout<< ch;
}
myfile.close();
return 0;
}
Output

Close a File

It is simply done with the help of close() function.

Syntax: File Pointer.close()

Example Program

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream myfile;
myfile.open("myfile.txt",ios::out);
myfile.close();
return 0;
}
Output:

The file gets closed.

Detecting End Of File

C++ provides a special function, eof( ), that returns nonzero (meaning TRUE)
when there are no more data to be read from an input file stream, and zero
(meaning FALSE) otherwise. Rules for using end-of-file (eof( )): 1. Always test for
the end-of-file condition before processing data read from an input file stream.

The eof() method of ios class in C++ is used to check if the stream is has
raised any EOF (End Of File) error. It means that this function will check if this
stream has its eofbit set.

File Pointers
A pointer is used to handle and keep track of the files being accessed.
Every file maintains two pointers called get_pointer (in input mode file) and
put_pointer (in output mode file), which tells the current position where reading
or writing will take place with the use of opening modes and their respective
manipulators.

Functions of file handling:

seekg():-

It is used to move the get pointer to the desired location concerning a reference
point.
Syntax: file_pointer.seekg (number of bytes ,Reference point);

Example: fin.seekg(10,ios::beg);

tellg():-

tellg() is used to realize which they get pointer is in a file.

Syntax: file_pointer.tellg();

Example: int posn = fin.tellg();

seekp():-

seekp() is used to move the put pointer to the desired location concerning a
reference point.

Syntax: file_pointer.seekp(number of bytes ,Reference point);

Example: fout.seekp(10,ios::beg);

tellp():-

tellp()is used to realize which they get pointer is in a file.

Syntax: file_pointer.tellp();

Example: int posn=fout.tellp();

reference points available?

The reference points are:

ios::beg – These are used from the beginning of the file

ios::end – These are used from the end of the file

ios::cur – These are used from the current position in the file.
Files Usage

● Data Preservation: Storing files in documents allows to hold records even


though this system terminates.
● Easy Data Access: Accessing records will become easy whilst there may be
a large number of records and it’s far saved with inside the record, then
these files may be accessed the use of the C++ commands.
● Portability: It will become less difficult to switch records from one pc to
any other with no changes.

Manipulators
Manipulators are helping functions that can modify
the input/output stream. It does not mean that we change the value of a variable,
it only modifies the I/O stream using insertion (<<) and extraction (>>) operators.

Types of Manipulators

Manipulators without arguments: The most important manipulators


defined by the IOStream library are provided below.

endl: It is defined in ostream. It is used to enter a new line and after


entering a new line it flushes (i.e. it forces all the output written on the screen or
in the file) the output stream.

ws: It is defined in istream and is used to ignore the whitespaces in the


string sequence.

ends: It is also defined in ostream and it inserts a null character into the
output stream. It typically works with std::ostrstream, when the associated
output buffer needs to be null-terminated to be processed as a C string.

flush: It is also defined in ostream and it flushes the output stream, i.e. it
forces all the output written on the screen or in the file. Without flush, the output
would be the same, but may not appear in real-time.

C++ Sequential input output operations


The file stream classes support a number of member functions for performing
the input and output operation on files. one pair of function put() and get() are
designed for handling a single character at a time. Another pair of functions
write() and read() are use to write and read blocks of binary data.

put() and get() function

here put() write a single character to the associated stream. similarly the get()
function reads a single character from the associated stream. in the below
program show how these functions work on file. The program requests for a
string. on recieve the string, The program writes it, character by character, to the
file using the put() function in a for loop.

write() and read() function

The function write() and read() unlike the function put() and get(), handled the
data in binary form. This means that the values are stored in the disk file in the
same format in which they are stored in the internal memory. in fig show how an
int value 2594 is stored, in the binary and character format. an int takes two
bytes to store its value in the binary form. irrespective of its size but a 4 digit in
will take four bytes to store it in the character form

The binary format is more accurate for storing the number as they are stored in
the exact internal representation. there are no conversions while saving the data
and therefore saving is much faster the binary input and output functions takes
the following form

Random Access –Updating a File


Random access files permit nonsequential, or random, access to a file's
contents. To access a file randomly, you open the file, seek a particular location,
and read from or write to that file.
C++ allows you random access to files, that is you can go anywhere in the
file. The file pointer is the carat/cursor that indicates the current read/write
location in the file. For input files we can navigate to a location using seekg(); for
output files the function is seekp()
Random file access is done by manipulating the file pointer using either
seekg() function (for input) and seekp() function (for output). In case you are
wondering, the g stands for “get” and the p for “put
Random-access iterators are iterators that can be used to access elements
at an arbitrary offset position relative to the element they point to, offering the
same functionality as pointers. Random-access iterators are the most complete
iterators in terms of functionality.

Random File Access Functions


Now we have a file open for reading. By default, the file is open and the
cursor is sitting at the beginning of the file. But now we want to move the file
pointer, that is the read/write location inside your file. Note that we told C++ to
open the file in append mode. This means our pointer is now at the END of the file.
Once you have a file open for processing, you can navigate to different
parts of the file. This is often referred to as random access of files. It really means
that you aren't at the beginning or the end. Two functions are available:

● istream: seekg() (or seek and get)


● ostream: seekp() (seek and put)

Both have special ios parameters/flags, similar to the open function of the
ifstream.

Paramete
Explanation Example
r
Default setting: start from the infile.seekg(50,
beg
beginning ios::beg);
infile.seekg(-50,
end Start from the end of the file
ios::end);
infile.seekg(25,
cur Start from location of the pointer
ios::cur);

Example Program
string searchResult;
infile.seekg(10);
getline(infile, searchResult);
cout<< "10 from Beginning = " << searchResult << endl;
infile.seekg(5, ios::cur);
getline(infile, searchResult);
cout<< "5 from Current = " << searchResult << endl;
infile.seekg(-10, ios::end);
getline(infile, searchResult);
cout<< "-10 from End = " << searchResult << endl;
Output
10 from Beginning = llo
5 from Current= Hello
-10 from End = up|Hello
Error Handling During the File Operations in C++
The C++ programming language provides several built-in functions to
handle errors during file operations. The file error handling
int bad()
It returns a non-zero (true) value if an invalid operation is attempted or an
unrecoverable error has occurred. Returns zero if it may be possible to recover
from any other error reported and continue operations.
int fail( )
It returns a non-zero (true) value when an input or output operation has
failed.
int good()
It returns a non-zero (true) value when no error has occurred; otherwise
returns zero (false).
int eof( )
It returns a non-zero (true) value when end-of-file is encountered while
reading; otherwise returns zero (false).
int bad( )
The bad( ) function returns a non-zero (true) value if an invalid operation is
attempted or an unrecoverable error has occurred. Returns zero if it may be
possible to recover from any other error reported and continue operations.
Example Program
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("my_file.txt", ios::out);
string data;
file>> data;
if(!file.bad()){
cout<< "Operation not success!!!" <<endl;
cout<< "Status of the badbit: " << file.bad() << endl;
}
else {
cout<< "Data read from file - " << data << endl;
}
return 0;
}
Output

Command Line Argument in C++


These values are called command line arguments and many times they are
important for your program especially when you want to control your program
from outside instead of hard coding those values inside the code.
The command line arguments are handled using main() function
arguments where argc refers to the number of arguments passed, and argv[] is a
pointer array which points to each argument passed to the program.
Syntax:
int main(int argc, char *argv[]) { /* ... */ }
or
int main(int argc, char **argv) { /* ... */ }
Arguments
● argc (ARGument Count) is an integer variable that stores the number of
command-line arguments passed by the user including the name of the
program. So if we pass a value to a program, the value of argc would be 2 (one
for argument and one for program name)
● The value of argc should be non-negative.
● argv (ARGument Vector) is an array of character pointers listing all the
arguments.
● If argc is greater than zero, the array elements from argv[0] to argv[argc-1]
will contain pointers to strings.
● argv[0] is the name of the program , After that till argv[argc-1] every element
is command -line arguments.

Properties of Command Line Arguments:


1. They are passed to the main() function.
2. They are parameters/arguments supplied to the program when it is invoked.
3. They are used to control programs from outside instead of hard coding those
values inside the code.
4. argv[argc] is a NULL pointer.
5. argv[0] holds the name of the program.
6. argv[1] points to the first command line argument and argv[argc-1] points to
the last argument.
Example Program
#include <stdio.h>
int main( int argc, char *argv[] ) {
printf("Program name %s\n", argv[0]);
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
UNIT -5
C++ Templates

A C++ template is a powerful feature added to C++. It allows you to define the
generic classes and generic functions and thus provides support for generic
programming. Generic programming is a technique where generic types are used
as parameters in algorithms so that they can work for a variety of data types.

Templates can be represented in two ways:

o Function templates
o Class templates

Function Templates:
We can define a template for a function. For example, if we have an add()
function, we can create versions of the add function for adding the int, float or
double type values.

Generic functions use the concept of a function template. Generic


functions define a set of operations that can be applied to the various
types of data.
The type of the data that the function will operate on depends on the type
of the data passed as a parameter.
For example, Quick sorting algorithm is implemented using a generic
function, it can be implemented to an array of integers or array of floats.
A Generic function is created by using the keyword template. The template
defines what function will do.

Syntax

template< class Ttype> ret_type func_name(parameter_list)

// body of function.

Ttype: It is a placeholder name for a data type used by the function. It is used
within the function definition. It is only a placeholder that the compiler will
automatically replace this placeholder with the actual data type.

Example of a function template:

#include <iostream>
using namespace std;
template<class T> T add(T &a,T &b)
{
T result = a+b;
return result;
}
int main()
{
int i =2;
int j =3;
float m = 2.3;
float n = 1.2;
cout<<"Addition of i and j is :"<<add(i,j);
cout<<'\n';
cout<<"Addition of m and n is :"<<add(m,n);
return 0;
}
Output:
Addition of i and j is :5
Addition of m and n is :3.5

Function Templates with Multiple Parameters

Syntax
template<class T1, class T2,.....>
return_type function_name (arguments of type T1, T2....)
{
// body of function.
}

CLASS TEMPLATE

Class Template can also be defined similarly to the Function Template. When a
class uses the concept of Template, then the class is known as generic class.

Syntax

template<class Ttype>

class class_name

}
Ttype is a placeholder name which will be determined when the class is
instantiated. We can define more than one generic data type using a comma-
separated list. The Ttype can be used inside the class body.

create an instance of a class

class_name<type> ob;
where class_name: It is the name of the class.
type: It is the type of the data that the class is operating on.
Example Program
#include <iostream>
using namespace std;
template<class T>
class A
{
public:
T num1 = 5;
T num2 = 6;
void add()
{
std::cout << "Addition of num1 and num2 : " << num1+num2<<std::endl;
}
};
int main()
{
A<int> d;
d.add();
return 0;
}
Output:
Addition of num1 and num2 : 11

CLASS TEMPLATE WITH MULTIPLE PARAMETERS

Syntax
template<class T1, class T2, ......>
class class_name
{
// Body of the class.
}

Standard Template Library (STL)


The Standard Template Library (STL) is a set of C++ template classes to
provide common programming data structures and functions such as lists, stacks,
arrays, etc. It is a library of container classes, algorithms, and iterators. It is a
generalized library and so, its components are parameterized. Working
knowledge of template classes is a prerequisite for working with STL.
The C++ Standard Template Library (STL) is a collection of algorithms, data
structures, and other components that can be used to simplify the development
of C++ programs. The STL provides a range of containers, such as vectors, lists,
and maps, as well as algorithms for searching, sorting and manipulating data.

Key components of the STL include:

1. Containers: The STL provides a range of containers, such as vector, list, map,
set, and stack, which can be used to store and manipulate data.
2. Algorithms: The STL provides a range of algorithms, such as sort, find, and
binary_search, which can be used to manipulate data stored in containers.
3. Iterators: Iterators are objects that provide a way to traverse the elements of
a container. The STL provides a range of iterators, such as forward_iterator,
bidirectional_iterator, and random_access_iterator, that can be used with
different types of containers.
4. Function Objects: Function objects, also known as functors, are objects that
can be used as function arguments to algorithms. They provide a way to pass a
function to an algorithm, allowing you to customize its behavior.
5. Adapters: Adapters are components that modify the behavior of other
components in the STL. For example, the reverse_iterator adapter can be used
to reverse the order of elements in a container.

1. Algorithms

The header algorithm defines a collection of functions specially designed to be


used on a range of elements. They act on containers and provide means for
various operations for the contents of the containers.

Algorithm
● Sorting
● Searching
● Important STL Algorithms
● Useful Array algorithms
● Partition Operations
2. Functors
The STL includes classes that overload the function call operator. Instances
of such classes are called function objects or functors. Functors allow the
working of the associated function to be customized with the help of parameters
to be passed. Must Read – Functors

3. Containers

Containers or container classes store objects and data. There are in total seven
standards “first-class” container classes and three container adaptor classes and
only seven header files that provide access to these containers or container
adaptors.

Classification of containers :

o Sequence containers
o Associative containers
o Derived containers

Sequence containers
● array: Static contiguous array (class template)
● vector: Dynamic contiguous array (class template)
● deque: Double-ended queue (class template)
● forward_list: Singly-linked list (class template)
● list: Doubly-linked list (class template)
Container Adaptors: provide a different interface for sequential containers.
● stack: Adapts a container to provide stack (LIFO data structure) (class
template).
● queue: Adapts a container to provide queue (FIFO data structure) (class
template).
● priority_queue: Adapts a container to provide priority queue (class
template).
Associative Containers: implement sorted data structures that can be quickly
searched (O(log n) complexity).
● Set: Collection of unique keys, sorted by keys
(class template)
● Map: Collection of key-value pairs, sorted by keys, keys are unique (class
template).
● multiset: Collection of keys, sorted by keys (class template)
● multimap: Collection of key-value pairs, sorted by keys
(class template)
Unordered associative containers
Unordered associative containers implement unsorted (hashed) data
structures that can be quickly searched (O(1) amortized, O(n) worst-case
complexity).

● unordered_set: Collection of unique keys, hashed by keys. (class template)


● unordered_map: Collection of key-value pairs, hashed by keys, keys are
unique. (class template)
● unordered_multiset: Collection of keys, hashed by keys (class template)
● unordered_multimap: Collection of key-value pairs, hashed by keys (class
template)
Example Program
#include <vector>
using namespace std;
int main()
{
vector<int> numbers = {1, 100, 10, 70, 100};
cout << "Numbers are: ";
for(auto &num: numbers) {
cout << num << ", ";
}
return 0;
}

Iterators
o Iterators are used to traverse from one element to another element, a
process is known as iterating through the container.
o The main advantage of an iterator is to provide a common interface for all
the containers type.
o Iterators make the algorithm independent of the type of the container
used.
o Iterators provide a generic approach to navigate through the elements of a
container.

o Iterators are pointer-like entities used to access the individual elements in


a container.
o Iterators are moved sequentially from one element to another element.
This process is known as iterating through a container.
o Iterator contains mainly two functions:

Syntax
<ContainerType> :: iterator;
<ContainerType> :: const_iterator;

Operations Performed on the Iterators:


o Operator (*) : The '*' operator returns the element of the current position
pointed by the iterator.
o Operator (++) : The '++' operator increments the iterator by one. Therefore, an
iterator points to the next element of the container.
o Operator (==) and Operator (!=) : Both these operators determine whether the
two iterators point to the same position or not.
o Operator (=) : The '=' operator assigns the iterator.

begin(): The member function begin() returns an iterator to the first element of the
vector.

end(): The member function end() returns an iterator to the past-the-last element of a
container.

Iterator Categories
Iterators are mainly divided into five categories:

1. Input iterator:
o An Input iterator is an iterator that allows the program to read the
values from the container.
o Dereferencing the input iterator allows us to read a value from the
container, but it does not alter the value.
o An Input iterator is a one way iterator.
o An Input iterator can be incremented, but it cannot be decremented.
2. Output iterator:
o An output iterator is similar to the input iterator, except that it allows
the program to modify a value of the container, but it does not allow to
read it.
o It is a one-way iterator.
o It is a write only iterator.
3. Forward iterator:
o Forward iterator uses the ++ operator to navigate through the
container.
o Forward iterator goes through each element of a container and one
element at a time.
4. Bidirectional iterator:
o A Bidirectional iterator is similar to the forward iterator, except that it
also moves in the backward direction.
o It is a two way iterator.
o It can be incremented as well as decremented.
5. Random Access Iterator:
o Random access iterator can be used to access the random element of a
container.
o Random access iterator has all the features of a bidirectional iterator,
and it also has one more additional feature, i.e., pointer addition. By
using the pointer addition operation, we can access the random
element of a container.

Example Program

#include <iostream>
#include<iterator>
#include<vector>
using namespace std;
int main()
{
std::vector<int> v{1,2,3,4,5};
vector<int>::iterator itr;
for(itr=v.begin();itr!=v.end();itr++)
{
std::cout << *itr <<" ";
}
return 0;
}
Output:
12345

Advantages of the C++ Standard Template Library (STL):


1. Reusability: One of the key advantages of the STL is that it provides a way to
write generic, reusable code that can be applied to different data types. This
can lead to more efficient and maintainable code.
2. Efficient algorithms: Many of the algorithms and data structures in the STL
are implemented using optimized algorithms, which can result in faster
execution times compared to custom code.
3. Improved code readability: The STL provides a consistent and well-
documented way of working with data, which can make your code easier to
understand and maintain.
4. Large community of users: The STL is widely used, which means that there is
a large community of developers who can provide support and resources, such
as tutorials and forums.

Disadvantages of the C++ Standard Template Library (STL):

1. Learning curve: The STL can be difficult to learn, especially for beginners, due
to its complex syntax and use of advanced features like iterators and function
objects.
2. Lack of control: When using the STL, you have to rely on the implementation
provided by the library, which can limit your control over certain aspects of
your code.
3. Performance: In some cases, using the STL can result in slower execution
times compared to custom code, especially when dealing with small amounts
of data.

Exception Handling

An exception is a problem that arises during the execution of a program. A C++


exception is a response to an exceptional circumstance that arises while a
program is running, such as an attempt to divide by zero.
Exception handling in C++ is built on three keywords: try, catch, and throw.
throw: A program throws an exception when a problem is detected which is done
using a keyword "throw". catch: A program catches an exception with
an exception handler where programmers want to handle the anomaly.

Exceptions provide a way to transfer control from one part of a program to


another. C++ exception handling is built upon three keywords: try,
catch, and throw.
● throw − A program throws an exception when a problem shows up. This is
done using a throw keyword.
● catch − A program catches an exception with an exception handler at the
place in a program where you want to handle the problem.
The catch keyword indicates the catching of an exception.
● try − A try block identifies a block of code for which particular exceptions
will be activated. It's followed by one or more catch blocks.

Assuming a block will raise an exception, a method catches an exception


using a combination of the try and catch keywords
Syntax

try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {
// catch block
}
Throwing Exceptions

Exceptions can be thrown anywhere within a code block


using throw statement. The operand of the throw statement determines a type
for the exception and can be any expression and the type of the result of the
expression determines the type of exception thrown.

double division(int a, int b)


{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}

Catching Exceptions
The catch block following the try block catches any exception. You can
specify what type of exception you want to catch and this is determined by the
exception declaration that appears in parentheses following the keyword catch.

Try
{
// protected code
}
catch()
{
// code to handle ExceptionName exception
}

Example Program

#include <iostream>
using namespace std;
double division(int a, int b) {
if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}
int main ()
{
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout<< z << endl;
}
catch (const char* msg)
{
cerr<< msg << endl;
}
return 0;
}
C++ Exception Classes

Exception Description
This is an exception and the parent class of all standard C++
std::exception
exceptions.
std::bad_alloc This exception is thrown by a new keyword.
std::bad_cast This is an exception thrown by dynamic_cast.
std::bad_exception A useful device for handling unexpected exceptions in C++ programs.
std::bad_typeid An exception thrown by typeid.
std::logic_error This exception is theoretically detectable by reading code.
This is an exception thrown after using a mathematically invalid
std::domain_error
domain.
std::invalid_argument An exception thrown for using invalid arguments.
std::length_error An exception thrown after creating a big std::string.
std::out_of_range Thrown by at method.
std::runtime_error This is an exception that cannot be detected via reading the code.
Exception Description
This exception is thrown after the occurrence of a mathematical
std::overflow_error
overflow.
This exception is thrown when you attempt to store an out-of-range
std::range_error
value.
An exception thrown after the occurrence of mathematical
std::underflow_error
underflow.

Types of exceptions

1. Standard exceptions

These exceptions are a part of the C++ Standard Library and are defined in
the <exception> header. They are intended to provide a standard set of exception
classes for use in C++ programs and are designed to represent a wide range of
error conditions that may occur during the execution of a program. The standard
exceptions include std::logic_error,

which represents errors resulting from an application’s logic (e.g., an


invalid argument passed to a function), and std::runtime_error, which represents
errors that occur due to external factors (e.g., a file not found).

2. Derived exceptions

These exceptions are derived from standard exceptions. They provide a


more specific indication of the type of error. For example, std::out_of_range is
derived from std::logic_error and is used to indicate that an index or a value is
out of the acceptable range for a container or an algorithm.
3. User-defined exceptions

The user in the application code defines these exceptions. They can be
derived from standard exceptions or a user-defined base class. User-defined
exceptions allow the programmer to indicate errors specific to the application
rather than relying on standard exceptions.
Example of User Define Exception

#include <iostream>
using namespace std;
class demo
{
};
int main()
{
try {
throw demo();
}
catch (demo d)
{
cout << "Caught exception of demo class \n";
}
}
Output:

Caught exception of demo class


Finally Block in Exception handling

The try-finally statement is a Microsoft-specific extension that supports


structured exception handling in the C and C++ languages.

Try-finally statement:
Syntax
C++Copy
// . . .
__try
{
// guarded code
}
__finally
{
// termination code
}
// . . .

You might also like