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

C++ Notes (Unit-4,5)

The document discusses different types of inheritance in object-oriented programming in C++. It covers single inheritance, multilevel inheritance, and provides code examples to demonstrate how they work. Key advantages of inheritance like code reusability and reduced redundancy are also mentioned.

Uploaded by

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

C++ Notes (Unit-4,5)

The document discusses different types of inheritance in object-oriented programming in C++. It covers single inheritance, multilevel inheritance, and provides code examples to demonstrate how they work. Key advantages of inheritance like code reusability and reduced redundancy are also mentioned.

Uploaded by

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

Object Oriented Programming

(C++)

Virendra Sir
(Scholars Education)
UNIT-4

Inheritance:Introduction, Importance of Inheritance, types of inheritance, Constructor


and Destructor in derived classes.
Polymorphism:Function overloading, operator overloading, virtual functions, pure
virtual functions.

Inheritance
 Inheritance is one of the key features of Object-oriented programming in C++. It
allows user to create a new class (derived class, sub class, child class) from an
existing class (base class, super class, Parent class).
 The derived class inherits all the features from the base class and can have
additional features of its own.Syntax
class derived-class: access-specifier base-class
 The process of obtaining the data members and methods from one class to
another class is known as inheritance. It is one of the fundamental features of
object-oriented programming.

Important points

 In the inheritance the class which is give data members and methods is known
as base or super or parent class.
 The class which is taking the data members and methods is known as sub or
derived or child class.

Syntax
class subclass_name : superclass_name
{
// data members
// methods
}

TC Business School | BEST BCA College In JAIPUR 1


Real life example of inheritance

The real life example of inheritance is child and parents, all the properties of father are
inherited by his son.

Diagram

In the above diagram data members and methods are represented in broken line are
inherited from faculty class and they are visible in student class logically.

Advantage of inheritance

TC Business School | BEST BCA College In JAIPUR 2


If we develop any application using this concept than that application have following
advantages,

 Application development time is less.


 Inheritance is used to increase “Reusability” of class.
 Applications take less memory.
 Application execution time is less.
 Transitive nature of inheritance.
 Application performance is enhance (improved).
 Redundancy (repetition) of the code is reduced or minimized so that we get
consistence results and less storage cost.

Inheriting the feature from base class to derived class

In order to inherit the feature of base class into derived class we use the following
syntax

Syntax

class classname-2 : classname-1


{
variable declaration;
method declaration;
}

Explanation

 classname-1 and classname-2 represents name of the base and derived classes
respectively.
 : is operator which is used for inheriting the features of base class into derived
class it improves the functionality of derived class.

Example of Inheritance in C++

TC Business School | BEST BCA College In JAIPUR 3


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

class employee
{
public:
int salary;
};
class developer : public employee
{
employee e;
public:
void salary()
{
cout<<"Enter employee salary: ";
cin>>e.salary; // access base class data member
cout<<"Employee salary: "<<e.salary;
}
};

void main()
{
clrscr();
developer obj;
obj.salary();
getch();
}

Output

Enter employee salary: 50000


Employee salary: 50000

TC Business School | BEST BCA College In JAIPUR 4


Types of Inheritance

Based on number of ways inheriting the feature of base class into derived class it
have five types they are:

1) Single inheritance
2) Mult level inheritance
3) Multiple inheritance
4) Hierarchical inheritance
5) Hybrid inheritance

1) Single inheritance
 In single inheritance there exists single base class and single derived class.
 In which one class access the property another class.

Program)
//inheritance ( single inheritance Example )

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

class base // base class


{
public:

TC Business School | BEST BCA College In JAIPUR 5


void show1()
{
cout<<"Show1"<<endl;
}
};

class derived : public base // base class is derived publicly in derived class
{ // single derived class
public:
void show2()
{
cout<<"Show2"<<endl;
}
};

int main()
{
derived d; // Derived class object

d.show1(); // show1() of base class is called


d.show2(); // show2() of derived class is called

getch();
return 0;
}
Output

TC Business School | BEST BCA College In JAIPUR 6


Program)
#include<iostream.h>
#include<conio.h>
class A
{
Int a,b,c;
protected:
void sum()
{
cout<<"Enter two number=";
cin>>a>>b;
c=a+b;
cout<<"Sum="<<c<<endl;
}
};

class B:A
{
Int p,q,r;
public:
void mul()
{
cout<<"enter two number=";

TC Business School | BEST BCA College In JAIPUR 7


cin>>p>>q;
r=p*q;
cout<<"multi="<<r<<endl;
sum();
}
};
void main()
{
clrscr();
B o;
o.mul();
getch();
}

Output

Note
 Private member cannot be accessed outside the class
 Protected member can be accessed child class but not outside the class and not
in main() function.
 When a base class is privately inherit derived class than public member of base
class become private member of derive of class.

Program) A public member of class base will be inaccessible to the object of derived
class.
#include<iostream.h>

TC Business School | BEST BCA College In JAIPUR 8


#include<conio.h>
class A
{
inta,b,c;
protected:
void sum()
{
cout<<"Enter two number=";
cin>>a>>b;
c=a+b;
cout<<"Sum="<<c<<endl;
}
};

class B:A
{
public:
void display()
{
sum();
}
};
void main()
{
clrscr();
B o;
o.display();
getch();
}
Output

TC Business School | BEST BCA College In JAIPUR 9


Program) On the other hand when the base class is public inherited then the public
member of base class become public member of base class can be accessed by
member function of derived class, with the object of derived class.
#include<iostream.h>
#include<conio.h>
class A
{
inta,b,c;
public:
void sum()
{
cout<<"Enter two number=";
cin>>a>>b;
c=a+b;
cout<<"Sum="<<c<<endl;
}
};

class B:public A
{
public:
void display()
{
sum();
}
TC Business School | BEST BCA College In JAIPUR 10
};
void main()
{
clrscr();
B o;
o.display();
o.sum();
getch();
}
Output

2) Multilevel inheritances
 It is the inheritance hierarchy wherein subclass acts as a base class for other
classes.
 In this when sub classes (B) inherit a base class (A) in this situation A become
parent class of B. And again class B inherited by class C in this situation class B
become parent class for class c.
 The transitive nature of inheritance is reflected by multilevel inheritance.

Syntex
TC Business School | BEST BCA College In JAIPUR 11
class A
{
……..
…….
};

Class B:A
{
……….
………

};

Class C:B
{
..........
…….
};

Program)
#include<iostream.h>
#include<conio.h>
class A
{
inta,b,c;
protected:
void sum()
{
cout<<"Enter two number=";
cin>>a>>b;
c=a+b;
cout<<"Sum="<<c<<endl;
}
};

class B:A
{
intp,q,r;
protected:
void mul()
{
sum();
cout<<"Enter no=";
cin>>p>>q;
r=p*q;

TC Business School | BEST BCA College In JAIPUR 12


cout<<"multiply= "<<r;

}
};
class C:B
{
intg,h,i;
public:
void divide()
{
mul();
cout<<endl;
cout<<"Enter two number";
cin>>g>>h;
i=g/h;
cout<<"divide="<<i;
}
};
void main()
{
clrscr();
C o;
o.divide();
getch();
}

Output

Program)

//inheritance ( Multilevel inheritance Example )

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

class base // base class


TC Business School | BEST BCA College In JAIPUR 13
{
public:
void show1()
{
cout<<"Show1"<<endl;
}
};

class derived1 : public base // base class is derived publicly in derived class
{ // first derived class
public:
void show2()
{
cout<<"Show2"<<endl;
}
};

class derived2 :public derived1 // second derived class from first derived class
{
public:
void show3()
{
cout<<"Show3"<<endl;
}
};

int main()
{
derived2 d; // Derived2 class object

d.show1(); // show1() of base class is called


d.show2(); // show2() of derived1 class is called
d.show3(); // show3() of derived2 class is called

getch();
return 0;
}

3) Multiple inheritance
 It is the inheritance one derived class inherits from multiple base class.
 When a sub class inherits more than one base class this situation is known as
multiple inheritance.

TC Business School | BEST BCA College In JAIPUR 14


Prog)

//inheritance ( Multiple inheritance Example )

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

class base1 // base1 class (first base class)


{
public:
void show1()
{
cout<<"Show1"<<endl;
}
};

class base2 // base2 class (second base class)


{
public:
void show2()
{
cout<<"Show2"<<endl;
}
};

TC Business School | BEST BCA College In JAIPUR 15


class derived : public base1, public base2 // derived class from base1 and base2 class
{
public:
void show3()
{
cout<<"Show3"<<endl;
}
};

int main()
{
derived d; // Derived class object (derived class derived from two base
classes)

d.show1(); // show1() of base1 class is called


d.show2(); // show2() of base2 class is called
d.show3(); // show3() of derived class is called

getch();
return 0;
}

Output

TC Business School | BEST BCA College In JAIPUR 16


4)Hierarchical inheritanceit is the inheritance hierarchy wherein multiple subclasses
inherit from one base class.

Prog)

//inheritance ( Hierachical inheritance Example )

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

class base // base class (one base class)


{
public:
void show1()
{
cout<<"Show1"<<endl;
}
};

class derived1 : public base // first derived class from base class
{
public:
void show2()
{
cout<<"Show2"<<endl;
}
};

class derived2 : public base // second derived class from base classs
{
public:

TC Business School | BEST BCA College In JAIPUR 17


void show3()
{
cout<<"Show3"<<endl;
}
};

int main()
{
clrscr();
derived1 d1; // Derived1 class object
derived2 d2; // Derived2 class object

d1.show1(); // show1() of base class is called


d1.show2(); // show2() of derived1 class is called

d2.show1(); // show1() of base class is called


d2.show3(); // show3() of derived2 class is called

getch();
return 0;
}

Output

Prog)Following example further explains concept of inheritance :

TC Business School | BEST BCA College In JAIPUR 18


#include<iostream.h>
#include<conio.h>
class Shape
{
protected:
float width, height;
public:
void set_data (float a, float b)
{
width = a;
height = b;
}
};

class Rectangle: public Shape


{
public:
float area ()
{
return (width * height);
}
};

class Triangle: public Shape


{
public:
float area ()
{
return (width * height / 2);
}
};

int main()
{
TC Business School | BEST BCA College In JAIPUR 19
clrscr();
Rectangle rect;
Triangle tri;
rect.set_data(5,3);
tri.set_data(2,5);
cout<<rect.area()<<endl;
cout<<tri.area()<<endl;
getch();
return 0;
}

Output

5) Hybrid inheritance

 The inheritance hierarchy that reflects any legal combination of other four types
of inheritance.
 A structure which is created by using two or more inheritance combination of two
inheritances is known as hybrid inheritance.

TC Business School | BEST BCA College In JAIPUR 20


Prog)
//inheritance ( Hybrid inheritance Example )
#include<iostream.h>
#include<conio.h>
class base1 // base class
{
public:
void show1()
{
cout<<"Show1"<<endl;
}
};

class base2
{
public:
void show4()
{
cout<<"Show4"<<endl;
}
};

class derived1 : public base1,public base2 // first derived1 class from base1 and
base2 class
{ // multiple inheritance
public:
void show2()
{
cout<<"Show2"<<endl;
}
};

TC Business School | BEST BCA College In JAIPUR 21


class derived2 : public derived1 // second derived2 class from derived1 class
{
public:
void show3()
{
cout<<"Show3"<<endl;
}
};

int main()
{
clrscr();
derived2 d;
d.show1();
d.show2();
d.show3();
d.show4();
getch();
return 0;
}

Output

TC Business School | BEST BCA College In JAIPUR 22


Assignment

Program-1)

//inheritance ( private derivation of base class in derived class


#include<iostream.h>
#include<conio.h>
class base
{
int a;
protected:
int b;
public:
base() //Base class constructor
{
a=10;
b=20;
cout<<a<<" "<<b;
// cout<<"This is base constructor";
}
};

class derived : private base // base class is derived privately in derived class
{
// protected and public members of base become private here
public:
int c;
derived()
{

c=30;

TC Business School | BEST BCA College In JAIPUR 23


cout<<" "<<c<<" ";
}
};
class sub:private derived
{
int e;
public:
sub()
{
e=40;
cout<<" "<<e;
}

};
int main()
{
//derived d;
//cout<<d.a; // a and b of base are not accessible here directly
//cout<<d.b;
//cout<<d.c; // public member c of derived class can be accessed
directly here
sub aa;
getch();
return 0;
}

Output

TC Business School | BEST BCA College In JAIPUR 24


Prog-2)

//inheritance ( protected derivation of base class in derived class )

#include<iostream.h>
#include<conio.h>
class base
{
int a;

protected:
int b;
public:
base() //Base class constructor
{
a=10;
b=20;
cout<<a<<" "<<b;
}
};

class derived : protected base // base class is derived protectedly in derived class
{
// protected and public members of base become protected here
public:
int c;
derived() // Derived class constructor
{
//a=50; // private member a can not be accessed in derived class
c=30;
cout<<" "<<c<<" ";
b=40; // protected member b can be accessed in derived class
cout<<" "<<b<<" ";
}
};

TC Business School | BEST BCA College In JAIPUR 25


int main()
{
derived d;
cout<<d.a; // a and b of base are not accessible here directly
//cout<<d.b;
cout<<d.c; // public member c of derived class can be accessed directly here

getch();
return 0;
}
Prog-3)
//inheritance ( public derivation of base class in derived class )

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

class base
{
int a;

protected:
int b;
public:
base() //Base class constructor
{
a=10;
b=20;
cout<<a<<" "<<b;
}
};

class derived : public base // base class is derived publicly in derived class
{
// protected will remain protected here ,
public: // public will remain public here
int c;
derived() // Derived class constructor
{
//a=50; // private member a can not be accessed in derived class
c=30;
cout<<" "<<c<<" ";
b=40; // protected member b can be accessed in derived class
cout<<" "<<b<<" ";
}
};

TC Business School | BEST BCA College In JAIPUR 26


int main()
{
derived d;
//cout<<d.a; // a and b of base are not accessible here directly
//cout<<d.b;
cout<<d.c; // public member c of derived class can be accessed directly here

getch();
return 0;
}

Output

Prog-4)

//inheritance ( Difference between private and protected data member of the class )

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

class base
{
int a;

protected:
int b;
public:
void fun()
{
a=10;
b=20;
cout<<a<<" "<<b<<" ";
}
};
TC Business School | BEST BCA College In JAIPUR 27
class derived : public base // base class is derived publicly in derived class
{

public:
void show()
{
a=30; // private member a is not accessed in derived function ,
b=40; // but protected member b can be accessed in derived class
function
//cout<<a<<" ";
cout<<b<<" ";
}

};

int main()
{
derived d; // Derived class object
d.fun(); // base class function fun() is called with derived class object
d.show(); // derived class function show() is called with derived object

getch();
return 0;
}

Prog-5)

//inheritance ( Ambiguity in single inheritance )

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

class base // base class


{
public:
void show() // show() of base
{
cout<<"Show base"<<endl;
}
};

class derived : public base


{
public: // function show with same name in base class

TC Business School | BEST BCA College In JAIPUR 28


void show() // show() of derived
{
cout<<"Show derived"<<endl;
}
};

int main()
{
clrscr();
derived d;

d.show();

d.base::show(); // Use of :: ( scope resolution operator )


// to resolve ambiguity problem in calling show()
getch();
return 0;
}

Output

Prog-6)

//inheritance ( Ambiguity in multilevel inheritance )

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

class base // base class


{
public:
void show() // show() of base
{
cout<<"Show base"<<endl;
}
TC Business School | BEST BCA College In JAIPUR 29
};

class derived : public base


{
public: // function show with same name in base class
void show() // show() of derived
{
cout<<"Show derived"<<endl;
}
};

class derived2 : public derived


{
public:
void show()
{
cout<<"Show derived2"<<endl;
}
};

int main()
{
clrscr();
derived2 d;

d.show();

d.derived::show(); // Use of :: ( scope resolution operator )


// to resolve ambiguity problem in calling show()
getch();
return 0;
}

Output

TC Business School | BEST BCA College In JAIPUR 30


Prog-7)

//inheritance ( constructors & destructors in inheritance )

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

class base
{
public:
base() // Base class constructor
{
cout<<"Base class constructor"<<endl;
}
~base() // Base class destructor
{
cout<<"Base class Destructor"<<endl;
}
};

class derived : public base


{
public:
derived() // Derived class constructor
{
cout<<"Derived class constructor"<<endl;
}
~derived() // Derived class destructor
{
cout<<"Derived class Destructor"<<endl;
}
};

int main()
{
{
derived d;
}
getch();
return 0;
}

Output

TC Business School | BEST BCA College In JAIPUR 31


Polymorphism
Most important characteristic of oop’s analysis and design is “POLYMORPHISM”.
Where “POLY” means “MANY” & “MORPHISM” means “FORM”.
Polymorphism is the ability to use an operator or function indifferent ways.
Polymorphism gives different meaning or function to the operators or functions. A single
function usage or an operator functioning in many ways can be called polymorphism.
Polymorphism refers to the ability to call different functions by using only one
types of function call.
Following different way to achieve polymorphism
1) Function overloading
2) Operator overloading
3) Dynamic Binding (virtual function)

1) Function overloading 
 More than one function with same name but parameter is different.
 In case of function overloading we can have two or more than two function by the
same name in the same class but the list of argument should be different.

Example:
#include<iostream.h>
#include<conio.h>
class A
{

TC Business School | BEST BCA College In JAIPUR 32


inta,b;
public:
void fun(int a)
{
cout<<"one argument a="<<a;
}
void fun(int a, int b)
{
cout<<"\n two argument a & b="<<a<<b;
}
};

void main()
{
clrscr();
A ob1;
ob1.fun(10);
obj1. fun(10,20);
getch();
}

Result:

2) Operating overloading
TC Business School | BEST BCA College In JAIPUR 33
To define additional task to an operator, we must specify the relation of operator with
class this is done by a special function called operatorfunction which describe the
task. The general syntax of operator function
return_typeclass_name:: operator op(argument_list)
{
function _body;
}
Another way
return_type operator op(argument_list)
{
//body of operator function
}

Note

 Here return type means which return a value.


 Hence op is the operator symbol being over loaded and op is proceeding by
keyword operator. Hence operator is the function_name.
 Operator function must be either member function or friend function.
 A basic difference between them is that a friend function will have only one
argument for unary operators and two for binary operator, while a member
functionhas no arguments for unary operators and only one for binary operators.

Overloading unary operator


Let us consider the unary minus operator. A minus operator when as a unary takes just
one operand. We know that this operator changes the sign of an operand when applied
to a basic data item. The unary minus when applied to an object should change the sign
of each of its data items.
There are four main unary overloading operator are used
1) Operator ++()
2) Operator --()

TC Business School | BEST BCA College In JAIPUR 34


3) Operator +()
4) Operator -()

Program) a program to perform unary minus operation on object of a class.


#include<iostream.h>
#include<conio.h>
class number
{
int x;
public:
void setdata(int a)
{
x=a;
}
void show()
{
cout<<"Value="<<x<<endl;
}
void operator-() //unary operator overloading
{
x=-x;
}
};

void main()
{
clrscr();
number N;
N.setdata(5);
N.show();
-N; //invoke operator-() function

TC Business School | BEST BCA College In JAIPUR 35


N.show();
getch();
}

Result:

Program) WAP to increase and decrease an object’s value using unary++ and –
operator.
#include<iostream.h>
#include<conio.h>
class number
{
int x;
public:
number(int a) //constructor
{
x=a;
}
void show()
{
cout<<"value of x="<<x<<endl;
}
void operator++() //overloading unary ++operator
{
x=x+1;

TC Business School | BEST BCA College In JAIPUR 36


}
void operator--()
{
x=x-1;
}
};
void main()
{
clrscr();
number n1(11);
n1.show();
++n1;
n1.show();
--n1;
n1.show();
getch();
}

Result:

Program)
//Operator overloading Example to overload - operator as a unary operator

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

class oprminus
TC Business School | BEST BCA College In JAIPUR 37
{
inta,b,c;
public:
oprminus(ints,intt,int u)
{
a=s;
b=t;
c=u;
}

void operator-() // operator function defined to overload - operator as unary


operator
{
a=-a; // changes the values of a ,b and c
b=-b;
c=-c;
}

void showabc()
{
cout<<a<<" "<<b<<" "<<c<<endl;
}

};

int main()
{
oprminus o1(2,3,4);
cout<<"Value of a,b and c before function call :";
o1.showabc();
-o1; // operator - function will be called
cout<<"Value of a,b and c after function call :";
o1.showabc();
getch();
return 0;
}

Output

TC Business School | BEST BCA College In JAIPUR 38


Program)

// unary -- operator example for prefix

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

class unary
{
int a;
public:
unary()
{
a=5;
}

void operator--() // prefix representation of operator--() function


{
a=a-1;
}

void show()
{
cout<<a<<endl;
}
};

int main()
{
unary o;
cout<<"Value of a before function call :";
o.show();

--o; // unary minus operator-- prefix

cout<<"Value of a after function call :";


o.show();
getch();
return 0;
}

Output

TC Business School | BEST BCA College In JAIPUR 39


Program)
#include<iostream.h>
#include<conio.h>
class space
{
intx,y,z;
public:
void getdata(inta,intb,int c);
void display(void);
void operator-(); //overload unary minus
};
void space::getdata(inta,intb,int c)
{
x=a;
y=b;
z=c;
}
void space::display(void)
{
cout<<x<<" ";
cout<<y<" ";
cout<<" "<<z<<endl;
}
void space::operator-()
{
x=-x;

TC Business School | BEST BCA College In JAIPUR 40


y=-y;
z=-z;
}
void main()
{
clrscr();
space s;
s.getdata(10,-20,30);
cout<<"S:";
s.display();
-s; //activates operator-() function
cout<<"S:";
s.display();
getch();
}
Output

Operator Keyword
The keyword operator facilitates overloading of the c++ operators. The general format of
operator overloading
ReturnType operator operatorSymbol(arg)
The keyword operator indicates that the operator symbol following it, the c++ operator to
be overloading to operate on members of its class. The operator overloaded in a class
is known as overloaded operator function.

TC Business School | BEST BCA College In JAIPUR 41


Overloading without explicit arguments to an operator function is known as unary
operator overloadingand overloading with a single explicit argument is known as
binary operator overloading.

Overloading Binary operator


The binary overloaded operator function takes the first object as an implicit operand and
the second operand must be passed explicitly.
The data members of the first object are without using the dot operator,whereas the
second argument member can be accessed using the dot operator if the second
argument is an object.

Program)

//Operator overloading Example to overload + operator

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

class oprplus
{
int a;
public:
oprplus()
{
a=5;
}
oprplus(int s)
{
a=s;
}

void operator+(oprplus& o) // operator function defined to overload +


operator
{
cout<<a+o.a;
}
};

int main()
{

TC Business School | BEST BCA College In JAIPUR 42


oprplus o1,o2(6);

o1+o2; // calls the operator function defined for + operator

getch();
return 0;
}

Output

Program)
//Operator overloading Example to overload - operator

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

class oprminus
{
int a;
public:
oprminus()
{
a=5;
}
oprminus(int s)
{
a=s;
}

oprminus operator-(oprminus& o) // operator function defined to overload - operator


{
oprminus t;
t.a=a-o.a;
return t;
}

TC Business School | BEST BCA College In JAIPUR 43


void show()
{
cout<<a<<endl;
}
};

int main()
{
oprminus o1,o2(7),o3;
cout<<"o1.a :";
o1.show();
cout<<"o2.a :";
o2.show();
o3=o1-o2; // calls the operator function defined for + operator
cout<<"o3.a :";
o3.show();
getch();
return 0;
}

Output

Program)

//Operator overloading Example to overload = operator

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

class opr
{
int a;
public:
opr()
{
a=5;

TC Business School | BEST BCA College In JAIPUR 44


}
opr(int s)
{
a=s;
}

void operator=(opr& o) // operator function defined to overload = operator


{
a=2;
cout<<a;
}

};

int main()
{
opr o1,o2(4);
o1=o2;
getch();
return 0;
}

Output

Program)

// Overload << and >> operator to print a message to the screen

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

class opr
{
public:
void operator<<(opr& o)

TC Business School | BEST BCA College In JAIPUR 45


{
cout<<"<< operator is overloaded"<<endl;
}

void operator<<(int c)
{
cout<<"overloading of << on passing a value to the operator function"<<endl;
}

void operator>>(int d)
{
cout<<"Overload >> operator";
}
};

int main()
{
opr o1,o2;
o1<<o2;
o1<<4;
o1>>5;
getch();
return 0;
}

Output

Program)
// overload + using object+int and int+object

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

class opr
{
public:
void operator+(int c)
{

TC Business School | BEST BCA College In JAIPUR 46


cout<<"Object + integer "<<endl;
}

friend void operator+(ints,opr& o);

};
void operator+(ints,opr& o)
{
cout<<"integer + object"<<endl;
}

int main()
{
clrscr();
opr o;
o+10; //object + integer ang integer is passed
10+o; // this will not work without making operator function as a friend of
the class
getch();
return 0;
}

Output

3) Virtual function 
 If there is member function with same name in base class and derived class then
virtual functions give programming capability to call member function of different
class by a same function calling. This feature is known as ‘runtime
polymorphism” or “data binding”.

TC Business School | BEST BCA College In JAIPUR 47


 If a base class & derived class has some function & if you write the code to
access that function using pointer of base class then function in the base class is
executed,if the object of derived class is referenced with the pointer variable.
 In C++ the member function which can change at run time such member function
are called virtual function. Polymorphism means multiple ways to do the work in
function overloading and constructor overloading.
 In C++ a member function means declare as virtual by inside the keyword virtual
before its prototype any member function include constructor and destructors can
be declare as virtual. Virtual function can be overloaded like other member
function. There are various rules for the virtual function
1) The virtual function must be member of same class.
2) A virtual function can be a friend of another class.
3) A virtual function in a base class must be defined, even though it may not
be used.
4) A virtual function can not be static member.
5) They are accessed by using object pointers.
6) It a virtual function is defined in the base class, it need not be necessarily
redefined in the derived class. In such cases, call will invoke the base
function.

Program)
#include<iostream.h>
#include<conio.h>
class super
{
public:
void display()
{
cout<<"display super";
}
virtual void show()

TC Business School | BEST BCA College In JAIPUR 48


{
cout<<"\n show super";
}
};
class sub: public super
{
public:
void display()
{
cout<<"\n display sub";
}
void show()
{
cout<<"\n show sub";
}
};
void main()
{
clrscr();
super b;
sub d;
super *ptr;
ptr=&b;
ptr->display(); //super
ptr->show(); //super
d.show();
getch();
}

Result:

TC Business School | BEST BCA College In JAIPUR 49


Program)
#include<iostream.h>
#include<conio.h>
class A
{
int x;
public:
A()
{
x=1;
}
void show()
{
cout<<"base class="<<x<<endl;
}
};
class B: public A
{
int y;
public:
B()
{
y=2;
}
void show()
{
cout<<"child class="<<y;
}
};

void main()
{
A *p;
B ob;
clrscr();
p=&ob;
p->show();
TC Business School | BEST BCA College In JAIPUR 50
getch();
}

Output

Program)

// (Static or early binding )

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

class base
{
public:
virtual void show() // show() function of base
{
cout<<"Show base"<<endl;
}
};

class derived : public base


{
public:
void show() // show() function of derived
{
cout<<"Show derived"<<endl;
}
};

class derived1 : public derived


{
public:
void show() // show() function of derived
{
cout<<"Show derived"<<endl;
}
};
int main()
TC Business School | BEST BCA College In JAIPUR 51
{
derived *p,b; // base pointer and base object
derived1 d;

p=&d; // base pointer points to the derived class object


p->show(); // it calls the show() of base class

p=&b; // base pointer points to the base class object


p->show(); // it calls the show() of base class

getch();
return 0;
}

Output

Program)

//Virtual functions are hierarchical

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

class x
{
public:
virtual void fun()
{
cout<<"Base fun()"<<endl;
}
};

class y:public x
{
public:

TC Business School | BEST BCA College In JAIPUR 52


void fun()
{
cout<<"Class y fun()"<<endl;
}
};

class z:public x
{
public:

};

int main()
{
x *bp,ob;
y ob1;
z ob2;

bp=&ob;
bp->fun();

bp=&ob1;
bp->fun();

bp=&ob2;
bp->fun();

getch();
return 0;
}

Output

TC Business School | BEST BCA College In JAIPUR 53


Pure virtual function
 A pure virtual function is a function that has the notation “=0”; in the declaration of
that function.
 The “=0” notation of a pure virtual function is also known as pure specifier.
Because it is make such a pure virtual function is actually pure.
 A pure virtual function is a virtual function with no body.
 Since, pure virtual function has no body, the programmer must add the notation
=0 for declaration of the pure virtual function in the base class.
Syntex
Virtual fun_name()=0;

Program)

//Pure virtual function Example

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

class A //Pure Abstract class


{
int x;
public:
A()
{
x=1;
}

virtual void show()=0; //Pure virtual function


};

class B:public A
{
int y;
public:
B()
{
y=2;
}
void show()
{
cout<<"value of y="<<y;
TC Business School | BEST BCA College In JAIPUR 54
}
};

int main()
{
clrscr();
A *p;
B ob;
p=&ob;
p->show();
getch();
return 0;
}

Output

Program)

//Pure virtual function Example

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

class x //Pure Abstract class


{
protected:
intval;
public:
voidsetval(int i)
{
val=i;
}

virtual void show()=0; //Pure virtual function


};

class y:public x
{
public:
void show()
{
TC Business School | BEST BCA College In JAIPUR 55
cout<<val<<endl;
}
};

class z:public x
{
public:
void show()
{
cout<<val<<endl;
}
};

class w:public x
{
public:
void show()
{
cout<<val<<endl;
}
};

int main()
{
clrscr();
y o1;
z o2;
w o3;
//x o4;

o1.setval(10);
o1.show();
o2.setval(20);
o2.show();
o3.setval(30);
o3.show();
getch();
return 0;
}

Output

TC Business School | BEST BCA College In JAIPUR 56


UNIT-5

File Management: Handling data files (sequential and random), Opening and closing of
files, stream state member functions, operations on files, Templates, Exception
Handling.

Exception Handling
Introduction
An exception is a problem that arises during the execution of a program. In journal a
program must have bugs like
1) Logical error
2) Syntactic error
The logical error occur to poor understanding of the problem and the syntactic error
arise due to poor understanding of the language but when there is a problem in a
program other than logical or syntactic syntax error. There are known as exception.
Exception is run time or unusual conditions that a problem may execute. Some
condition such as division by zero, error index out of bounds exception or running out of
memory or disk space.
An exception is run-time error. When doing exception handling it consist of three
things
1) The detecting of a run-time error.
2) Raising an exception in response to the error, and
3) Taking corrective action.
In C++ for exception handling there is block syntax. For example
try
{
//In try block the code which is monitor for the exception is kept.
throw exception;

TC Business School | BEST BCA College In JAIPUR 57


----------------------
----------------------
}
catch(type arg)
{
// block of statements that handles the exception
----------------------
----------------------
}

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.
1) try: A try block identifies a block of code for which particular exceptions will be
activated. It is followed by one or more catch blocks.

2) 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.
And the error which is monitor in the try block is handle or catch by the
catch block. Each try block is follow by a catch block, multiple catch can be there
with a single try block so in a way the try block detect an exception and catch
block handle the exception. If matching close is found than its handler executing

TC Business School | BEST BCA College In JAIPUR 58


this process is repeated is until the exception is handle by a matching catch bock
and if they do not match, the program is aborted with the help of the abort()
function which is invoked by default.
When no exception is detected and thrown, the control goes to the
statement immediately after the catch block. That is, the catch block is skipped.
3) throw: A program throws an exception when a problem shows up. This is done
using a throw keyword.

You can list down multiple catch statements to catch different type of exceptions in
case your try block raises more than one exception in different situations.
try
{
// protected code
}catch( ExceptionName e1 )
{
// catch block
}catch( ExceptionName e2 )
{
// catch block
}catch( ExceptionName eN )
{
// catch block
}

//Note exception handling program runs on Dev c++ software

Program-1)

#include<iostream>

using namespace std;

class Excep
{
double a,b,c;

TC Business School | BEST BCA College In JAIPUR 59


public:
void getab()
{
cout<<"Enter value of a and b :";
cin>>a>>b;
}

void div()
{
try
{
if(b!=0)
{
c=a/b;
cout<<"Division a/b : "<<c;
}
else
throw b;
}
catch(double x)
{
cout<<"value of b should not be zero....";
}
}
};
int main()
{
Excep e;
e.getab();
e.div();
return 0;
}

Result:

TC Business School | BEST BCA College In JAIPUR 60


Program-2)
#include<iostream>

using namespace std;

class test
{
int num;
public:
void checkno(int n)
{
num=n;
try
{
if(n>10)
throw 1;
else
cout<<"Number is less than 10 ";
}
catch(int e)
{
cout<<"You should enter a number less than 10...";
}
}
};

int main()
{
int no;
test o;
cout<<"Enter any number :";
cin>>no;
o.checkno(no);
return 0;
}

Result:

TC Business School | BEST BCA College In JAIPUR 61


Program-3)

#include<iostream>
using namespace std;

class EvenOdd
{
int no,num[10];
double avg,sum;
public:
void checkno(int n)
{
no=n;
try
{
if(no%2==0)
{
getarr();
getavg();
}
else
{
throw 1;
}
}
catch(int i)
{
cout<<"Enter any even number to calculate average......";
}
}

void getarr()
{
cout<<"Enter "<<no<<" elements of array :"<<endl;

for(int i=0;i<no;i++)
{
cin>>num[i];
}
}

void getavg()
{
sum=0.0;
for(int i=0;i<no;i++)
{

TC Business School | BEST BCA College In JAIPUR 62


sum=sum+num[i];
}
avg=sum/no;
cout<<"Average of "<<no<<" numbers is :"<<avg;
}
};

int main()
{
EvenOdd o;
int n;
cout<<"Enter any number :";
cin>>n;
o.checkno(n);
return 0;
}

Result:

Program-4)
// Exception Handling ( Multiple catch Block )

#include<iostream>
using namespace std;

class Excep
{
int size,arr[];

public:
void getarr()
{
cout<<"Enter size of array :";

TC Business School | BEST BCA College In JAIPUR 63


cin>>size;
try
{
if((size>=1)&&(size<=5))
{
cout<<"Enter "<<size<<" elements :";
for(int i=0;i<size;i++)
{
cin>>arr[i];
}

showarr();
}
if(size>5)
throw 1;
if(size<1)
throw 'a';

}
catch(int x)
{
cout<<"Size should not be greater than 5";
}

catch(char y)
{
cout<<"Size should not be less than 1";
}
}

void showarr()
{
cout<<"Array elements are :";
for(int i=0;i<size;i++)
{
cout<<arr[i]<<" ";
}
}

};
int main()
{
Excep e;
e.getarr();
return 0;
}

TC Business School | BEST BCA College In JAIPUR 64


Result:

Program-5)
// Exception Handling ( Default catch block )

#include<iostream>
using namespace std;

class Excep
{
int eid;
int age;
public:
void getdata()
{
cout<<"Enter Employee ID :";
cin>>eid;
cout<<"Enter Age :";
cin>>age;
try
{
if(eid==5)
throw 1;
else
cout<<"Valid Employee id ,";

if(age==20)
throw 'c';
else
cout<<"Valid age ";
TC Business School | BEST BCA College In JAIPUR 65
}
catch(int i)
{
cout<<"Please Enter Eid other than 5";
}
catch(...) // Default catch block with elipses (...)
{
cout<<"Please Enter age other than 20";
}
}
};
int main()
{
Excep e;
e.getdata();
return 0;
}

Result:

Program-6)
// Exception Handling ( Base - Derived concept in Exception Handling )

#include<iostream>
using namespace std;

class base
{
public:

};

TC Business School | BEST BCA College In JAIPUR 66


class Derived : public base
{
public:

};

int main()
{
Derived d; // Derived class object

try
{
throw d; // throw the derived class object
}
catch(Derived d)
{
cout<<"Derived type exception ";
}
catch(base b)
{
cout<<"Base type Exception ";
}

return 0;
}

Result:

TC Business School | BEST BCA College In JAIPUR 67


Templates
Introduction
 Templates are the foundation of generic programming ( for all data type).
 Generic programming means it involves writing code in a way that is independent
of any particular type. For example if we are creating a function with (swap) so
this function will be applicable for all data types using generic program.
 A template is a blueprint for creating a generic class or a function .

template <class type> ret-type func-name(parameter list)


{
// body of function
}

Function Template
There are several functions which have to be used with different data type. The
limitation of such function is that they operate only on a particular data type it can be
overcomes by defining that function as a function template. A function template
specifies how an individual function can be constructed.
The general form of a template function definition is shown here:
template<class T>
returntype functionname(arguments of type T)
{
//body of function
// with type T
//…
}
We must use the template parameter T as and when necessary in the function body
and in its arguments list.

TC Business School | BEST BCA College In JAIPUR 68


Program)
#include<iostream.h>
#include<conio.h>
template<class T>
void swap(T &x, T&y)
{
T temp=x;
x=y;
y=temp;
}
void data(int x, int y, double a, double b)
{
cout<<"x and y before swap:"<<x<<" "<<y<<endl;
swap(x,y);
cout<<"x and y after swap:"<<x<<" "<<y<<endl;
cout<<"a and b before swap:"<<a<<" "<<b<<endl;
swap(a,b);
cout<<"a and b after swap:"<<a<<" "<<b<<endl;
}
void main()
{
clrscr();
data(125,65,18.22,44.56);
getch();
}

Result:

TC Business School | BEST BCA College In JAIPUR 69


Function templates with multiple parameters
Declaration of a function template
having multiple parameter of different data type requires multiple arguments.
The general format is as follows;
Template<class T1, class T2,…..>
returntype functionname(argument of types T1,T2)
{
//body of function
//…
}

Program)
#include<iostream.h>
#include<conio.h>
template<class T1,class T2>
void display(T1 a, T2 b)
{
cout<<a<<" "<<b<<endl;
}
void main()
{
clrscr();
display(2016,"Virendra education society");
getch();
TC Business School | BEST BCA College In JAIPUR 70
}
Result:

Overloading of template function


A template function may be overload either by
template function or ordinary function of ordinary name.
Program)
#include<iostream.h>
#include<conio.h>
template<class T>
void display(T a)
{
cout<<"Template display:"<<a<<endl;
}
void display(int a)
{
cout<<"Function display:"<<a<<endl;
}
void main()
{
clrscr();
display(260);
display(10.50);
getch();
}
Result:

TC Business School | BEST BCA College In JAIPUR 71


Assignment
Program-1) class template
#include<iostream.h>
#include<conio.h>
template <class T1,class T2>

class test
{
T1 a;
T2 b;
public:
test(T1 x,T2 y)
{
a=x;
b=y;
}

void show()
{
cout<<a<<" and "<<b<<"\n";
}
};

int main()
{
test <float,int> test1(1.23,123);
test <int,char> test2(100,'w');

TC Business School | BEST BCA College In JAIPUR 72


test1.show();
test2.show();
getch();
return 0;
}

Result:

Program-2)
//Function Template Example

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

template<class T>
T fun(T x)
{
return x*x;
}

int main()
{
int a=fun(2);
double b=fun(3.4);
cout<<a<<endl;

TC Business School | BEST BCA College In JAIPUR 73


cout<<b<<endl;
getch();
return 0;
}
Result:

Program-3)
//Overloading template function

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

template <class X> void swapargs(X &a, X &b)


{
X temp;
temp = a;
a = b;
b = temp;
cout << "Inside template swapargs.\n";
}
// This overrides the generic version of swapargs() for ints.
void swapargs(int &a, int &b)
{
int temp;
temp = a;
a = b;

TC Business School | BEST BCA College In JAIPUR 74


b = temp;
cout << "Inside swapargs int specialization.\n";
}
int main()
{
int i=10, j=20;
double x=10.1, y=23.3;
char a='x', b='z';
cout << "Original i, j: " << i << ' ' << j << '\n';
cout << "Original x, y: " << x << ' ' << y << '\n';
cout << "Original a, b: " << a << ' ' << b << '\n';
swapargs(i, j); // calls explicitly overloaded swapargs()
swapargs(x, y); // calls generic swapargs()
swapargs(a, b); // calls generic swapargs()
cout << "Swapped i, j: " << i << ' ' << j << '\n';
cout << "Swapped x, y: " << x << ' ' << y << '\n';
cout << "Swapped a, b: " << a << ' ' << b << '\n';
getch();
return 0;
}
Result:

TC Business School | BEST BCA College In JAIPUR 75


File Management

 This chapter we will see how C++ programmers can create, open, close test or binary
files for their data storage.

 A File represents a sequence of bytes. “C++” programming language provides access


on high level to handle file on your storage devices. A file is stored record in permanently
in a File.

(0, 1) Bit

Data (Collection of Bits is called Data)

File (Collection of Data is called File)

Folder (Collection of File is called Folder)

Record (Collection of Folder is called Record)

Directory

 When ever there is a need to handle large volume of the data, we store the data into the
file on the disk and we read when ever necessary a file is a place on the disk where a
group of related data is store.

Definition

 The information or data stored under a specific name on a storage device is


called a file.
 A File represents a sequence of bytes on the disk where a group related data is stored.
File is created for permanent storage of data. We use a pointer of file type to declare a
file.
 A file is a collection of letters, numbers and special characters: it may be a
program, a database, a reading list, a simple letter etc.

TC Business School | BEST BCA College In JAIPUR 76


 Sometimes you may import a file from else where, for example from another
computer. If you want to enter your own text or data, you will start by creating a
file.
 C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a
device likes a keyboard, a disk drive, or a network connection etc. to main
memory, this is called input operation and if bytes flow from main memory to a
device like a display screen, a printer, a disk drive, or a network connection, etc.,
this is called output operation.

Type of File

TC Business School | BEST BCA College In JAIPUR 77


File can be represented by two ways

1) Text File
It is a file that store information in ASCII character. In which every line is
terminating with special character know as EOF.
2) Binary File
It is a file that contains information in same formation as it is held in
memory. There is no need to terminate binary file.

File stream Operation

Stream class Hierarchy

Stream classes required for file I/O are

Function Description

1) ifstream  It is used to read a data file. Where i means input (for read) and f
means file.
 Ifstream means Input file stream class.
 Open() is a member function of class ifstream.
 Inherited function of ifstream class from the class istream
are
 get()
 getline()
 read()

TC Business School | BEST BCA College In JAIPUR 78


2) ofstream  It is used to write data on a file. Where o means output (for write)
and f means file.
 Ofstream means Output file stream class.
 Open() is a member function of class ofstream
 Inherited functions of ofstream class from the class ostream are
 put()
 write()

3) fstream  read write both from a file. fstream class to apply both read
write.
 It supports files for simultaneous input and output.
 fstream is derived from iostream class.
 Member functions of class fstream are:
 open()
 close()

Assignment

Program-1)

//File Handling ( writing - reading to the file ) use of open() to open a file

#include<iostream>
#include<fstream> // header file for file input - output operations
using namespace std;

class FileEx
{
char ch[30]; // character array to hold the data from file
fstream f; // file stream object
public:
void writeToFile() // Function to write to the file
{
f.open("D:\\File1",ios::out); // open a file in writing mode in E drive
f<<"Hello how are you ?"; // write line of text to the file through stream
f.close(); // close the stream
}
void showFromFile() // Function to read characters from file
{
f.open("D:\\File1",ios::in); // open file in reading mode
TC Business School | BEST BCA College In JAIPUR 79
while(f) // while file pointer goes to end of file
{
f.getline(ch,30); // getline function will get the maximum 30
characters and store it in ch array variable
cout<<ch; // display text on the screen
}
f.close(); // close() will close the association of file to stream
}
};
int main()
{
FileEx f; // class FileEx object
f.writeToFile(); // calls writeToFile() function
f.showFromFile(); // calls showFromFile() function
return 0;
}

Result:

Program-2)
//File Handling ( writing - reading to the file ) use of constructor to open file

//File Handling ( writing - reading to the file ) use of open() to open a file

#include<iostream>
#include<fstream> // header file for file input - output operations
using namespace std;

class FileEx
{
char ch[30]; // character array to hold the data from file
public:
void writeToFile() // Function to write to the file
{
fstream f("E:\\File2",ios::out); // file is opened in writing mode using
constructor
f<<"Hello how are you ?"; // write line of text to the file through stream
f.close(); // close the stream
}
void showFromFile() // Function to read characters from file
{
fstream f("E:\\File2",ios::in); // open file in reading mode
TC Business School | BEST BCA College In JAIPUR 80
while(f) // while file pointer goes to end of file
{
f.getline(ch,30); // getline function will get the maximum 30
characters and store it in ch array variable
cout<<ch; // display text on the screen
}
f.close(); // close() will close the association of file to stream
}
};
int main()
{
FileEx f; // class FileEx object
f.writeToFile(); // calls writeToFile() function
f.showFromFile(); // calls showFromFile() function
return 0;
}

Result:

Program-3)
//File Handling ( writing - reading to the file ) use of open() to open a file

#include<iostream>
#include<fstream> // header file for file input - output operations
using namespace std;

//File Handling ( writing - reading to the file ) use of ifstream and ofstream class

class FileEx
{
char ch; // character to get and put the data from file
fstream f;
public:
void writeToFile() // Function to write to the file
{
f.open("D:\\File4",ios::out); // ofstream class object for output operations
//f<<"Hello how are you ?"; // write line of text to the file through stream
cout<<"Enter text :";

while(cin>>ch) // while ch!= eof character


{
f.put(ch); //put() write characters one by one to the file
TC Business School | BEST BCA College In JAIPUR 81
}
f.close(); // close the stream
}
void showFromFile() // Function to read characters from file
{
f.open("D:\\File4",ios::in); // ifstream class object for input operations
while(f) // while file pointer goes to end of file
{
ch=f.get(); // get() function will characters
//one by one and store it in ch and display
cout<<ch; // display text on the screen
}
f.close(); // close() will close the association of file to stream
}
};
int main()
{
FileEx f; // class FileEx object
f.writeToFile(); // calls writeToFile() function
f.showFromFile(); // calls showFromFile() function
return 0;
}

Result:

Program-4)
//File Handling ( writing - reading to the file ) use of open() to open a file

#include<iostream>
#include<fstream> // header file for file input - output operations
using namespace std;

//File Handling ( writing - reading to the file ) use of ifstream and ofstream class

class FileEx
{
char ch; // character to get and put the data from file
fstream f;
public:

TC Business School | BEST BCA College In JAIPUR 82


void writeToFile() // Function to write to the file
{
f.open("E:\\File4",ios::out); // ofstream class object for output operations
//f<<"Hello how are you ?"; // write line of text to the file through stream
cout<<"Enter text :";

while(cin>>ch) // while ch!= eof character


{
f.put(ch); //put() write characters one by one to the file
}
f.close(); // close the stream
}
void showFromFile() // Function to read characters from file
{
f.open("E:\\File4",ios::in); // ifstream class object for input operations
while(f) // while file pointer goes to end of file
{
ch=f.get(); // get() function will characters
//one by one and store it in ch and display
cout<<ch; // display text on the screen
}
f.close(); // close() will close the association of file to stream
}
};
int main()
{
FileEx f; // class FileEx object
f.writeToFile(); // calls writeToFile() function
f.showFromFile(); // calls showFromFile() function
return 0;
}

Result:

Program-7)
//File Handling ( writing - reading to the file ) use of open() to open a file

#include<iostream>
TC Business School | BEST BCA College In JAIPUR 83
#include<fstream> // header file for file input - output operations
using namespace std;

//A program to check if the file exist if not then the file is created

int main()
{
char ch[30];
fstream f;

f.open("E:\\f.txt",ios::in);
f.close();
if(!f)
{
f.open("E:\\f.txt",ios::out);
cerr<<"New File created..";
f.close();
}
else
{

cout<<"Enter data for the file :";


f.open("E:\\f.txt",ios::out|ios::app);
while(cin.getline(ch,30))
{
f<<ch;
}

f.close();
}

return 0;
}

Result:

Program-7)
//A program which copies a file from one location to another

//File Handling ( writing - reading to the file ) use of open() to open a file

TC Business School | BEST BCA College In JAIPUR 84


#include<iostream>
#include<fstream> // header file for file input - output operations
using namespace std;

int main()
{
fstream f1,f2;
char ch[30];
f1.open("d:\\file3.txt",ios::out);
f1<<"hello how are you?";
f1.close();

f2.open("e:\\file4.txt",ios::out);
f1.open("d:\\file3.txt",ios::in);
while(f1)
{
f1.getline(ch,50);
f2<<ch;
}
if(f1.eof())
cout<<"File copied";
f1.close();
f2.close();
return 0;
}

Result:

TC Business School | BEST BCA College In JAIPUR 85

You might also like