0% found this document useful (0 votes)
10 views

Oop Notes

This document provides an overview of object-oriented programming concepts including: 1) It compares procedural programming and object-oriented programming, noting that OOP focuses on data security and dividing programs into objects rather than functions. 2) Key concepts of OOP like classes, objects, encapsulation, abstraction, inheritance and polymorphism are defined. A class is a blueprint for an object, and objects are instances of classes. 3) Encapsulation binds together data and functions that operate on the data, and leads to data abstraction or hiding. Abstraction displays only essential information and hides details. 3) Polymorphism means a message can take different forms - an operation may exhibit different behaviors depending

Uploaded by

dkthehell007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Oop Notes

This document provides an overview of object-oriented programming concepts including: 1) It compares procedural programming and object-oriented programming, noting that OOP focuses on data security and dividing programs into objects rather than functions. 2) Key concepts of OOP like classes, objects, encapsulation, abstraction, inheritance and polymorphism are defined. A class is a blueprint for an object, and objects are instances of classes. 3) Encapsulation binds together data and functions that operate on the data, and leads to data abstraction or hiding. Abstraction displays only essential information and hides details. 3) Polymorphism means a message can take different forms - an operation may exhibit different behaviors depending

Uploaded by

dkthehell007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 122

INFORMATION TECHNOLOGY

DEPARTMENT

COURSE –OBJECT ORIENTED PROGRAMMING(22316)

SEMESTER –III CLASS- IF3I/CO3I-A/CO3I-B

LECTURER – MISS.SHANTI TULSHIDAS SHIRSAT.


Chapter No1:Principles of Object Oriented Programming oop(22316)

Chapter1
Principles of object oriented programming
• pop vs oop:

POP OOP

Basic Procedure/Structure oriented . Object oriented.

Approach Top-down. Bottom-up.

Basis Main focus is on "how to get Main focus is on 'data

the task done" i.e. on the security'. Hence, only

procedure or structure of a objects are permitted to

program . access the entities of a

class.

Division Large program is divided into Entire program is divided

units called functions. into objects.

Entity accessing No access specifier observed. Access specifier are

mode "public", "private",

"protected".

Notes By:Miss shanti tulshidas shirsat Page 1 of 18


Chapter No1:Principles of Object Oriented Programming oop(22316)

Overloading or Neither it overload functions It overloads functions,

Polymorphism nor operators. constructors, and

operators.

Inheritance Their is no provision of Inheritance achieved in

inheritance. three modes public private

and protected.

Data hiding & There is no proper way of Data is hidden in three

security hiding the data, so data is modes public, private, and

insecure protected. hence data

security increases.

Data sharing Global data is shared among the Data is shared among the

functions in the program. objects through the

member functions.

Friend functions No concept of friend function. Classes or function can

or friend classes become a friend of another

class with the keyword

Notes By:Miss shanti tulshidas shirsat Page 2 of 18


Chapter No1:Principles of Object Oriented Programming oop(22316)

"friend".

Note: "friend" keyword is

used only in c++

Virtual classes or No concept of virtual classes . Concept of virtual function

virtual function appear during inheritance.

Example C, VB, FORTRAN, Pascal C++, JAVA, VB.NET,

C#.NET.

• . 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.

Notes By:Miss shanti tulshidas shirsat Page 3 of 18


Chapter No1:Principles of Object Oriented Programming oop(22316)

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.
For Example: Consider the Class of Cars. There may be many cars with different
names and brand but all of them will share some common properties like all of
them will have 4 wheels, Speed Limit, Mileage range etc. So here, Car is the class
and wheels, speed limits, mileage are their properties.
• 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 behaviours.

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.Object take up space in memory and have an associated address .

Notes By:Miss shanti tulshidas shirsat Page 4 of 18


Chapter No1:Principles of Object Oriented Programming oop(22316)

When a program is executed the objects interact by sending messages to one


another.

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.
Consider a real-life example of encapsulation, in a company, there are different
sections like the accounts section, finance section, sales section etc. The finance
section handles all the financial transactions and keeps records of all the data
related to finance. Similarly, the sales section handles all the sales-related activities
and keeps records of all the sales. Now there may arise a situation when for some
reason an official from the finance section needs all the data about sales in a
particular month. In this case, he is not allowed to directly access the data of the
sales section. He will first have to contact some other officer in the sales section
and then request him to give the particular data. This is what encapsulation is. Here
the data of the sales section and the employees that can manipulate them are
wrapped under a single name “sales section”.

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 is one of the most essential and important features
of object-oriented programming in C++. Abstraction means displaying only
essential information and hiding the details. Data abstraction refers to providing
only essential information about the data to the outside world, hiding the
background details or implementation.
Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerators will increase the speed of the car or applying brakes will
stop the car but he does not know about how on pressing accelerator the speed is
actually increasing, he does not know about the inner mechanism of the car or the
implementation of accelerator, brakes etc in the car. This is what abstraction is.

Notes By:Miss shanti tulshidas shirsat Page 5 of 18


Chapter No1:Principles of Object Oriented Programming oop(22316)

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, some times
there are 2 integers, some times 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.

• 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.

Notes By:Miss shanti tulshidas shirsat Page 6 of 18


Chapter No1:Principles of Object Oriented Programming oop(22316)

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.

• . Applications of Object Oriented Programming

Main application areas of OOP are:

• User interface design such as windows, menu.


• Real Time Systems
• Simulation and Modeling
• Object oriented databases
• AI and Expert System
• Neural Networks and parallel programming
• Decision support and office automation systems etc.

• Structure of C++:

Notes By:Miss shanti tulshidas shirsat Page 7 of 18


Chapter No1:Principles of Object Oriented Programming oop(22316)

Notes By:Miss shanti tulshidas shirsat Page 8 of 18


Chapter No1:Principles of Object Oriented Programming oop(22316)

Notes By:Miss shanti tulshidas shirsat Page 9 of 18


Chapter No1:Principles of Object Oriented Programming oop(22316)

Notes By:Miss shanti tulshidas shirsat Page 10 of 18


Chapter No1:Principles of Object Oriented Programming oop(22316)

• Simple C++ program:

// Simple C++ program to display "Hello World"


// Header file for input output functions
#include<iostream>
// main function -
// where the execution of program begins
int main()
{
// prints hello world
cout<<"Hello World";

Notes By:Miss shanti tulshidas shirsat Page 11 of 18


Chapter No1:Principles of Object Oriented Programming oop(22316)

return 0;
}

• Control Structure :Decision making statements and loops

• Scope resolution operator:


In C++, scope resolution operator is ::

It is used for following purposes.

1) To access a global variable when there is a local variable with same


name:

Notes By:Miss shanti tulshidas shirsat Page 12 of 18


Chapter No1:Principles of Object Oriented Programming oop(22316)

#include<iostream>

int x; // Global x

int main()

int x = 10; // Local x

cout << "Value of global x is " << ::x;

cout << "\nValue of local x is " << x;

return 0;

2) To define a function outside a class.

#include<iostream.h>

class A

public:

// Only declaration

void fun();

};

// Definition outside class using ::

void A::fun()

Notes By:Miss shanti tulshidas shirsat Page 13 of 18


Chapter No1:Principles of Object Oriented Programming oop(22316)

cout << "fun() called";

int main()

A a;

a.fun();

return 0;

➢ Memory management operators:


• C++ Memory Management: new and delete
• Arrays can be used to store multiple homogenous data but there are serious
drawbacks of using arrays.
• You should allocate the memory of an array when you declare it but most of
the time, the exact memory needed cannot be determined until runtime.
• The best thing to do in this situation is to declare an array with maximum
possible memory required (declare array with maximum possible size
expected).
• The downside to this is unused memory is wasted and cannot be used by any
other programs.
• To avoid wastage of memory, you can dynamically allocate memory
required during runtime using new and delete operator in C++.

Notes By:Miss shanti tulshidas shirsat Page 14 of 18


Chapter No1:Principles of Object Oriented Programming oop(22316)

• New operator:

A new operator is used to create the object while a delete operator is used to delete
the object. When the object is created by using the new operator, then the object
will exist until we explicitly use the delete operator to delete the object. Therefore,
we can say that the lifetime of the object is not related to the block structure of the
program.

Syntax

1. pointer_variable = new data-type

The above syntax is used to create the object using the new operator. In the above
syntax, 'pointer_variable' is the name of the pointer variable, 'new' is the
operator, and 'data-type' defines the type of the data.

Example 1:

1. int *p;
2. p = new int;

In the above example, 'p' is a pointer of type int.

Example 2:

1. float *q;
2. q = new float;

In the above example, 'q' is a pointer of type float.

• Delete operator:

When memory is no longer required, then it needs to be deallocated so that the


memory can be used for another purpose. This can be achieved by using the delete
operator, as shown below:

1. delete pointer_variable;

In the above statement, 'delete' is the operator used to delete the existing object,
and 'pointer_variable' is the name of the pointer variable.

Notes By:Miss shanti tulshidas shirsat Page 15 of 18


Chapter No1:Principles of Object Oriented Programming oop(22316)

In the previous case, we have created two pointers 'p' and 'q' by using the new
operator, and can be deleted by using the following statements:

1. delete p;
2. delete q;

➢ Array ,String and Structure in C++:


Array:

An array in C or C++ is a collection of items stored at contiguous memory


locations and elements can be accessed randomly using index of an array.
They are used to store similar type of elements as in the data type must be
the same for all elements. They can be used to store collection of primitive
data types such as int, float, double, char, etc of any particular type.

String:
• Just like characters, strings in C++ are used to store letters and digits.
Strings can be referred to as an array of characters as well as an individual
data type.
• It is enclosed within double quotes, unlike characters which are stored
within single quotes. The termination of a string in C++ is represented by the
null character, that is, ‘\0’. The size of a string is the number of individual
characters it has.
• In C++, a string can be declared in the following ways:
• char name[30] = ‘’Hello!”; // The compiler reserves 30 bytes of memory for
the string.
• char name[] = “Hello!”; // The compiler reserves the required amount of
memory for the string.

Notes By:Miss shanti tulshidas shirsat Page 16 of 18


Chapter No1:Principles of Object Oriented Programming oop(22316)

• char name[30] = { ‘H’ , ’e’ , ’l’ , ’l’ , ’o’};; // This is how a string is
represented as a set of characters.
string name = “Hello” // The compiler reserves 32 bytes of memory

Structure:
A structure is a user-defined data type in C/C++. A structure is a collection of different
data types elements.

The ‘struct’ keyword is used to create a structure. The general syntax to create a
structure is as shown below:

struct structureName{
member1;
member2;
member3;
.
.
.
memberN;
};

struct structureName{
member1;
member2;
member3;
.
.
.
memberN;
};

Notes By:Miss shanti tulshidas shirsat Page 17 of 18


Chapter No1:Principles of Object Oriented Programming oop(22316)

Structures in C++ can contain two types of members:


• Data Member: These members are normal C++ variables. We can create a
structure with variables of different data types in C++.
• Member Functions: These members are normal C++ functions. Along with
variables, we can also include functions inside a structure declaration.

struct student

int roll_no;

char name[20];

float marks;

void get();

void show();

};

Notes By:Miss shanti tulshidas shirsat Page 18 of 18


Chapter No2:Classes and Objects oop(22316)

Chapter no2
Classes and Objects
2.1 Classes and Objects:
• Classes:

• A Class in C++ is a user defined type declared with keyword class


that has data and fu
(also called methods) as its members.
• A class (declared with keyword class) in C++ differs from a
structure (declared with ke-
struch as by default, members are private in a class while they are
public in a structure.
• A class is used to pack data members and member function
together,
The class has a mechanism to prevent direct access to its members,
which is the central
of object oriented programming
• Class specification has two parts:
1. Class declaration: Class declaration describes the type and scope
of its members.
2. Class Function Definition: It describes how the class functions
are implemented.
Syntax:
• class class_name
{
private:

Notes By:Miss shanti tulshidas shirsat Page 1 of 45


Chapter No2:Classes and Objects oop(22316)

Variable declarations;
Function declarations;
public:
Variable declarations;
Function declarations;

};

Example:

class person
{
char name[10]; //variable declaration
int age; Il private by default
public:
void getdata(); //function declaration
void putdata();
};

• Data members are usually declared as private and member


function as public
AS per the above syntax class_name is the name of the class.

Notes By:Miss shanti tulshidas shirsat Page 2 of 45


Chapter No2:Classes and Objects oop(22316)

The body of a class is enclosed Within braces and terminated


bya semicolon. The body contains the declarations of variables
and functions. These functions and variables are called as
members.

• Access Specifiers:
Acess specifiers idefine the access rights for the statements or
functions that follow it
until another access specifier or till the end of a class. The three
types of access specithers are
1. private
2.upublic
3.protected

Syntax

class Base
{
private:
// private members go here
public:
// public members go here
protected
// protected members go here
};

Notes By:Miss shanti tulshidas shirsat Page 3 of 45


Chapter No2:Classes and Objects oop(22316)

private:
• The members declared as "private" can be accessed only within the
same class and not from outside the class.
public:
• The members declared as "public" are accessible within the class
as well as from outside the class.
protected:
• The members declared as "protected" cannot be accessed from
outside the class, but can be accessed from a derived class. This is
used when inheritance is applied to the members of a class.

• Creating Objects:

• The definition of class does not define any objects but only
specifies what that class contains.
• Once class has been defined, we can create variables of that type
by using the class name.
• Objects can be defined in similarly way as structure is defined.

Syntax:
class name variable name;

• Let's say for the defined class Sample, objects for that class can be
defined as:
Example:

Notes By:Miss shanti tulshidas shirsat Page 4 of 45


Chapter No2:Classes and Objects oop(22316)

Sample obj1, obj2;

• Here, two objects (objl and obi2 of Sample class are defined.

• Memory has been assigned to objects.

• Accessing Class Memberss:

Example:
class Item
{
int number
float cost;
public:
void getdata(inta,float b);
void putdata(void);
};
void main0
{
Item x.y,y,z; //memory for xy,z is created
}

Notes By:Miss shanti tulshidas shirsat Page 5 of 45


Chapter No2:Classes and Objects oop(22316)

• Objects are nothing but class variables. x, y, z are called as


objects of type item. According to the requirement we can
create objects.
• Private data of class can be accessed only through the
member functions of that class. The main() cannot contain
statements that access number and cost directly.
• Syntax for calling member functionn

obiect name.function name (actual arquments);

• Example
x.qetdata(50,65.5):
xputdata0: //display the values of data members.

• Defining Member Function:

• Member functions can be defined in two places:


1.Outside the class definition
The member functions of a class can be defined outside
the class definitions. It is only declared inside the class but
defined outside the class. The general form of member
function definition outside the class definition is:
Syntax:
returntype class_name ::function_name(argument list)
{

Notes By:Miss shanti tulshidas shirsat Page 6 of 45


Chapter No2:Classes and Objects oop(22316)

function body
}

• Where symbol :: is a scope resolution operator


• In this, a programmer can declare as many functions as he
wants depending upon the need of a program. Once done
with it, a programmer can then define those functions outside
of a class using scope resolution operator i.e. (::).
• Advantage of having outside declaration is to have as many
functions as we want and we can define it anywhere in a
program.

Example: Program to add two numbers and displaying a


result.

• #include<iostream.h>
#include conio.h> Enter the value of a and b:
class Add
{
int a, b, total;

public:
void getdata();
void display():
};

void Add: getdata()


{
cout<<" \n Enter the value of a and b:";
cin>>a>>b;
}

Notes By:Miss shanti tulshidas shirsat Page 7 of 45


Chapter No2:Classes and Objects oop(22316)

void Add:: display()


{
total =a+b;
cout< <"n The sum of a and b="<<total;
}

void main ()
{
Add a;
a.getdata ();
a.display();
getch ();

2.Inside the class definition


• The member function of a class can be declared and defined
inside the class definition.

Syntax
class class_name
{
public:
return_type function_name(argument(s))
{
function body;
}

Example: Program to add two numbers and displaying a result.

Notes By:Miss shanti tulshidas shirsat Page 8 of 45


Chapter No2:Classes and Objects oop(22316)

#include<iostream.h>
#include<conio.h>
class Add
{

int a, b,total;
public:
void getdata0
{
cout<<,"\n Enter the value of a and b";
cin> >a>>b;
}
void display0
{
total a+b;
cout<<"\n the sum of a and b="<<total;
}

void main()
{
Add a;
a.getdata();
a.display():
getch();
}

Notes By:Miss shanti tulshidas shirsat Page 9 of 45


Chapter No2:Classes and Objects oop(22316)

• Memory Allocations for Objects:

• The memory şpace for object is allocated when they are


declared and not when the class is specified.
• Actually, the member functions are created and placed in
memory space only once when they are defined as a part of a
class definition.
• Since all the objects belonging to that class use the same
member fünctions, no separate space is allocated for member
functions.
• When the objects are created only space for member variable
is allocated separately for each object.
• Separate memory locations for the objects are essential
because the member variables will hold different data values
for different objects.

Notes By:Miss shanti tulshidas shirsat Page 10 of 45


Chapter No2:Classes and Objects oop(22316)

2.2 Static data members,Static member function,Friend function:

Static data members :


• Members that are associated with the class itself rather than
individual objects are called as static members
• A data member of a class can be made static. A static variable is
initialized to zero when the objects are created
• Characteristics of Static member variable
• It is initialized to zero when the first object of its class is
created.
• It has only one copy for entire class and is shared by all the
objects of that class.
• It is visible only within class but the lifetime is for the entire
program.
• It has to be declared outside the class using scope resolution
operator with name of class.

• Syntax:
A) For defining static member variable inside the
class:
static data_type variable name; Example:
static int count;

B) For defining static variable outside the class:

Notes By:Miss shanti tulshidas shirsat Page 11 of 45


Chapter No2:Classes and Objects oop(22316)

data-type class-name: static-variable

Example: int Test,.: count;

• The static variable must be declared in a class with a keyword


static
Example:
class item
{
static int count; /count is static
public:
};

int item : count; //definition of static data member

Program1: static data members

#include<iostream.h>
#include<conió.h>
class item
{

static int count; //count is static


int number;

Notes By:Miss shanti tulshidas shirsat Page 12 of 45


Chapter No2:Classes and Objects oop(22316)

public:

void getdata(int a)
{
number=a;
count++
}
void getcount(void)
{
cout<<"count:";
cout< <count< <"\n":
}
};
int item ::count //count defined

void main0
{
item w,x,y //count is initialized to zero
w.getcount(); //display count
x.getcount();
y.getcount(): //getting data into object a
w.getdata(100); //getting data into object b
x.getdata(200);
y.getdata(300); //getting data int object c
cout<<"After reading data "<<"\n
w.getcount( );
x.getcount():

Notes By:Miss shanti tulshidas shirsat Page 13 of 45


Chapter No2:Classes and Objects oop(22316)

y.getcount():
getch();
}

Static Member Function :

• Static member function can have access to only other static


variable or functions, declared in tne same class.
• It can be called using the class name instead of object.
• It can be declared inside the class with static keyword placed
before return type.
• A static member function does not have this pointer. They may
not be virtual. There cant be static and non static version of the
same function.

• Syntax

static return_type function_name()


{
}

• Syntax for calling static function

Notes By:Miss shanti tulshidas shirsat Page 14 of 45


Chapter No2:Classes and Objects oop(22316)

class_name::function_name0;

• Program: static member function implementation

#include <iostream.h>
class test
{
int code; //static member variable
static int count;

public:

void setcode()
{
code=++count;
}

void showcode()
{
cout<<"Object number:"<<code< <end;
}

static void showcount() // static member function

Notes By:Miss shanti tulshidas shirsat Page 15 of 45


Chapter No2:Classes and Objects oop(22316)

{
cout<<"Count:"< <count< <endl;
}
};
int test::count //definition of static data member
void main0
{
test t1,t2;
t1.setcode ();
t2.setcode ():

test:showcount(); //accessing static function


test t3;
t3.setcode();
test:showcount0:
t1.showcode();
t2.showcode();
t3.showcode():
getch();
}

Friend Function:
• A friend function of a class is defined outside that class' scope.
• It has the right to access all private and protected members of
class.

Notes By:Miss shanti tulshidas shirsat Page 16 of 45


Chapter No2:Classes and Objects oop(22316)

• Even though the prototypes for friend functions appear in the


class definition, friends are not member functions.
• A friend can be a function, function template, or member
function, or a class or class
template, in which case the entire class and all of its members
are friends.
• Characteristics of friend function:
• It is not in the scòpe of the class to which it has
been declared.as friend.
• It can be invoked like normal function without the help of any
object.
• It cannot be called using the object of that class.
• Unlike member functions ,it cannot access the member names
directly and has to use an object name and dot membership
operator with each member name.(e.g. A.m)
• It can be declared either in the public or the private part of class
without affecting its meaning
• Usually it has the objects as arguments.

• Syntax:

class class_name
{
public:

//friend function declaration

Notes By:Miss shanti tulshidas shirsat Page 17 of 45


Chapter No2:Classes and Objects oop(22316)

friend returntype functionname(parameters)


};

return type functionname(parameter) //friend


function definition
{
}

Write a program to find the mean value of a given number using friend
function. [W-13

#include<iostream.h> O
#include< conio.h>
class base
{

int val1,val2;
public:
void get( )
{
cout<< "Enter two values:";
cin>> val1>>yal2;

friend float mean(base ob) //friend function declaration


};
float mean(base ob) //friend function definition
{

Notes By:Miss shanti tulshidas shirsat Page 18 of 45


Chapter No2:Classes and Objects oop(22316)

return float(ob.val1+ob.val2)/2;
}
void main()
{
clrscrO:
base ob;
ob.get0:
cout<<"\n Mean value is:"< <mean(obj); //call to friend function
getch0:
}

2.3 Array:
2.3.1Array of objects:
• Array is a collection of variables of same data; similarly array of
objects is collection of more than object of same class.
• We can have arrays of variables that are of the type class. Such
variables are called array of objects.

• Syntax:
class class_name
{
}object name[sizej;

Notes By:Miss shanti tulshidas shirsat Page 19 of 45


Chapter No2:Classes and Objects oop(22316)

OR
Class class_name
{

};
void main()
{
class name objectname[size];
}

Example:
class employee
{
char name[30];
float age;
public:
void getdata();
void putdata0;
};

Eg. Employee managers[3]; //array of manager

In above declaration, the array managers contains three objects


(managers), namely,managers[o], managers[1] and managers[2],
of the type employee class.
Since, an array of objects behaves like any other array, we can
use the usual array-accessing, methods to access individual
elements and then the dot member opèrator to access the member
functions.
For example, the statement
manager[i].putdata();

Notes By:Miss shanti tulshidas shirsat Page 20 of 45


Chapter No2:Classes and Objects oop(22316)

2.3.2 Objects as Function Arguments in c++


• Similar to variables, object can be passed to function.
Functions may have object as argument using two ways:
1) A copy of entire object is passed to the function called as
pass by value
2) Only the-objert is passed to the function called pass by
reference

• The objects of a class can be passed as arguments to member


functions as well as non member functions either by value or by
reference.
Pass by value:
• When an object is passed by value, a copy of the actual object is
created inside the function.
• A copy of object (actual object) is sent to function and assigned to
the object of called function(formal object).
• Both actual and formal copies-of objects are stored at different
memory locations. Hence changes made in formal object are not
reflected to actual object.

Notes By:Miss shanti tulshidas shirsat Page 21 of 45


Chapter No2:Classes and Objects oop(22316)

• This copy is destroyed when the function terminates. Moreover,


any changes made to the copy of the object inside the function are
not reflected in the actual object.
Pass by reference:
• On the other hand, in pass by reference, only a reference to that
object (not the entire object) is passed to the function. Thus, the
changes made to the object within the function are also reflected in
the actual object.


Example: Write a program for addition of two objects. IS-10, W-
13]

#include<iostream.h>
#include <conio.h>
class Addition
{

int a,b;
public:
void getno(intx,int y)
{
a-x
b=y
}

Notes By:Miss shanti tulshidas shirsat Page 22 of 45


Chapter No2:Classes and Objects oop(22316)

void putno()
{
cout<<"first no:"< <a;
cout<<"second no:"< <b;
}
void sum(Addition, Addition); //objects as function argument

void sum(Addition A1,Addition A2)


{
a=Al.a+A2.a;
b A1.b+A2.b;
}
void main()
{
Addition al, a2, a3;
clrscrO:
al.getno(2, 5);
a2.getno(2, 5);
a3.sum(A1, A2); //A3=Al+A2
cout<<"A1:"
al.putno();

cout<<"A2:"
a2.putno();
cout<<"A3:"

Notes By:Miss shanti tulshidas shirsat Page 23 of 45


Chapter No2:Classes and Objects oop(22316)

a3.putno():
getch():
}

2.4Concepts of Constructors:
• A Constructor is a special member function of a class whose task is
to initialize the objects of its class.
• Uniike normal functions, constructors have specific rules for how
they must be named:

1.A Constructor will have exact same name as the Class.


2. It does not have any return type at all, not even void.

Notes By:Miss shanti tulshidas shirsat Page 24 of 45


Chapter No2:Classes and Objects oop(22316)

• Constructor is invoked when object of its class is created; it


constructs the value of data members of the class.

Syntax of constructor

class class_name
{
Access Specifier:
Member variables;
Member functions;
public:
Class name( arguments) // Constructor name is same as class
name
{
Body of constructor;
}

• There is no need to declare any statement to invoke constructor. It


gets invoked automatically whenever object of its class is created.
• Constructors can be defined either inside the class definition or
outside class definition using class name and scope resolution:
operator.
e.g.

class circle //Specify a class


{
private:
float radius; // Class data member

Notes By:Miss shanti tulshidas shirsat Page 25 of 45


Chapter No2:Classes and Objects oop(22316)

public:
circle () // default constructor
{
radius=0;
}
int main()
{
circle c1; // default constructor called
return 0;
}

Following are the characteristics/properties of constructors:


1. Constructors have same name as that of class they belong to.
2. They should be declared in the public section.
3. They are automatically invoked whenever objects are created.
4. They have no return types not even void, neither can they return
values.
5. They cannot be inherited but called by Derived Class.
6. They cannot be virtual.
7. We cannot refer to their addresses.
8. They can have default arguments like normal functions.
9. They make implicit calls to new operator and delete operator when
memory allocation is
néeded.
10. An object with a constructor can't member of union.

Types of Constructor:
There are three types of constructors
1. Default Constructor
2. Parameterized Constructor

Notes By:Miss shanti tulshidas shirsat Page 26 of 45


Chapter No2:Classes and Objects oop(22316)

3 Copy Constructor

1 Default_Constructor: A constructor that accepts no parameters is


known as default
constructor. If no constructor is defined then the compiler supplies a
'default constructor'.

circle() .
{
radius = 0;
}
2. Parameterized Constructor: A constructor that receives
arguments/parameters is called
parameterized constructor'
circle(double r)
{
radius =r;
}

3. Copy Constructor: A constructor that initializes an object using


values of another object
passed to it as parameter is called 'copy constructor. It creates the
copy of the passed
object .
circle(circle &t)
{
radius t.radius;
}

Notes By:Miss shanti tulshidas shirsat Page 27 of 45


Chapter No2:Classes and Objects oop(22316)

1. Default Constructoor
Default Constructoor is the constructor which doesn't take any
argument. It has no parameter.
Syntax

class_name ()
{
Constructor Definition
}

Example:

class Cube
{

int side;
public:
Cube()
{
side=10;
}

Notes By:Miss shanti tulshidas shirsat Page 28 of 45


Chapter No2:Classes and Objects oop(22316)

int main()
{
Cube c;
cout << c.side;
}
Note:
In this case, as soon as the object is Created the constructor is called
which initializes its data members.
A default constructor is so important for inialization of object
members, that even if we do not
define a constructor explicitly, the compier WIll provide a default
constructor implicitly.

2. Parameterized Constructor:
• Constructor which has arguments that constructor is called as'
Parameterized Constructor'.
• It is same as normal function take arguments just put arguments
in the constructor and use them to initialize objects.

Notes By:Miss shanti tulshidas shirsat Page 29 of 45


Chapter No2:Classes and Objects oop(22316)

• Syntax:
class class_name
{
Access Specifier
Member Variables;
Member Functions;
public: .
class-name(parameter1, parameter2,..,parameter n)
{
/ / Constructor code
}

Following is example of parameterized constructor program

class time
{
private:
int hrs, min, sec;

Notes By:Miss shanti tulshidas shirsat Page 30 of 45


Chapter No2:Classes and Objects oop(22316)

Public:
time ( int h, int m, int s) // <-- Parameterized constructor with three
arguments
{

hrs= h;
min=m;
sec =s;
}

void disp()
{
cout<<"HRS: "<<hrs<<endl;
cout<< "MIN: "<<min< <endl;
cout<<"SEC: "<<sec< <endl;
}
};

void main ()
{
cout<< "implicit cal:"<<endl;
time t1 (10, 20, 30): //implicit call
t1.disp();

cout<<"explicit call:"< <endl;


time t2 =time(100, 200, 300); //explicit call
t2.disp():
getch();
}

Notes By:Miss shanti tulshidas shirsat Page 31 of 45


Chapter No2:Classes and Objects oop(22316)

note:
Above program will pass initial value as arguments to constructor time
We can pass this values to constructor by two ways
1. By calling constructor implicitly:
time t1 (10, 20, 30);
2.By calling constructor explicitly:
time t2= time (100, 200, 300);

3. Copy constructor:

• A constructor which accept a reference to its own class as


parameter which is called as copy constructor'.
• Copy constructor is used to initialize one object from another of
the same type
Syntax for copy constructor

class name (class_name &obj)


{
// body of constructor
}

• Following Is example of copy constructor program:

#include<iostream.h>
#include<conio.h>
class abc
{
private:
int a,b;
public:

Notes By:Miss shanti tulshidas shirsat Page 32 of 45


Chapter No2:Classes and Objects oop(22316)

abc()
{
a= 2;
b =4;
}

abc(abc &X)
{
a= X.a
b =X.b;
}

void disp()
{
cout<<"a="<<a<<"b="< <b<<endi;
}

void main()
{
abc obj1;
obj1.disp():
abc obj2(obj1);
obj2.disp();
getch();
}

2.5 Overloaded Constructor: Multiple Constructors in a Class:

Notes By:Miss shanti tulshidas shirsat Page 33 of 45


Chapter No2:Classes and Objects oop(22316)

• We can declare number of different constructors in a single


program.
• Wen more than one constructor function is declared and defined in
a class, then the Constructors are overloaded.
• Constructor overloading is same as function overloading because
constructor is special function.

• Following syntax shows how we can declare multiple constructors


in a class.

class class name


{
Access Specifier:
Member Variables;
Member Functions

public:
class name() // default constructor
{
// Constructor code
}

class-name(parameter1, parameter2) /// parameterized


constructor

{
// Constructor code
}

class-name(classname &obj) //copy constructor

Notes By:Miss shanti tulshidas shirsat Page 34 of 45


Chapter No2:Classes and Objects oop(22316)

{
// Constructor code
}

};

Example:
#include <iostream.h> Output:
#include <conio.h>
class abc
{
public:
int a, b;

abc( ) // default constructor


{
a= b= 5;
}

abc(int x) // parameterized constructor with one parameter


value
{
a = b = X;
}

Notes By:Miss shanti tulshidas shirsat Page 35 of 45


Chapter No2:Classes and Objects oop(22316)

abc(int m, int n) // parameterized constructor with two parameter


{
a =m;
b=n;
}

Abc(abc &obj) // copy constructor


{
a = obj.a;
b= obj.b;
}

void disp()
{
Cout << "a= "< <a<<" b= "<<b<<"\n";
}

void main()
{
abc A;
abc A1(10);
abc A2(15, 20);
abc A3(A2);

cout <<"\nDefault constructor value:"


A.disp();
cout <<"\nSingle parameter parameterized constructor value:"
A1.disp();
cout << "\nTwo parameter parameterized constructor value:";

Notes By:Miss shanti tulshidas shirsat Page 36 of 45


Chapter No2:Classes and Objects oop(22316)

A2.disp();
cout << "\ncopy constructor value:";
A3.disp();

getch();
}

Constructor with default arguments:

• Constructor can define with default arguments.


• Similar to functions, it is also possible to declare constructors with
default arguments.
• It is possible to define constructor with default argument.
• For example, the constructor
AréaOfTriangle() can be declared as follow:
AreaOfTrianglefint a, int b 20)
• The default value of argument b is 20, then the statement

AreaOfTriangle a(10, 30); Assigns 10 to 'a' and 30 to 'b'


AreaOfTriangle a(10); Assigns 10 to 'a' and 20 to 'b'

• Here actual parameter overrides the default value.


• Following is the syntax of default argument constructor:
class class name
{
Access Specifier:
Member Variables;
Member Functions;
public:
class name(data_type = value)

Notes By:Miss shanti tulshidas shirsat Page 37 of 45


Chapter No2:Classes and Objects oop(22316)

{
// Constructor code
}
};

Following is a sample program of default constructor.


#include<conio.h>
#include<iostream.h>

class abc
{
int a; b
float b;

public:

abc (int x=10, float y=40)

Notes By:Miss shanti tulshidas shirsat Page 38 of 45


Chapter No2:Classes and Objects oop(22316)

a= x;
b =y;
}

void display()
{
cout<<"\n\n a: "<<a;
cout<<"n b: "<<b;
}
};

void main()
{
clrscrO:
abc obj
abc obj2(1,60);

cout<<"n Output using default constructor arguments:\n";


obj.display();

cout<<"n Output without default constructor arguments:\n";


obj2.display0:

getch();
}

Notes By:Miss shanti tulshidas shirsat Page 39 of 45


Chapter No2:Classes and Objects oop(22316)

Example2: Declare a class simple interest having data members as


principle amount, rate of interest,number of years. The constructor will
have default value of rate of interest as 11.5%. Accept this data for two
objects. Calculate and display simple interest for each object.

#include<conio.h>
#include <iostream.h>
class simpleinterest
{

private:
float principle, numberOfyears, rateOfinterest;

public: ,
simplehterest(float p, float n, float r = 11.5)
{
principle = p;
numberOtyears = n;
rateOflnterest= r;
}

void displaySimplelnterest0
{
float SI= (principle* numberOfyears *rateOfinterest)/100;
coute <<"n Simple Interest: " <<SI;
}
};
void main()

Notes By:Miss shanti tulshidas shirsat Page 40 of 45


Chapter No2:Classes and Objects oop(22316)

clrscr():
cout<<"nObj1 \n":
simpleinterest obji(1000,2);
obj1.displaySimplelnterest();

cout<<"\nObj2 :\n"
simplelnterest obj2(1000, 2, 10);
obj2.displaySimplelnterest();
getch();
}

2.6 Destructor:

• A destructor is a special member function that is called when the


lifetime of an object ends.
• Destructor is a special member function is used to destroy the
objects that have been created by constructor.
• Destructor will be invoked implicitly by the compiler upon exit
from the program to clean up the storage.
• Destructor is a special member function whose name is same as the
class name.
• Destructor is preceded by a tilde (-).
• Syntax of destructor:

Notes By:Miss shanti tulshidas shirsat Page 41 of 45


Chapter No2:Classes and Objects oop(22316)

~class name ()
{
// body of destructor
}

• Destructors have following characteristics:


1. Destructors have the same name as that of the class they belong
to preceded by ~ (tilde).
2. Similar to constructors, the destructórs do not have return type
and not even void.
3. Destructors cannot be inherited, though a derived class can call
the destructors of the
base class.
4. Destructors can be virtual, but constructors cannot.
5. Only one destructor can be defined in the single class. The
destructor does not have anyarguments.
6. Destructors neither have default values nor can be overloaded.
7. An object with a constructor or destructor cannot be used as a
member of a union.

Notes By:Miss shanti tulshidas shirsat Page 42 of 45


Chapter No2:Classes and Objects oop(22316)

Following is a sample program of destructor:


#include<iostream.h>
#include<conio.h>

class Marks
{
C++ Object created
public:
int maths;
int science;

Marks()
{
cout< < "\n Inside Constructor"< <endl;
cout< <"\n C++ Object created"<<endl;
}

~Marks() //Destructor
{
cout < "n Inside Destructor"< <end;
cout «< "n C++ Object destructed"<<endl;
}
};

void main()
{
clrscrO;
cout<<"n Enter blöck m1";

Notes By:Miss shanti tulshidas shirsat Page 43 of 45


Chapter No2:Classes and Objects oop(22316)

Marks m1; // Constructor gets called


// Destructor gets called
cout <<”Exit-błock m1";

cout<<"\n\n Enter block m2";

Marks m2 ; //Constructor gets called


// Destructor gets called

cout<<"\n Exit block m2";

getch();

Difference between constructor and destructor:

Notes By:Miss shanti tulshidas shirsat Page 44 of 45


Chapter No2:Classes and Objects oop(22316)

Notes By:Miss shanti tulshidas shirsat Page 45 of 45


Chapter No3:Extending classes using Inheritance oop(22316)

Chapter No3

Extending classes using Inheritance

3.1.Inheritance : Inheritance is an important feature of object oriented programming used for


code reusability. Inheritance allows us to inherit all the code (except declared as private) of one
class to another class.

The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important feature of Object Oriented
Programming.
Sub Class: The class that inherits properties from another class is called Sub class or Derived
Class or child class.
Super Class:The class whose properties are inherited by sub class is called Base Class or Super
class,parent class

3.2.Visibility modes and effects.

3.2.1 Public Inheritance:

• This is the most used inheritance mode.

• With public visibility mode derived class can inherit all public member variables and
public member functions of base class.
Syntax

class B : public A
{
Members of class B
}

3.2.2) Private Inheritance

• With private visibility mode derived class cannot inherit any member variables and
member functions of base class even if they are declared as public or private.

• Syhtax

class B: private A // default ViSibility mode is private so writing private word is


optional
{

Notes by:Miss.Shanti Tulshidas Shirsat Page 1 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

Members of class B
}

3.2.3) Protected Inheritance:

• There is another visibility mode with limited inheritance property protected.

• The public makes all members accessible to all functions of program and loses the
data hiding

• The private does not allow accessing any members directly from the program.

• The protected solves this problem by making members protected accessible to access
from the same class and next immediate derived class

• The declared protected members cannot access by any other class from the program.

• Syntax:
class A
{
protected:
member variables;
member function;
}

class B: public A
{
Members of class B

3.3 Types of Inheritance:

3.3.1Single Inheritance:

Notes by:Miss.Shanti Tulshidas Shirsat Page 2 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

class A // base class

..........

};

class B : acess_specifier A // derived class

...........

};

Example

#include <iostream.h>

class base //single base class

Notes by:Miss.Shanti Tulshidas Shirsat Page 3 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

public:

int x;

void getdata()

cout << "Enter the value of x = ";

cin >> x;

};

class derive : public base //single derived class

private:

int y;

public:

void readdata()

cout << "Enter the value of y = ";

cin >> y;

void product()

Notes by:Miss.Shanti Tulshidas Shirsat Page 4 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

cout << "Product = " << x * y;

};

int main()

derive a; //object of derived class

a.getdata();

a.readdata();

a.product();

return 0;

} //end of program

3.3.2 Multilevel Inheritance:

Multilevel inheritance represents a type of inheritance when a derived class is a base class for
another class.

Notes by:Miss.Shanti Tulshidas Shirsat Page 5 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

Example: Here, the derived class Rectangle is used as a base class to create the derived class
called ColorRectangle. Due to inheritance the ColorRectangle inherit all the characteristics of
Rectangle and Shape and add an extra field called rcolor, which contains the color of the
rectangle.

Syntax:Multilevel Inheritance :

class A // base class

...........

};

class B : acess_specifier A // derived class

Notes by:Miss.Shanti Tulshidas Shirsat Page 6 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

...........

};

class C : access_specifier B // derived from derived class B

...........

};

Program:

#include <iostream>

class base //single base class

public:

int x;

void getdata()

cout << "Enter value of x= ";

cin >> x;

};

class derive1 : public base // derived class from base class

Notes by:Miss.Shanti Tulshidas Shirsat Page 7 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

public:

int y;

void readdata()

cout << "\nEnter value of y= ";

cin >> y;

};

class derive2 : public derive1 // derived from class derive1

private:

int z;

public:

void indata()

cout << "\nEnter value of z= ";

cin >> z;

void product()

Notes by:Miss.Shanti Tulshidas Shirsat Page 8 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

cout << "\nProduct= " << x * y * z;

};

int main()

derive2 a; //object of derived class

a.getdata();

a.readdata();

a.indata();

a.product();

return 0;

} //end of program

3.3.3 Multilple Inheritance :

Notes by:Miss.Shanti Tulshidas Shirsat Page 9 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

Syntax:

class A

..........

};

class B

...........

};

class C : acess_specifier A,access_specifier A // derived class from A and B

...........

};

Notes by:Miss.Shanti Tulshidas Shirsat Page 10 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

C++ Multiple Inheritance Example

// multiple inheritance.cpp

#include <iostream.h>

class A

public:

int x;

void getx()

cout << "enter value of x: ";

cin >> x;

};

class B

public:

int y;

void gety()

Notes by:Miss.Shanti Tulshidas Shirsat Page 11 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

cout << "enter value of y: ";

cin >> y;

};

class C : public A, public B //C is derived from class A and class B

public:

void sum()

cout << "Sum = " << x + y;

};

int main()

C obj1; //object of derived class C

obj1.getx();

obj1.gety();

obj1.sum();

return 0;

Notes by:Miss.Shanti Tulshidas Shirsat Page 12 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

} //end of program

3.3.4 Hierarchical Inheritance:

• When 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

• .For example, a car is a common class from which Audi, Ferrari, Maruti etc can be
derived.

Syntax:

class A // base class

Notes by:Miss.Shanti Tulshidas Shirsat Page 13 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

..............

};

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:

#include <iostream>

using namespace std;

class A //single base class

Notes by:Miss.Shanti Tulshidas Shirsat Page 14 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

public:

int x, y;

void getdata()

cout << "\nEnter value of x and y:\n"; cin >> x >> y;

};

class B : public A //B is derived from class base

public:

void product()

cout << "\nProduct= " << x * y;

};

class C : public A //C is also derived from class base

public:

void sum()

Notes by:Miss.Shanti Tulshidas Shirsat Page 15 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

cout << "\nSum= " << x + y;

};

int main()

B obj1; //object of derived class B

C obj2; //object of derived class C

obj1.getdata();

obj1.product();

obj2.getdata();

obj2.sum();

return 0;

} //end of program

3.3.5 Hybrid Inheritance:

• The inheritance in which the derivation of a class involves more than one form of any
inheritance is called hybrid inheritance.

• Basically C++ hybrid inheritance is combination of two or more types of inheritance.

• It can also be called multi path inheritance.

Notes by:Miss.Shanti Tulshidas Shirsat Page 16 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

Syntax:

class A

.........

};

class B : public A

..........

};

class C

...........

};

class D : public B, public C

...........

Notes by:Miss.Shanti Tulshidas Shirsat Page 17 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

};

Example:

#include <iostream>

using namespace std;

class A

public:

int x;

};

class B : public A

public:

B() //constructor to initialize x in base class A

x = 10;

};

class C

Notes by:Miss.Shanti Tulshidas Shirsat Page 18 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

public:

int y;

C() //constructor to initialize y

y = 4;

};

class D : public B, public C //D is derived from class B and class C

public:

void sum()

cout << "Sum= " << x + y;

};

int main()

D obj1; //object of derived class D

Notes by:Miss.Shanti Tulshidas Shirsat Page 19 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

obj1.sum();

return 0;

} //end of program

3.4.1Virtual Base Class:

In above fig, properties of Base class are inherited via Derived/base class I and Derived/base
class.2 to the Derived class.

Notes by:Miss.Shanti Tulshidas Shirsat Page 20 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

• Fiqure above explains that the properties of grandparent class can be inherited by the
child class via two parents class and sometimes grandparent can directly accessible
to child.

• Here, Child class gets confused as the same property Is inherited by him twice and
this introduces ambiguity which must be avoided.

• To help child class we have to declare Dase cias5 as virtual Class so that properties
of that class becomes virtual and child class won't pay attention to those properties
assuming as virtual .

• When a class is made virtual base class C++ takes necessary action for
copy of base class and that single copy inherited by child class action for making
only single copy of base class and that single copy inherited by child class.

Syntax:

class Base
{

public:
public member variables
public member function
private:
public member variables
public member function

};

Notes by:Miss.Shanti Tulshidas Shirsat Page 21 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

Class intermediate_base1: virtual visibility_mode Base


{
public:
public member variables
public member function
private:
public member variables
public member function

};

Class intermediate_base2: visibility_mode virtual Base


{
public:
public member variables
public member function
private:
public member variables
public member function

};

class derived : visibity_mode intermediate_base1 ,visibity_mode intermediate_base2


{

public:
public member variables
public member function
private:
public member variables
public member function

};

Notes by:Miss.Shanti Tulshidas Shirsat Page 22 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

Example:

#include<iostream.h>
#include<conio.h>
class base
{
public:
void show_a()
{
cout<< "In class a";
}
};

class parent1: virtual public base


{
public:
void show_b()
{
cout< <"\nin class b";
}
};

class parent2: virtual public base


{
public:
void show_c()
{
cout<< "\nin class c";
}

};

class derived: public parent1, public parent2


{
public:
void show_d()
{
cout<< "\nln class d";
}

Notes by:Miss.Shanti Tulshidas Shirsat Page 23 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

};

void main()
{
derived d;
d.show_a();
d.show_b():
d.show_c();
d.show_d();
getch();
}

3.4.2 Abstract Class:

• Abstract is-used just to act as base class.

• Objects of Abstract class cannot be created.

• Abstract Class is a class which contains at least one Pure Virtual function in it.

• Abstract classes are used to provide an Interface for its sub classes.

• Classes inheriting an Abstract Class must provide definition to the pure virtual u
otherwise they will also become abstract class.

Characteristies of Abstract Class:

• Abstract class cannot be instantiated, but pointers and references of Abstract class
type can be created.

• Abstract class can have normal functions and variables along with a pure virtual
tunction.

• Classes inheriting an Abstract Class must implement all pure virtual functions, or else
they will become Abstract too.

Pure Virtual Functions:

• Pure virtual Functions are virtual functions with no definition.

• They start with virtual keyword and ends with 0.

Notes by:Miss.Shanti Tulshidas Shirsat Page 24 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

• Syntax for a pure virtual function,


virtual void f() = 0;

Program

#tinclude<iostream.h>
#include <conio.h>
class Base //- ---Abstract base class Implementation of Virtual Function
{

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

class Derived :public Base

{
public:
void show()

cout<< "Implementation of Virtual Function in Derived class";


}

};

void main()
{

Base obj; // we cannot create object of abstract class. Gives compile Time Error
Base *b;
Derived d;
b=&d;

Notes by:Miss.Shanti Tulshidas Shirsat Page 25 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

b->show():
getch();

3.4.3 Constructors in derived class:

Syntax

Derived_construcor (argB1, argB2, argD): base1(argB1), base2(argB2)

//Body of derived class constructor;

variable X = argD;

basel(argB1) invokes the base constructor base1() and base2(argB2) invokes another base class
constructor base2().

The Derived_ constructor( ) supply the values i.e. argB1, argB2 to base1() and base2() and to
one of its own variables X.

Hence, the assignment of the values will be as follows:

When an object of Derived class is created;

Derived_class object-name(5, 12, 7);

argB1=5

argB2=12

argD=7

#include <<iostream.h»

#irnclude<< conio.h>>

Notes by:Miss.Shanti Tulshidas Shirsat Page 26 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

class basel1

private:

int a;

public:

base1(int p)

a= p;

cout <<"\n basel class initialized \n";

void show_b1()

cout"\n a = "< <a;

};

class base2

private:

float b;

public:

base2(float q)

b =q;

cout<< "\n base2 class initialized \n";

Notes by:Miss.Shanti Tulshidas Shirsat Page 27 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

void show_b2()

cout<< "\n b = "< <b;

};

class derived :public base2, public base1

private:

int c,d;

public:

derived(int j, float k, int I, int m): base1(j),base2(k)

c=l;

d=m;

cout« "n derived class initialized \n";

void show_d()

Cout<"\n c = "< <c;

Cout< "\n d = "< <d;

};

void main()

Notes by:Miss.Shanti Tulshidas Shirsat Page 28 of 29


Chapter No3:Extending classes using Inheritance oop(22316)

derived obj(27,3.14,200,5);

obj.show_b1();

obj.show_b2();

obj.show_d();

Notes by:Miss.Shanti Tulshidas Shirsat Page 29 of 29


Chapter No4:Pointers and Polymorphism inC++ oop(22316)

Chapter No4

Pointers and polymorphism in C++

4.1Concept of pointer:

• Pointer:

• A pointer is a variable that stores the address of another variable.

• Unlike other variables that hold values of a certain type, pointer holds the address of a
variable.

• For example, an integer variable holds an integer value, however an integer pointer holds
the address of a integer variable.

• Pointer declaration:
Here is the syntax to declare a pointer
data_type *poiter_name;
Let's consider with following example statement
int *ptr;
Here, in this statement
• ptr is the name of pointer variable
• The character asterisk (*) tells to the compiler that the identifier ptr should be declare as
pointer.
• The data type int tells to the compiler that pointer ptr will store memory address of
integer type variable.
• Finally, ptr will be declared as integer pointer which will store address of integer type
variable.

• Address operator:

After declaration of a pointer variable, we need to initialize the pointer with the valid
memory address; to get the memory address of variable “Address Of" (&) Operator is
used.

Notes by:Miss.Shanti Tulshidas Shirsat Page 1 of 19


Chapter No4:Pointers and Polymorphism inC++ oop(22316)

int main()
{
int x=10; //integer variable
int *ptrX; //integer pointer declaration
ptrX=&x; //pointer initialization with the address of x

cout<<”Value of x=”<<*ptrx;
cout<<”Address of x=”<<ptrx;
return 0;
}

• Pointer Arithmetic:

• Following operations can be performed on pointer


1. Incrementing.a pointer (++)
2 Decrementing a pointer ( --)
3 Addition of a number to a pointer (+)
4. Subtraction of a number from a pointer (-)

• Following operations cannot be performed on a pointer.

1 Addition of two pointers.


2. Multiplication of a pointer with a constant.
3. Division of a pointer with a constant.

• Program 1: Incrementing a pointer:

include<iostream.h>
#include<conio.h>
void main()

{
int i=3, *X;
X = &i;
cout<<"\nOriginal address in x = "<<x;

X++ // pointer increment.


cout<<"\nNew address in x = "<<x;

Notes by:Miss.Shanti Tulshidas Shirsat Page 2 of 19


Chapter No4:Pointers and Polymorphism inC++ oop(22316)

getch();
}

4.2Pointer to object:

4.2.1 pointer to object:

• Pointer to object is pointer variable of the same class whose object is to be pointed to by
it.

• Syntax:

class name *variable name;

• To access individual members of object using pointer an operator called arrow operator (-
>)

• Following is example of pointer to object

abc obj;

abc *ptr= &obj;

• abc is class and obj is its object.

• Pointer ptr is initialized with the address of obj object

• So ptr is used to access the functions of class, just like object.

Program:

#include<IOstream.h>
#include<conio.h>
#include <string.h>
class book
{
char book_title[20],author_name[20];
float price;

public:
void getdàta()
{
cout<<"\nEnter Book Title, Author Name & Price";
cin>>book_title> > author name> >price;

Notes by:Miss.Shanti Tulshidas Shirsat Page 3 of 19


Chapter No4:Pointers and Polymorphism inC++ oop(22316)

}
void putdata()
{
cout<<"\nBook Title:"< <book_title;
cout<<"\nAuthor Name:"<<author_name;
cout<<"\n Price:"< <price;
}
};
void main()
{
book b,*pt;,
ptr=&b;
ptr->getdat();
ptr->putdata();
getch0;
}

Program2:

#include<iostream.h>
#include <conio.h>
class birthday
{
public:
int day,month.year;

void getdata()
{
cout< <"\nEnter bdate (Day Month Year) :
cin>>day> > month> >year,
}
void putdata()
{
cout< <day<<"/"< <month< <"l"<<year
}
};

void main0
{
birthday b[5],*p;
p=&b[0];

for(int i=0;i<5;i++)
{
cout"\nEnter bday:";

Notes by:Miss.Shanti Tulshidas Shirsat Page 4 of 19


Chapter No4:Pointers and Polymorphism inC++ oop(22316)

p->getdata0;
p++;
}
p=&b[0];

for(i=0;i<5;i++)
{
cout<<"bday”;
p->putdata();
p++;
}
getch();
}
4.2.2 this pointer
• it is predefined pointer variable in every class.
• it is pointer to the current object i.e the object whose member (data/function) is currently
being accessed.
• when a member function is called this' pointer is automatically passed as an implicit
argument to that function.
• Syntax:
The keyword this is used to access the pointer to the current object. We have to use the
arrow operator (->) in order to access the members of the current object along with this
pointer.

• Program 1. Write a program to display rollno and name of student using ' this' pointer
#include<iostream.h»
#include<conio.h>
#include< string.h>
class student
{
public:
int n ,
char name[20];

void print0;
student(int n, char name[]);

};

student:: student(int n, char name[])


{
this->n=n;
strcpy( this-> name, name);
}

Notes by:Miss.Shanti Tulshidas Shirsat Page 5 of 19


Chapter No4:Pointers and Polymorphism inC++ oop(22316)

void print0
{
cout<< "Roll no = "<<n< <endl;
çout<< "name = " <<name< <endl;
}

void main0
{
student s(6,"abc");
s.print();
getch();
}
4.2.3 pointer to derived class

#include<iostream.h>
class base
{
public:
int n1;
void show()
{
cout<<”\nn1 = “<<n1;
}
};
class derive : public base
{
public:
int n2;
void show()
{
cout<<”\nn1 = “<<n1;
cout<<”\nn2 = “<<n2;
}
};
int main()
{
base b;
base *bptr; //base pointer
cout<<”Pointer of base class points to it”;
bptr=&b; //address of base class
bptr->n1=44; //access base class via base pointer
bptr->show();

Notes by:Miss.Shanti Tulshidas Shirsat Page 6 of 19


Chapter No4:Pointers and Polymorphism inC++ oop(22316)

derive d;
cout<<”\n”;
bptr=&d; //address of derive class
bptr->n1=66; //access derive class via base pointer
bptr->show();
return 0;
}

4.3 Polymorphism:

4.3.1:Concept:

• Polymorphism is considered as one of the important features of Object Oriented


Programming.
• The word polymorphism means having many forms.
• In simple words, we can define polymorphism as the ability of a message to be displayed
in more than one form.
• Real life example of polymorphism, a person at the same time can have different
characteristic. Like a man at the same time is a father, a husband, an employee. So the
same person posses different behavior in different situations. This is called
polymorphism.
• In C++ polymorphism is mainly divided into two types:
• Compile time Polymorphism
• Runtime Polymorphism

4.3.2.Types of polymorphism

Notes by:Miss.Shanti Tulshidas Shirsat Page 7 of 19


Chapter No4:Pointers and Polymorphism inC++ oop(22316)

4.4: Compile time polymorphism: This type of polymorphism is achieved by function


overloading or operator overloading.

4.4.1 Function Overloading:

• Overloading means use of same thing but for different purpose

• Function overloading allows you to use the same name for different functions, to
perform,either same or different functions in the same class.

• When there are multiple functions with same name but different parameters then these
functions are said to be overloaded.

• Functions can be overloaded by change in number of arguments or/and change in type


of arguments.

• Following are two ways to overload a function:


1 By changing number of Arguments.

2.By having different types of argument.

1) Number of arguments:

• In this type of function overloading, we define two functions with same names but
different number of parameters of the same type.
void display (int x)
{
cout< <"x="< <x;
}
void display (int x; int y)

{
cout<<"x="<<x;
cout<<"y="< <y;
}

void main()

display (10)
display (10,20);
}

Notes by:Miss.Shanti Tulshidas Shirsat Page 8 of 19


Chapter No4:Pointers and Polymorphism inC++ oop(22316)

• In above example, display () function is overloaded to have one and two arguments.

• Display() function will be called depending on the number of arguments.

2) Different types of arquments:

• In this type of overloading, we define two or more functions with same name and same
number of parameters, but the type of parameter is different.

void display (int x, int y)

{
cout<<"x="<<X;
}
void display (float x, float y)
{

cout< <"x="< <x;


cout<<"y="< <y;

}
void main()

display (10);

display (10.10,20.10);

• program to swap 2 numbers using function overloading

#include<iostream.h>

#include<conio.h>

void swap(int a,,int b)

Notes by:Miss.Shanti Tulshidas Shirsat Page 9 of 19


Chapter No4:Pointers and Polymorphism inC++ oop(22316)

int c;

c=a;

a=b;

b=c;

void swap(float a,float b)

float c;

c=a;

a=b;

b=c;

void main()

int a,b;

float c,d;

clrscr();

cout<<"enter the values of a,b for integer";

cin>>a>>b;

cout<<"enter the values for c,d ";

cin>>c>>d;

void swap(a,b );

void swap(c,d);

Notes by:Miss.Shanti Tulshidas Shirsat Page 10 of 19


Chapter No4:Pointers and Polymorphism inC++ oop(22316)

cout<<"\nafter swaping ";

cout<<"\nvalues of a,b "<<a<<"\t"<<b;

cout<<" \nvalues of c,d "<<c<<"\t"<<d;

getch();

4.4.2 Operator Overloading:

• C++ also provide option to overload operators.

• For example, we can make the operator (‘+’) for string class to concatenate two strings.
We know that this is the addition operator whose task is to add two operands.

• So a single operator ‘+’ when placed between integer operands , adds them and when
placed between string operands, concatenates them.

• it is a type of polymorphism in which an operator is overloaded to give user defined


meaning to it.

• Overloaded operator is used to perform operation on user-defined data type

• For example,'+' operator can be overloaded to perform addition on various data types,
like for Integer, String (concatenation) etc.

• when an operator is overloaded its original meaning does not lost.

• Following restrictions are on Operator Overloading:

• . Precedence and Associativity of an operator cannot be changed

• Arity (numbers of Operands) cannot be changed. Unary operator remains unary


binary remains binary etc.

• No new operators can be created, only existing operators can be overloaded.

• Can't redefine the meaning of a procedure. You cannot change how integers are
added.

Notes by:Miss.Shanti Tulshidas Shirsat Page 11 of 19


Chapter No4:Pointers and Polymorphism inC++ oop(22316)

• Following operators cannot be overloaded :


1. Scope Operator (::)
2 Size Operator (sizeof)
3. Member Selector Operator (.,.*)
4 Conditional Operator (?)

• Syntax of operator overloading:

Return type class_name::operator operator_symbol (argument_list)


{
\lfunction body:
}

• Operator overloading can be done by implementing a function which can be:

• Member Function: Mermber function has no arguments for unary operator and
one for binary operator

• Friend Function: Friend function has only one argument for unary operator and
two for binary operator

1 Overloading Unary operator. Program:

#include<iostream.h>

#include<conio.h>

class complex {

int a, b;

public:

void getvalue()

Notes by:Miss.Shanti Tulshidas Shirsat Page 12 of 19


Chapter No4:Pointers and Polymorphism inC++ oop(22316)

cout << "Enter the value of Complex Numbers a,b:";

cin >> a>>b;

complex operator+(complex ob) {

complex t;

t.a = a + ob.a;

t.b = b + ob.b;

return (t);

void display() {

cout << a << "+" << b << "i" << "\n";

};

void main()

clrscr();

complex obj1, obj2, result;

obj1.getvalue();

obj2.getvalue();

result = obj1 + obj2;

Notes by:Miss.Shanti Tulshidas Shirsat Page 13 of 19


Chapter No4:Pointers and Polymorphism inC++ oop(22316)

cout << "Input Values:\n";

obj1.display();

obj2.display();

cout << "Result:";

result.display();

getch();

4.4.3 Rules for operator overloading:

• Precedence and Associativity of an operator cannot be changed.

• Arity (numbers of Operands) cannot be changed. Unary operator remains unary, binary
remains binary etc.

• No new operators can be created, only existing operators can be overloaded.

• Cannot redefine the meaning of a procedure. You cannot change how integers are added.

• Only existing operators can be overloaded

• New operators cannot be created

• Overloaded operator must follow the original syntax rulees.

• We cannot used friend function to overload certain operators: -

i. Assignment operator (=)


ii. Function call operators ( () )
ii. Subscripting operator (0)
iv. Class member access operator (->)

Notes by:Miss.Shanti Tulshidas Shirsat Page 14 of 19


Chapter No4:Pointers and Polymorphism inC++ oop(22316)

4.5 Run Time Polymorphism:

• C++ allows binding to be delayed till run time.

• This will need the use of a single pointer variable to refer to the objects of different
classes.

• This sort of operation is referred to as 'dynamic linking', or "late binding:

• Here, we use the pointer to base class tó refer to all the defived objects.

• .The compiler ignores the content of the pointer and chooses the member function that
matches the type of pointer. For this Virtual Functions are needed.

• Virtual functions allow us to create a list of base class pointers and call methods of any of
the derived classes without even knowing kind of derived class object.

• A Virtual function is a function in a base class that is declared using the keyword virtual.

• Defining in a base class a virtual function, with another version in a derived class, signals
to the compiler that we don't want static linking for this function.

• Runtime polymorphism is achieved only when a virtual function is accessed through a


pointer to the base class.

4.5.1:Virtual Function:

• Supports to late binding in which function in base class is declared virtua! using keyword
virtual & overridden in each-derived class

• It is invoked through pointer a base class which points to object of derived class whose
function definition is used.

#include<iostream.h>
#include<conio.h>
class Base

{
public:

Notes by:Miss.Shanti Tulshidas Shirsat Page 15 of 19


Chapter No4:Pointers and Polymorphism inC++ oop(22316)

virtual void show()


{
cout < "Base class";
}

};

class Derivèd:public Base


{

public:

void show()
{
cout <<"Derived Class";
}
void main0
{
Base *b;
Derived d;
b=&d
b->show()
getch();

4.5.2:Rules for virtual functions

• only the Base class Method's declaration needs the virtual keyword, not the definition.

• if a function is declared as virtual in the base class, it will be virtual in all its derived
classes.

• The virtual function cannot be static members.

• The virtual functions are accessed by using object pointer.

Notes by:Miss.Shanti Tulshidas Shirsat Page 16 of 19


Chapter No4:Pointers and Polymorphism inC++ oop(22316)

• It can be friend of another class.

• Virtual constructors cannot be created but virtual destructors can be created.

• The base pointer can point to any type of the derived object but derived cannot.

4.5.3:Pure Virtual function:

• Pure virtual Functions are virtual functions with no definition.

• They start with virtual keyword and ends with = 0;

• The "= 0" portion of a pure virtual function is also known as the pure specifier,
because it's what makes a pure virtual function "pure".

• The notation "= 0" is just there to indicate that the virtual function is a pure virtual
function,and that the function has no body or definition.

• "=0" does not mean that function assigned value 0.

• syntax for a pure virtual function:


virtual void function_name() = 0;

• Program: Pure virtual function

#include <iostream.h>
#include <conio.h>

class Base

{
public:
virtual void show() ; //Pure Virtual Function

};

class Derived:public Base


{
public:

Notes by:Miss.Shanti Tulshidas Shirsat Page 17 of 19


Chapter No4:Pointers and Polymorphism inC++ oop(22316)

void show()
{

cout << "Implementation of Virtual Function in Derived class”;

}
void main()

{
Base *b;
Derived d;
b= &d
b->show0:
getch();

4.5.4 Difference between Compile time Polymorphism and Runtime Polymorphism

In Compile time Polymorphism, the call is In Run time Polymorphism, the call is

1 resolved by the compiler. not resolved by the compiler.

It is also known as Static binding, Early It is also known as Dynamic binding,

2 binding and overloading as well. Late binding and overriding as well.

Method overloading is the compile-time

polymorphism where more than one methods Method overriding is the runtime

share the same name with different polymorphism having same method

parameters or signature and different return with same parameters or signature, but

3 type. associated in different classes.

It is achieved by function overloading and It is achieved by virtual functions and

4 operator overloading. pointers.

Notes by:Miss.Shanti Tulshidas Shirsat Page 18 of 19


Chapter No4:Pointers and Polymorphism inC++ oop(22316)

It provides slow execution as compare

It provides fast execution because the method to early binding because the method

that needs to be executed is known early at that needs to be executed is known at

5 the compile time. the runtime.

Run time polymorphism is more

Compile time polymorphism is less flexible flexible as all things execute at run

6 as all things execute at compile time. time.

Notes by:Miss.Shanti Tulshidas Shirsat Page 19 of 19


Chapter No5:File operations oop(22316)

CHAPTER NO:5

FILE OPERATIONS

5.1 C++ stream classes:


5.1.1: C++ stream classes

Notes by:Miss.Shanti Tulshidas Shirsat Page 1 of 10


Chapter No5:File operations oop(22316)

5.1.2: Classes for file stream operations:

5.2 file operation:

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

• Opening a file: open()


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

5.2.1: Opening file:

➢ We can open a file using any one of the following methods:


1. First is bypassing the file name in constructor at the time of object creation.
2. Second is using the open() function.

Notes by:Miss.Shanti Tulshidas Shirsat Page 2 of 10


Chapter No5:File operations oop(22316)

➢ To open a file use :- open() function


➢ Syntax: void open(const char* file_name,ios::openmode mode);
➢ Here, the first argument of the open function defines the name and format of the file with
the address of the file.
➢ The second argument represents the mode in which the file has to be opened.
➢ Example:

fstream new_file;

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

➢ In the above example, new_file is an object of type fstream, as we know fstream is a class
so we need to create an object of this class to use its member functions. So we create
new_file object and call open() function. Here we use out mode that allows us to open the
file to write in it.
➢ Default Open Modes :

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

➢ We can combine the different modes using or symbol | .

Example

ofstream new_file;

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

➢ Here, input mode and append mode are combined which represents the file is opened for
writing and appending the outputs at the end.
➢ As soon as the program terminates, the memory is erased and frees up the memory
allocated and closes the files which are opened.
➢ But it is better to use the close() function to close the opened files after the use of the file.
➢ Using a stream insertion operator << we can write information to a file and using stream
extraction operator >> we can easily read information from a file.
➢ Example of opening/creating a file using the open() function

#include<iostream>

#include <fstream>

using namespace std;

Notes by:Miss.Shanti Tulshidas Shirsat Page 3 of 10


Chapter No5:File operations oop(22316)

int main()

fstream new_file;

new_file.open("new_file",ios::out);

if(!new_file)

cout<<"File creation failed";

else

cout<<"New file created";

new_file.close(); // Step 4: Closing file

return 0;

➢ Explanation
In the above example we first create an object to class fstream and name it
‘new_file’. Then we apply the open() function on our ‘new_file’ object. We give
the name ‘new_file’ to the new file we wish to create and we set the mode to ‘out’
which allows us to write in our file. We use a ‘if’ statement to find if the file
already exists or not if it does exist then it will going to print “File creation failed”
or it will gonna create a new file and print “New file created”.

5.2.2: Closing file:

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


➢ Syntax: File Pointer.close()
➢ Example:

#include <iostream>

#include <fstream>

Notes by:Miss.Shanti Tulshidas Shirsat Page 4 of 10


Chapter No5:File operations oop(22316)

using namespace std;

int main()

fstream new_file;

new_file.open("new_file.txt",ios::out);

new_file.close();

return 0;

Output:

The file gets closed.

5.2.3: Reading from and writing file:

➢ Reading from file:

#include <iostream>

#include <fstream>

using namespace std;

int main()

fstream new_file;

new_file.open("new_file_write.txt",ios::in);

if(!new_file)

cout<<"No such file";

else

Notes by:Miss.Shanti Tulshidas Shirsat Page 5 of 10


Chapter No5:File operations oop(22316)

char ch;

while (!new_file.eof())

new_file >>ch;

cout << ch;

new_file.close();

return 0;

➢ Explanation:

In this example, we read the file that generated id previous example i.e. new_file_write.
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.

➢ Writing to a file:

Example:

#include <iostream>

#include <fstream>

using namespace std;

int main()

fstream new_file;

new_file.open("new_file_write.txt",ios::out);

Notes by:Miss.Shanti Tulshidas Shirsat Page 6 of 10


Chapter No5:File operations oop(22316)

if(!new_file)

cout<<"File creation failed";

else

cout<<"New file created";

new_file<<"Learning File handling"; //Writing to file

new_file.close();

return 0;

➢ Explanation:

Here we first create a new file “new_file_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.

5.3.1Detection of end of file

➢ You can detect when the end of the file is reached by using the member function eof()
which has prototype :

int eof();
➢ It returns non-zero when the end of file has been reached, otherwise it returns zero.

Notes by:Miss.Shanti Tulshidas Shirsat Page 7 of 10


Chapter No5:File operations oop(22316)

➢ Example:
ifstream fin ;
fin.open("master", ios::in | ios::binary);

while(!find.eof()) //as long as eof() is zero


{ //that is, the file's end is not reached
: //process the file
}
if(fin.eof()) //if non-zero

{
cout << "End of file reached ! \n" ;
}

Example 2:

#include <iostream.h>

#include <fstream.h>

#include <assert.h>

int main(void)

int data; // file contains an undermined number of integer values

ifstream fin; // declare stream variable name

fin.open("myfile",ios::in); // open file

fin >> data; // get first number from the file (priming the input statement)

// You must attempt to read info prior to an eof( ) test.

while (!fin.eof( )) //if not at end of file, continue reading numbers

cout<<data<<endl; //print numbers to screen

fin >> data; //get next number from file

Notes by:Miss.Shanti Tulshidas Shirsat Page 8 of 10


Chapter No5:File operations oop(22316)

fin.close( ); //close file

assert(!fin.fail( ));

return 0;

5.3.2:file modes:

Notes by:Miss.Shanti Tulshidas Shirsat Page 9 of 10


Chapter No5:File operations oop(22316)

Notes by:Miss.Shanti Tulshidas Shirsat Page 10 of 10

You might also like