0% found this document useful (0 votes)
202 views105 pages

C++ Programs

This document contains 6 C++ programs demonstrating dynamic memory allocation using new and delete operators, function overloading, constructor overloading, and copy constructors in C++. The programs allocate and initialize memory for basic data types, arrays, and user-defined classes. They show different ways to overload functions and constructors based on parameter types and counts. The summaries provided with each program explain the concepts demonstrated in the code.

Uploaded by

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

C++ Programs

This document contains 6 C++ programs demonstrating dynamic memory allocation using new and delete operators, function overloading, constructor overloading, and copy constructors in C++. The programs allocate and initialize memory for basic data types, arrays, and user-defined classes. They show different ways to overload functions and constructors based on parameter types and counts. The summaries provided with each program explain the concepts demonstrated in the code.

Uploaded by

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

NIT KURUKSHETRA

C++ ASSIGNMENT

Name:-Nishant Sharma
Roll No.:-11912090
Section:-CS-B(6)
Submitted to:-Manpreet Sir
(09/04/2020)DYNAMIC MEMORY ALLOCATION:

PROGRAM-1:
#include<iostream>
#include<new>
using namespace std;
int main()
{
int *p;
try {
p=new int;
//or if(!p){throw p;}
} catch (bad_alloc ex/*or int *p*/) {
cout<<"heap is full,thus exception generated.\n";
return 1;//unsuccessfull ending.
}
*p=10;
cout<<"the stored value is:\n"<<*p<<endl;
delete p;
return 0;
}
OUTPUT:

EXPLANATION:
New and delete operators are used to allocate and free memory at run
time respectively. Allocation statement should be surrounded with try-
catch block always. In the catch block, we catch the error and do
something about it. The catch statement takes a parameter. If no error
occurs, the catch block is skipped. New operator allocates memory and
return a pointer to the start of it. Delete operator frees previously
allocated memory using new. Throw keyword can also be used to output
a reference number.

PROGRAM-2:
#include<iostream>
#include<new>
using namespace std;
int main()
{
int *p;
try {
p=new int(10); // allocate memory and initilize at same
time
} catch (bad_alloc ex) {
cout<<"heap is full,thus exception generateed.\n";
return 1;
}
cout<<"the stored value is:"<<endl<<*p<<endl;
delete p;
return 0;
}
OUTPUT:

EXPLANATION:

In this program the allocation and initialization of memory was done in a


single statement. It’s syntax is: p_variable=new type(value);

PROGRAM-3:
#include<iostream>
#include<new>
using namespace std;
int main()
{
int i,*arr;
try {
arr=new int[10];
} catch (bad_alloc ex) {
cout<<"heap is full,thus exception is generated.\n";
return 1;
}
for(i=0;i<10;i++)
{
arr[i]=i+1;
}
cout<<"the data stored is:"<<endl;
for(i=0;i<10;i++)
{
cout<<arr[i]<<"\t";
}
cout<<endl;
delete [] arr;
return 0;
}
OUTPUT:

EXPLANATION:

In this program dynamic allocation of memory through integer is done.


It’s syntax is: p_variable=new arr_type[size];
PROGRAM-4:
#include<iostream>
#include<new>
using namespace std;
class Point{
int x;
int y;
public:
Point()
{
x=0;
y=0;
}
~Point()
{

}
void set_x(int x)
{
this->x=x;
}
void set_y(int y)
{
this->y=y;
}
int get_x()
{
return this->x;
}
int get_y()
{
return this->y;
}
};
int main()
{
Point *p;
try {
p=new Point;
} catch (bad_alloc ex) {
cout<<"heap is full,thus exception generated."<<endl;
return 1;
}
p->set_x(10);
p->set_y(20);
cout<<"x="<<p->get_x()<<endl<<"y="<<p-
>get_y()<<endl;
delete p;
return 0;
}

OUTPUT:

EXPLANATION:

In this program we have allocated and free class object’s memory.


Allocation of memory was done by using new operator to pointer to class.
Class’s data members were initialized using setters function of class.

PROGRAM-5:

#include<iostream>
#include<new>
using namespace std;
class Point{
int x;
int y;
public:
Point(int x,int y)
{
this->x=x;
this->y=y;
}
~Point()
{

}
void set_x(int x)
{
this->x = x;
}
void set_y(int y)
{
this->y = y;
}
int get_x() {
return this->x;
}
int get_y()
{
return this->y;
}
};
int main()
{
Point *p;
try {
p=new Point(10,20);
} catch (bad_alloc ex) {
cout<<"heap is full,thus exception generated.\n";
return 1;
}
cout<<"x="<<p->get_x()<<endl<<"y="<<p-
>get_y()<<endl;
delete p;
return 0;
}

OUTPUT:

EXPLANATION:

In this program we have allocated and free class object’s memory.


Allocation of memory was done by using new operator to pointer to class.
In this case initialization is done using parameterized constructor of class.

PROGRAM-6:

#include<iostream>
#include<new>
using namespace std;
class Point{
int x;
int y;
public:
Point()
{
x=0;
y=0;
}
~Point()
{

}
void set_x(int x)
{
this->x=x;
}
void set_y(int y)
{
this->y=y;
}
int get_x()
{
return this->x;
}
int get_y()
{
return this->y;
}
};
int main()
{
Point *p;
try {
p=new Point[3];
} catch (bad_alloc ex) {
cout<<"heap is full,thus exception generated."<<endl;
return 1;
}
p[0].set_x(10);
p[0].set_y(10);
p[1].set_x(20);
p[1].set_y(20);
p[2].set_x(30);
p[2].set_y(30);
for(int i=0;i<=2;i++)
{
cout<<i+1<<".x="<<p[i].get_x()<<endl<<"
y="<<p[i].get_y()<<endl;
}
delete [] p;
return 0;
}

OUTPUT:

EXPLANATION:

In this program allocation of memory is done at run time to class object’s


array using new operator. In case of normal pointer to access members of
class we use arrow operator(->) but in case of array we have used dot
operator (.).Initialization is done using setters.
(13/04/2020)Function overloading,constructor
overloading & copy constructor:

PROGRAM-1:

#include<iostream>
#include<new>
using namespace std;

int abs(int number)


{
if(number < 0)
return number * -1;
else
return number;
}

double abs(double number)


{
if(number < 0)
return number * -1.0;
else
return number;
}

int main(void)
{
cout<<abs(-20)<<"\n";// integer argument is passed so first
function will be called
cout<<abs(-30.30)<<"\n";// double argument is passed so
second function will be passed
return 0;
}

OUTPUT:
EXPLANATION:

In this program function overloading is done with different types of


parameters. This program will find absolute value of integer/float points
to be noted:-
1. same name of two functions "abs".
2. overloading with different parameter types .
3. No effect of return type on function overloading.

PROGRAM-2:
#include<iostream>
#include<new>
using namespace std;

int sum(int n1,int n2)


{
return n1+n2;
}

int sum(int n1,int n2,int n3)


{
return n1+n2+n2;
}

int main(void)
{
cout<<sum(10,20)<<"\n";// two arguments are passed so
first function will be called
cout<<sum(10,20,30)<<"\n";// three arguments are passed
so second function will be passed
return 0;
}

OUTPUT:

EXPLANATION:
In this program function overloading is done with different numbers of
parameters. There is no effect of return type on function overloading.

PROGRAM-3:

#include<iostream>
#include<new>
using namespace std;

int sum(int n1,int n2)// two integer arguments


{
return n1+n2;
}

int sum(int n1,int n2,int n3)//three integer arguments


{
return n1+n2+n3;
}

double sum(double n1,double n2)// two double arguments


{
return n1+n2;
}

double sum(double n1,int n2)// one integer and one double


type argument
{
return n1+n2;
}

int main(void)
{
cout<<sum(10,20)<<"\n";// two arguments are passed so
first function will be called
cout<<sum(20,20,30)<<"\n";// three arguments are passed
so second function will be passed
cout<<sum(10.10,20.20)<<"\n";
cout<<sum(10.10,20)<<"\n";
return 0;
}
OUTPUT:

EXPLANATION:

In this program mixture of function overloading with mixture of different


types and different number of parameters is done.

PROGRAM-4:

#include <iostream>
#include <cstdio>
using namespace std;
class date {
int day, month, year;

public:
date(const char *d) // constructor with string
argument
{
sscanf(d, "%d%*c%d%*c%d", &month, &day,
&year);
}
date(int m, int d, int y)// constructor with integer
arguments
{
day = d;
month = m;
year = y;
}
void show_date()
{
cout << month << "/" << day;
cout << "/" << year << "\n";
}
};

int main()
{
date ob1(12, 4, 2003); // second constructor will be called
date ob2("10/22/2003");// first constructor will be called
ob1.show_date();
ob2.show_date();
return 0;
}

OUTPUT:
EXPLANATION:

In this program constructor overloading is done. In this case same rules


are applied as of function overloading i.e. parameters that are passed
should of different type of differ in number of parameters.

PROGRAM-5:

#include <iostream>
#include <new>

using namespace std;

class powers {
int x;
public:
// overload constructor two ways
powers() { x = 0; } // no initializer
powers(int n) { x = n; } // initializer

int getx() { return x; }


void setx(int i) { x = i; }
};
int main()
{
powers ofTwo[] = {1, 2, 4, 8, 16}; // initialized
powers ofThree[5]; // uninitialized

powers *p;
int i;

// show powers of two


cout << "Powers of two: ";
for(i=0; i<5; i++)
{
cout << ofTwo[i].getx() << " ";
}
cout << "\n\n";

// set powers of three


ofThree[0].setx(1);
ofThree[1].setx(3);
ofThree[2].setx(9);
ofThree[3].setx(27);
ofThree[4].setx(81);
// show powers of three
cout << "Powers of three: ";
for(i=0; i<5; i++)
{
cout << ofThree[i].getx() << " ";
}
cout << "\n\n";

// dynamically allocate an array


try
{
p = new powers[5]; // no initialization
} catch (bad_alloc xa) {
cout << "Allocation Failure\n";
return 1;
}

// initialize dynamic array with powers of two


for(i=0; i<5; i++)
p[i].setx(ofTwo[i].getx());
// show powers of two
cout << "Powers of two: ";
for(i=0; i<5; i++)
cout << p[i].getx() << " ";
cout << "\n\n";
delete [] p;

return 0;
}

OUTPUT:

EXPLANATION:

In this program constructor is overloaded by defining one parameterized


and one non-parameterized constructor. In case of non-parameterized
constructor array of object should be initialized by setters whereas in case
of parameterized constructor array of object is initialized in same line
where the array of object is declared.

PROGRAM-6:
#include<iostream>
#include<new>
using namespace std;

class Point {
int x,y;
public:

Point()//default constructor
{
cout<<"Constructor is called\n";
}
~Point()//destructor
{
cout<<"destructor is called\n";
}

void setX(int x) {
this->x = x;
}
void setY(int y)
{
this->y = y;
}
int getX() {
return this->x;
}
int getY()
{
return this->y;
}
};

int main(void)
{
Point p1; // constructor will be called
p1.setX(10);
p1.setY(20);

Point p2 = p1;// no constructor will be called

return 0;
}

OUTPUT:

EXPLANATION:

In this program constructor will be called only once when creating object
p1. p2 will be using same memory as p1(copy will be bitwise copy), so no
constructor will be called for p2. But destructor will be called 2 times for
both p1 and p2, it means same memory is freed two times which is
undesirable. So this is an undesirable code.

PROGRAM-7:

#include<iostream>
#include<new>
using namespace std;

class Point {
int x,y;
public:
Point()//default constructor
{
cout<<"Constructor is called\n";
}

Point(Point &p)// copy constructor


{
cout<<"Copy constructor is called\n";
this->x = p.x;
this->y = p.y;
}

~Point()//destructor
{
cout<<"destructor is called\n";
}

void setX(int x) {
this->x = x;
}
void setY(int y)
{
this->y = y;
}
int getX() {
return this->x;
}
int getY()
{
return this->y;
}
};

int main(void)
{
Point p1; // constructor will be called
p1.setX(10);
p1.setY(20);
Point p2 = p1;// copy constructor is called here
return 0;
}
OUTPUT:

EXPLANATION:

In this program constructor will be called when creating object p1. p2 will
call copy constructor destructor will be called 2 times for both p1 and p2.
Thus this is a desirable code as copy constructor will be bypassing the
default bitwise copy.
Syntax of copy constructor is: classname (const classname &o)
{
// body of constructor
}

(18/04/2020)OPERATOR OVERLOADING:

PROGRAM-1:

#include <iostream>
using namespace std;

class loc
{
int longitude, latitude;
public:
// constructors are overloaded here
loc() {} //Default Constructor
loc(int lg, int lt) // Parameterized Constructor
{
longitude = lg;
latitude = lt;
}
void show() // show function to print longitude and
latitude
{
cout << longitude << " ";
cout << latitude << "\n";
}

loc operator+(loc op2); // declaration of operator


function
};

loc loc::operator+(loc op2) // defination of operator function


{
loc temp;
temp.longitude = op2.longitude + this->longitude;
temp.latitude = op2.latitude + this->latitude;
return temp;
}

int main()
{
loc ob1(10, 20), ob2( 5, 30);
ob1.show(); // displays 10 20
ob2.show(); // displays 5 30

ob1 = ob1 + ob2;


ob1.show(); // displays 15 50
return 0;
}

OUTPUT:

EXPLANATION:

In this program binary operator(+) is overloaded. in case of binary


operators first object will passed automatically and second object need to
pass explicitly. It is similar to normal member function call as member
function call automatically pass calling object to function.

PROGRAM-2:
#include <iostream>
using namespace std;

class loc
{
int longitude, latitude;
public:
loc() {} // needed to construct temporaries
loc(int lg, int lt)
{
longitude = lg;
latitude = lt;
}

void show()
{
cout << longitude << " ";
cout << latitude << "\n";
}

loc operator+(loc op2);// binary operator +


loc operator-(loc op2);// binary operator -s
loc operator=(loc op2);// unary operator =
loc operator++();// unary operator ++
};

// Overload + for loc.


loc loc::operator+(loc op2)
{
loc temp;
temp.longitude = op2.longitude + longitude;
temp.latitude = op2.latitude + latitude;
return temp;
}

// Overload - for loc.


loc loc::operator-(loc op2)
{
loc temp;
// notice order of operands
temp.longitude = this->longitude - op2.longitude;
temp.latitude = this->latitude - op2.latitude;
return temp;
}

// Overload asignment for loc.


loc loc::operator=(loc op2)
{
longitude = op2.longitude;
latitude = op2.latitude;
return *this; // i.e., return object that generated call
}

// Overload prefix ++ for loc.


loc loc::operator++()
{
longitude++;
latitude++;
return *this;
}

int main()
{
loc ob1(10, 20), ob2( 5, 30), ob3(90, 90);
ob1.show(); // show 10 20
ob2.show(); // show 5 30
++ob1; // call increment operator function
ob1.show(); // displays 11 21
ob2 = ++ob1; // call increment operator function will
increment ob1 ,
// then call = operator function and assign value to
ob2
ob1.show(); // displays 12 22
ob2.show(); // displays 12 22
ob1 = ob2 = ob3; // multiple assignment call will generate
from left side.
ob1.show(); // displays 90 90
ob2.show(); // displays 90 90
return 0;
}

OUTPUT:
EXPLANATION:

In this program unary operator(=) &(prefix++) are overloaded with binary


(+) and (-) operators. Multiple assignment call will generate from left side.

PROGRAM-3:

#include <iostream>
using namespace std;

class loc
{
int longitude, latitude;
public:
loc() {} // needed to construct temporaries
loc(int lg, int lt)
{
longitude = lg;
latitude = lt;
}

void show()
{
cout << longitude << " ";
cout << latitude << "\n";
}

loc operator++();// prefix operator ++


loc operator++(int x);//postfix operator ++
};
loc loc::operator++()
{
longitude++;
latitude++;
return *this; // *this means return object , this means
return pointer to object
// in this case we are returning object not pointer to
object
}
loc loc::operator++(int x)
{
longitude++;
latitude++;
return *this;
}

int main()
{
loc ob1(10, 20);
ob1.show(); // show 10 20

++ob1; // call prefix increment operator function


ob1.show(); // displays 11 21

ob1++; // call postfix


ob1.show(); // displays 12 22
return 0;
}

OUTPUT:
EXPLANATION:

In this program postfix and prefix ++ and -- operators were overloaded.


Syntax for prefix and postfix increment and decrement are :
// Prefix increment Same is for decrement operator.
type operator++( ) {
// body of prefix operator
}
// Postfix increment
type operator++(int x) {
// body of postfix operator
}
here x is temporary argument to differentiate weather function is for postfix or
prefix.
If temporary argument is passed then function is for postfix otherwise function
is for prefix operator.

PROGRAM-4:

#include <iostream>
using namespace std;

class loc
{
int longitude, latitude;
public:
loc() {} // needed to construct temporaries
loc(int lg, int lt)
{
longitude = lg;
latitude = lt;
}

void show()
{
cout << longitude << " ";
cout << latitude << "\n";
}

loc operator+=(loc ob2);// shorthand operator +=

};

// Overload prefix ++ for loc.


loc loc::operator+=(loc ob2)
{
longitude = longitude + ob2.longitude;
latitude = latitude + ob2.latitude;
return *this;
}

int main()
{
loc ob1(30,40),ob2(10, 20);
ob2.show(); // show 10 20
ob2.show(); // show 30 40
ob1 += ob2;
ob1.show(); // displays 40 60
return 0;
}

OUTPUT:
EXPLANATION:

In this program shorthand operators (+=) & prefix ++ were overloaded.


ob1 += ob2;-> In this statement call of += operator function ob1 passed
implicitly.

PROGRAM-5:

#include <iostream>
using namespace std;

class loc {
int longitude, latitude;
public:
loc() {} // needed to construct temporaries
loc(int lg, int lt) {
longitude = lg;
latitude = lt;
}
void show() {
cout << longitude << " ";
cout << latitude << "\n";
}

friend loc operator+(loc op1, loc op2); };

loc operator+(loc op1, loc op2)


{
loc temp;
temp.longitude = op1.longitude + op2.longitude;
temp.latitude = op1.latitude + op2.latitude;
return temp;
}
int main()
{
loc ob1(10, 20), ob2( 5, 30);
ob1 = ob1 + ob2;
ob1.show();
return 0;
}
OUTPUT:

EXPLANATION:

In this program binary operarors were overloaded using friend function.


Since a friend function is not a member of the class, it does not have a
this pointer. Therefore, an overloaded friend operator function is passed
the operands explicitly. This means that a friend function that overloads a
binary operator has two parameters, and a friend function that overloads
a unary operator has one parameter. When overloading a binary operator
using a friend function, the left operand is passed in the first parameter
and the right operand is passed in the second parameter.

PROGRAM-6:

#include <iostream>
using namespace std;

class loc {
int longitude, latitude;
public:
loc() {}
loc(int lg, int lt) {
longitude = lg;
latitude = lt;
}

void show() {
cout << longitude << " ";
cout << latitude << "\n";
}

loc operator=(loc op2);


friend loc operator++(loc &op);
friend loc operator--(loc &op);
};

// Overload assignment for loc.


loc loc::operator=(loc op2)
{
longitude = op2.longitude;
latitude = op2.latitude;
return *this; // i.e., return object that generated call
}

// Now a friend; use a reference parameter.


loc operator++(loc &op)
{
op.latitude++;
op.longitude++;
return op;
}
// Make op-- a friend; use reference.
loc operator--(loc &op)
{
op.longitude--;
op.latitude--;
return op;
}
int main()
{
loc ob1(10, 20), ob2;
ob1.show();
++ob1;
ob1.show(); // displays 11 21
ob2 = ++ob1;
ob2.show(); // displays 12 22
--ob2;
ob2.show(); // displays 11 21
return 0;
}
OUTPUT:

EXPLANATION:

In this program prefix ++ &-- were overloaded using friend functions.


I have passed the operand as a reference parameter in this case as friend
function don’t have this pointer.

PROGRAM-7:

#include <iostream>
using namespace std;

class loc {
int longitude, latitude;
public:
loc() {}
loc(int lg, int lt) {
longitude = lg;
latitude = lt;
}

void show() {
cout << longitude << " ";
cout << latitude << "\n";
}
friend loc operator+(loc op1, int op2);
friend loc operator+(int op1, loc op2);
};

// + is overloaded for loc + int.


loc operator+(loc op1, int op2)
{
loc temp;
temp.longitude = op1.longitude + op2;
temp.latitude = op1.latitude + op2;
return temp;
}

// + is overloaded for int + loc.


loc operator+(int op1, loc op2)
{
loc temp;
temp.longitude = op1 + op2.longitude;
temp.latitude = op1 + op2.latitude;
return temp;
}

int main()
{
loc ob1(10, 20), ob2( 5, 30), ob3(7, 14);
ob1.show();ob2.show();
ob3.show();
ob1 = ob2 + 10; // both of these
ob3 = 10 + ob2; // are valid
ob1.show();
ob3.show();
return 0;
}

OUTPUT:

EXPLANATION:

This program illustrates how friend functions are used to define an


operation that involves an object and built-in type. To allow both
object+integer and integer+object, simply I have overloaded the function
twice—one version for each situation. Thus, when you overload an
operator by using two friend functions, the object may appear on either
the left or right side of the operator.

PROGRAM-8:

#include <iostream>
#include <cstdlib>
#include <new>

using namespace std;

class loc {
int longitude, latitude;
public:
loc() {}
loc(int lg, int lt) {
longitude = lg;
latitude = lt;
}
void show() {
cout << longitude << " ";
cout << latitude << "\n";
}
void *operator new(size_t size);
void operator delete(void *p);
};

// new overloaded relative to loc.


void *loc::operator new(size_t size)
{
void *p;
cout << "In overloaded new.\n";
p = malloc(size);
if(!p) {
bad_alloc ba;
throw ba;
}
return p;
}
// delete overloaded relative to loc.
void loc::operator delete(void *p)
{
cout << "In overloaded delete.\n";
free(p);
}

int main()
{
loc *p1, *p2;
try {
p1 = new loc (10, 20);
} catch (bad_alloc xa) {
cout << "Allocation error for p1.\n";
return 1;
}

try {
p2 = new loc (-10, -20);
} catch (bad_alloc xa) {
cout << "Allocation error for p2.\n";
return 1;;
}
p1->show();
p2->show();
delete p1;
delete p2;
return 0;
}

OUTPUT:
EXPLANATION:

In this program new and delete operators were overloaded. To overload


the new and delete operators for a class, simply make the overloaded
operator functions class members. Syntax for this:-
// Allocate an object.
void *operator new(size_t size)
{
/* Perform allocation. Throw bad_alloc on failure.
Constructor called automatically. */
return pointer_to_memory;
}
// Delete an object.
void operator delete(void *p)
{
/* Free memory pointed to by p.
Destructor called automatically. */
}

(20/04/2020)INHERITANCE:
PROGRAM-1:

#include<iostream>
using namespace std;
class base
{
int i;
int j;
public:
void set(int a,int b)
{
i=a;
j=b;
}
void show()
{
cout<<"i="<<i<<"\nj="<<j<<endl;
}
};
class derived:public base{
int k;
public:
derived(int a)
{
k=a;
}
void showk()
{
cout<<"k="<<k<<endl;
}
};
int main()
{
derived ob(5);
ob.set(2,3);
ob.show();
ob.showk();
return 0;
}
OUTPUT:
EXPLANATION:

In this program single inheritance is done. In this case the members of the
base class will become members of the derived class. Class inheritance
uses this general form:-
class derived-class-name:access-specifier base-class-name{
//body of class.
}.Access-specifier must be either public, private or protected.
If no access specifier is specified then it is private by default in case of
class.

PROGRAM-2:

#include<iostream>
using namespace std;
class base
{
int i;
int j;
public:
void set(int a,int b)
{
i=a;
j=b;
}
void show()
{
cout<<"i="<<i<<"\nj="<<j<<endl;
}
};
class derived:private base
{
int k;
public:
void setb(int a,int b)//public member fxn in derived class to
access private member fxns in base class.
{
set(a,b);
}
void showb()
{
show();
}
derived(int a)
{
k=a;
}
void showk()
{
cout<<"k="<<k<<endl;
}
};
int main()
{
derived ob(5);
ob.setb(2,3);
ob.showb();
ob.showk();
return 0;
}

OUTPUT:
EXPLANATION:

In this program base class is inherited by using private access specifier.


Thus all public and protected member of base class will become private
member of derived class.Thus for code to be compiled I have made public
member function in derived class to access private member function of
base class.

PROGRAM-3:

#include <iostream>
using namespace std;
class base
{
protected:
int i,j;
public:
void set(int a,int b)
{
i=a;
j=b;
}
void show()
{
cout<<"i="<<i<<endl;
cout<<"j="<<j<<endl;
}
};
class derived1:public base
{
int k;
public:
void setk()
{
k=i*j;
}
void showk()
{
cout<<"k="<<k<<endl;
}
};
class derived2:public derived1
{
int m;
public:
void setm()
{
m=i-j;
}
void showm()
{
cout<<"m="<<m<<endl;
}
};
int main()
{
derived1 ob1;
derived2 ob2;
ob1.set(5,4);
ob1.show();
ob1.setk();
ob1.showk();
ob2.set(6,4);
ob2.show();
ob2.setk();
ob2.showk();
ob2.setm();
ob2.showm();
return 0;
}

OUTPUT:

EXPLANATION:

In this program multiple inheritance is done i.e. base to derived1,


derived1 to derived2.In this case base is inherited by derived1 as public
and because i and j are declared as protected, derived1's function setk( )
will access them. Derived1 class is used as a base class for another
derived2 class, thus any protected member of the initial base class that is
inherited (as public) by the first derived class will be inherited as
protected again by a second derived class.

PROGRAM-4:
// This program won't compile.
// example of multilevel inheritance base to drived1 and
drived1 to drived2

#include <iostream>
using namespace std;

class base {
protected:
int i, j;
public:
void set(int a, int b) { i=a; j=b; }
void show() { cout << i << " " << j << "\n"; }
};

// Now, all elements of base are private in derived1.


class derived1 : private base {
int k;
public:
// this is legal because i and j are private to derived1
void setk() { k = i*j; } // OK
//if i and j are private then this(👆🏻) will also shows an
error(important**)
void showk() { cout << k << "\n"; }
};

// Access to i, j, set(), and show() not inherited.


class derived2 : public derived1 {
int m;
public:
// illegal because i and j are private to derived1
void setm() { m = i-j; } // Error(*** very important)⦻
void showm() { cout << m << "\n"; }
};

int main()
{
derived1 ob1;
derived2 ob2;
ob1.set(1, 2); // error, can't use set()
ob1.show(); // error, can't use show()
ob2.set(3, 4); // error, can't use set()
ob2.show(); // error, can't use show()
return 0;
}

OUTPUT:

Program won’t compile.

EXPLANATION:

It’s explanation is in the comments of program that I have made.

PROGRAM-5:

// protected base class inheritance

#include <iostream>
using namespace std;

class base {
protected:
int i, j; // private to base, but accessible by derived
public:
void setij(int a, int b) { i=a; j=b; }
void showij() { cout << i << " " << j << "\n"; }
};

// Inherit base as protected.


class derived : protected base{
int k;
public:
// derived may access base's i and j and setij().
void setk() { setij(10, 12); k = i*j; }
// may access showij() here
void showall() { cout << k << " "; showij(); }
};

int main(){
derived ob;
//ob.setij(2, 3); // error/illegal, setij() is
// protected member of derived
ob.setk(); // OK, public member of derived
ob.showall(); // OK, public member of derived
// ob.showij(); // error/illegal, showij() is protected
// member of derived
return 0;
}

OUTPUT:

EXPLANATION:

It’s explanation is also is in the comments of program that I have made.

PROGRAM-6:

#include <iostream>
using namespace std;

class base1 {
protected:
int x;
public:
void showx() { cout << x << "\n"; }
};

class base2 {
protected:
int y;
public:
void showy() {cout << y << "\n";}
};

// Inherit multiple base classes.


class derived: public base1, public base2 {
public:
void set(int i, int j) { x=i; y=j; }
};

int main()
{
derived ob;
ob.set(10, 20); // provided by derived
ob.showx(); // from base1
ob.showy(); // from base2
return 0;
}

OUTPUT:
EXPLANATION:

In this program multiple base class were inherited as derived class


inherits both base1 and base2.
As the example illustrates for inherit more than one base class, comma-
separated list is being used and also access-specifier for each base class
inherited is being used.

PROGRAM-7:

#include <iostream>
using namespace std;

class base {
public:
base() { cout << "Constructing base\n"; }
~base() { cout << "Destructing base\n"; }
};

class derived1 : public base {


public:
derived1() { cout << "Constructing derived1\n"; }
~derived1() { cout << "Destructing derived1\n"; }
};

class derived2: public derived1 {


public:
derived2() { cout << "Constructing derived2\n"; }
~derived2() { cout << "Destructing derived2\n"; }
};

int main()
{
derived2 ob;
// construct and destruct ob
return 0;
}
OUTPUT:

EXPLANATION:

In this program it is observed that when an object of a derived class is


created, the base class’ constructor will be called first, followed by the
derived class’ constructor. When a derived object is destroyed, its
destructor is called first, followed by the base class' destructor. Thus the
general rule applies: Constructors are called in order of derivation,
destructors in reverse order.
PROGRAM-8:

#include <iostream>
using namespace std;

class base1 {
public:
base1() { cout << "Constructing base1\n"; }
~base1() { cout << "Destructing base1\n"; }
};

class base2 {
public:
base2() { cout << "Constructing base2\n"; }
~base2() { cout << "Destructing base2\n"; }
};

class derived: public base1, public base2 {


public:
derived() { cout << "Constructing derived\n"; }
~derived() { cout << "Destructing derived\n"; }
};

int main()
{
derived ob;
// construct and destruct ob
return 0;
}

OUTPUT:
EXPLANATION:

In this program calling sequence of constructors and destructors were


noted by multiple inheritance i.e. multiple base classes were inherited.

PROGRAM-9:
#include<iostream>
using namespace std;
class base
{
protected:
int i;
public:
base(int x)
{
i=x;
cout<<"constructing base.\n";
}
~base()
{
cout<<"destructing base.\n";
}
};
class derived:public base
{
int j;
public:
derived(int y,int x):base(x)
{
j=y;
cout<<"constructing derived.\n";
}
~derived()
{
cout<<"destructing derived.\n";
}
void showall()
{
cout<<"i="<<i<<endl;
cout<<"j="<<j<<endl;
}
};
int main()
{
derived ob(2,3);
ob.showall();
return 0;
}

OUTPUT:
EXPLANATION:

In this program we have passed parameters for base class constructors.


But for passing parameters to base class constructor an expanded form
of derived-class constructor declaration is used i.e.
derived-constructor(arg-list) : base1(arg-list),
base2(arg-list),
// ...
baseN(arg-list)
{
// body of derived constructor
}

PROGRAM-10:

#include <iostream>
using namespace std;

class base1 {
protected:
int i;
public:
base1(int x) { i=x; cout << "Constructing base1\n"; }
~base1() { cout << "Destructing base1\n"; }
};

class base2 {
protected:
int k;
public:
base2(int x) { k=x; cout << "Constructing base2\n"; }
~base2() { cout << "Destructing base1\n"; }
};

class derived: public base1, public base2 {


int j;
public:
derived(int x, int y, int z): base1(y), base2(z)
{ j=x; cout << "Constructing derived\n"; }
~derived() { cout << "Destructing derived\n"; }
void show() { cout << i << " " << j << " " << k <<
"\n"; }
};

int main()
{
derived ob(3, 4, 5);
ob.show(); // displays 4 3 5
return 0;
}

OUTPUT:
EXPLANATION:

In this program expanded derived class constructor is declared to pass


Arguments to multiple base classes as multiple inheritace is done here.

PROGRAM-11:

#include <iostream>
using namespace std;
class base1 {
protected:
int i;
public:
base1(int x) { i=x; cout << "Constructing base1\n"; }
~base1() { cout << "Destructing base1\n"; }
};
class base2 {
protected:
int k;
public:
base2(int x) { k=x; cout << "Constructing base2\n"; }
~base2() { cout << "Destructing base2\n"; }
};
class derived: public base1, public base2 {
public:
/* Derived constructor uses no parameter,
but still must be declared as taking them to
pass them along to base classes.
*/
derived(int x, int y): base1(x), base2(y)
{ cout << "Constructing derived\n"; }
~derived() { cout << "Destructing derived\n"; }
void show() { cout << i << " " << k << "\n"; }
};
int main()
{
derived ob(3, 4);
ob.show(); // displays 3 4
return 0;
}
OUTPUT:

EXPLANATION:
In this program derived class's constructor does not use any arguments, it
will still need to declare one if the base class requires it. In this situation,
the arguments passed to the derived class are simply passed along to the
base.

PROGRAM-12

#include <iostream>
using namespace std;

class base {
int i; // private to base
public:
int j, k;
void seti(int x) { i = x; }
int geti() { return i; }
};

// Inherit base as private.


class derived: private base {
public:
/* The next three statements override
base's inheritance as private and restore j,
seti(), and geti() to public access. */
using base::j; // make j public again - but not k
using base::seti; // make seti() public
using base::geti; // make geti() public
// base::i; // illegal, you cannot elevate access
int a; // public
};

int main()
{
derived ob;
//ob.i = 10; // illegal because i is private in derived
ob.j = 20; // legal because j is made public in derived
//ob.k = 30; // illegal because k is private in derived
ob.a = 40; // legal because a is public in derived
ob.seti(10);
cout << ob.geti() << " " << ob.j << " " << ob.a<<endl;
return 0;
}

OUTPUT:

EXPLANATION:

In this program I have granted certain public members of the base class
public status in the derived class even though the base class is inherited
as private. But a member declared as private in a base class cannot be
made public by a derived class.
Syntax for this is:- class derived: private base {
public:// here is access declaration
using base::j; // make j public again
};
PROGRAM-13:

#include<iostream>
using namespace std;
class base
{
public:
int i;
};
class derived1:public base
{
public:
int j;
};
class derived2:public base
{
public:
int k;
};
class derived3:public derived1,public derived2
{
public:
int sum;
void showall()
{

cout<<"i="<<derived1::i<<endl<<"j="<<j<<endl<<"k="<<
k<<endl;
}
};
int main()
{
derived3 ob;
ob.derived1::i=5;//if i is static?????
ob.j=10;
ob.k=15;
ob.sum=ob.derived1::i+ob.j+ob.k;
ob.showall();
cout<<"sum of i,j & k is:"<<endl<<ob.sum<<endl;
return 0;
}

OUTPUT:
EXPLANATION:

This program uses explicit scope resolution to select i. Derived3 inherits


both derived1 and derived2.
This means that there are two copies of base
in derived3. ob.derived1::i = 10; // scope resolved, use derived1's i.

PROGRAM-14:

#include<iostream>
using namespace std;
class base
{
public:
int i;
};
class derived1:virtual public base
{
public:
int j;
};
class derived2:virtual public base
{
public:
int k;
};
class derived3:public derived1,public derived2
{
public:
int sum;
void showall()
{

cout<<"i="<<i<<endl<<"j="<<j<<endl<<"k="<<k<<endl;
}
};
int main()
{
derived3 ob;
ob.i=5;//this is unambiguous as virtual base class has been
used thus no two copies of i are there (**imp)but also in
derived1 and derived2 base is still present in object of either
type.
ob.j=10;
ob.k=15;
ob.sum=ob.i+ob.j+ob.k;
ob.showall();
cout<<"sum of i.j & k is:"<<endl<<ob.sum<<endl;
return 0;
}

OUTPUT:
EXPLANATION:

In this program virtual base class has been used derived3 inherits both
derived1 and derived2.
This time, there is only one copy of base class.
Now ob.i = 10;->this statement is now unambiguous.

(21/04/2020)VIRTUAL FUNCTION:
PROGRAM-1:
#include <iostream>
using namespace std;

class base {
public:
virtual void vfunc() {
cout << "This is base's vfunc().\n";
}
};

class derived1 : public base {


public:
void vfunc() {//function overriding
cout << "This is derived1's vfunc().\n";
}
};

class derived2 : public base {


public:
void vfunc() {//function overriding
cout << "This is derived2's vfunc().\n";
}
};

int main()
{
base *p, b;
derived1 d1;
derived2 d2;
// point to base
p = &b;
p->vfunc(); // access base's vfunc()
// point to derived1
p = &d1;
p->vfunc(); // access derived1's vfunc()
// point to derived2
p = &d2;
p->vfunc(); // access derived2's vfunc()
return 0;
}
OUTPUT:

EXPLANATION:
In this program function overriding is done which means if derived class
has function with same name as base class(base class function should be
public so it can be derived) then it is called overridden function and this
concept is called function overriding. Function overriding means two
functions has same name but different code. inside base, the virtual
function vfunc( ) is declared.Notice that the keyword virtual precedes the
rest of the function declaration. When vfunc( ) is redefined by derived1
and derived2, the keyword virtual is not needed. In this program, base is
inherited by both derived1 and derived2. Inside each class definition,
vfunc( ) is redefined relative to that class.
PROGRAM-2:
#include<iostream>
using namespace std;
class base
{
public:
virtual void vfunc()
{
cout<<"virtual function of base is called."<<endl;
}
};
class derived1:public base
{
public:
void vfunc()
{
cout<<"virtual function of derived1 is called."<<endl;
}
};
class derived2:public base
{
public:
void vfunc()
{
cout<<"virtual function of derived2 is called."<<endl;
}
};
void f(base &x)
{
x.vfunc();
}
int main()
{
base b;
derived1 d1;
derived2 d2;
f(b);
f(d1);
f(d2);
return 0;
}

OUTPUT:
EXPLANATION:
In this program virtual fxn is called through a base class reference.
Syntax for this is:- Use a base class reference parameter.
void f(base &r) {
r.vfunc();
}

PROGRAM-3:
#include<iostream>
using namespace std;
class base
{
public:
virtual void vfun()
{
cout<<"virtual fxn of base class is called."<<endl;
}
};
class derived1:public base
{
public:
void vfun()
{
cout<<"virtual fxn of derived1 class is called."<<endl;
}
};
class derived2:public derived1
{
public:
void vfun()
{
cout<<"virtual fxn of derived2 class is called."<<endl;
}
};
void f1(base &x)
{
x.vfun();
}
int main()
{
base b;
derived1 d1;
derived2 d2;
f1(b);
f1(d1);
f1(d2);
return 0;
}

OUTPUT:
EXPLANATION:
In this program multilevel inheritance is done but derived2 inherits virtual
function vfunc() from derived1 which implies When a virtual function is
inherited, its virtual nature is also inherited. This means that when a
derived class that has inherited a virtual function is itself used as a base
class for another derived class, the virtual function can still be overridden.
Put differently, no matter how many times a virtual function is inherited,
it remains virtual.

PROGRAM-4:
#include <iostream>
using namespace std;

class base {
public:
virtual void vfunc() {
cout << "This is base's vfunc().\n";
}
};

class derived1 : public base {


public:
void vfunc() {
cout << "This is derived1's vfunc().\n";
}
};

class derived2 : public base {


public:
// vfunc() not overridden by derived2, base's is used
};

int main()
{
base *p, b;
derived1 d1;
derived2 d2;
// point to base
p = &b;
p->vfunc(); // access base's vfunc()
// point to derived1
p = &d1;
p->vfunc(); // access derived1's vfunc()
// point to derived2
p = &d2;
p->vfunc();

return 0;
}

OUTPUT:
EXPLNATION:
In this program derived2 class do not override vfun(). But when vfun()
through derived2’s class’s object’s address is called it will call base’s
class’s vfun() which tells us that virtual functions are hierarchical in nature
as derived2 class inherits base class.

PROGRAM-5:
#include<iostream>
using namespace std;
class base
{
public:
virtual void vfun()
{
cout<<"virtual fxn of base's class is called."<<endl;
}
};
class derived1:public base
{
public:
void vfun()
{
cout<<"virtual fxn of derived1's class is called."<<endl;
}
};
class derived2:public derived1
{
public:
//no vfun is overridden in derived2's class thus when vfun of
this class is called then vfun of class from which it is derived is
called.
//thus in this case derived1's vfun is called.
//this is done because virtual fxns are hierarchical.
};
void f(base &x)
{
x.vfun();
}
int main()
{
base b;
derived1 d1;
derived2 d2;
f(b);
f(d1);
f(d2);//vfun of derived1's class is called.
return 0;
}

OUTPUT:
EXPLANATION:
In this program derived2 class do not override vfun().Thus when calling
vfun() for derived2 class derived1’s vfun() is used as derived2 class is
derived from derived1 class.

PROGRAM-6:
#include<iostream>
using namespace std;
class number
{
protected:
int num;
public:
void set(int i)
{
num=i;
}
virtual void show()=0;//pure virtual function.
};
class hextype:public number
{
public:
void show()
{
cout<<"number in hexadecimal form
is:"<<endl<<hex<<num<<endl;
}
};
class dectype:public number
{
public:
void show()
{
cout<<"number in decimal form
is:"<<endl<<num<<endl;
}
};
class octtype:public number
{
public:
void show()
{
cout<<"number in octal form
is:"<<endl<<oct<<num<<endl;
}
};
int main()
{
hextype h;
dectype d;
octtype o;
d.set(20);
d.show();//if i put dectype object under hextype then
d.show() is showing hexadecimal number.WHY????****
h.set(20);
h.show();
o.set(20);
o.show();
return 0;
}
OUTPUT:

EXPLANATION:
This program contains example of pure virtual function. A pure virtual
function is a virtual function that has no definition within the base
class. To declare a pure virtual function,this general form is used:
virtual type func-name(parameter-list) = 0;
When a virtual function is made pure, any derived class must provide its
own definition. If the derived class fails to override the pure virtual
function, a compile-time error will result. . The base class, number,
contains an integer called val, the function setval( ), and the pure virtual
function show( ). The derived classes hextype, dectype, and octtype
inherit number and redefine show( ) so that it outputs the value of val in
each respective number base (that is, hexadecimal, decimal, or octal).

PROGRAM-7:
#include<iostream>
using namespace std;
class convert
{
protected:
double val1;//initial value.
double val2;//converted value.
public:
convert(double i)
{
val1=i;
}
virtual void compute()=0;//pure virtual function.
double getinit_val()
{
return val1;
}
double getcon_val()
{
return val2;
}
};
class derived_l_to_g:public convert//litres to gallons.
{
public:
derived_l_to_g(double i):convert(i){}
void compute()
{
val2=val1/3.7854;
}
};
class derived_f_to_c:public convert//farenheit to celsius.
{
public:
derived_f_to_c(double i):convert(i){}
void compute()
{
val2=(val1-32)/1.8;
}
};
int main()
{ convert *p;
derived_l_to_g ltg(5);
derived_f_to_c ftc(50);
p=&ltg;
p->compute();
cout<<p->getinit_val()<<"_litres="<<p-
>getcon_val()<<"_gallons"<<endl<<endl;
p=&ftc;
p->compute();
cout<<p->getinit_val()<<"℉="<<p-
>getcon_val()<<"℃"<<endl;
return 0;
}
OUTPUT:

EXPLANATION:

In this program practical example of virtual function has been shown.


Example that illustrates the value of the "one interface,multiple
methods" philosophy.
One of the most powerful and flexible ways to implement the "one
interface,multiple methods" approach is to use virtual functions, abstract
classes, and run-time polymorphism. Using these features, you create a
class hierarchy that moves from general to specific (base to derived).
(23/04/2020)FILE HANDLING:
PROGRAM-1:

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ofstream out("INVNTRY"); // output, normal file
if(!out) {
cout << "Cannot open INVENTORY file.\n";
return 1;
}

out << "Radios " << 39.95 << endl;


out << "Toasters " << 19.95 << endl;
out << "Mixers " << 24.80 << endl;
out.close();
return 0;
}
OUTPUT:

EXPLANATION:

To read from or write to a text file we can simply use the << and >>
operators the same way you do when performing console I/O, except
that instead of using cin and cout, substitute a stream that is linked to a
file. This program creates a short inventory file that contains each item's
name and its cost.

PROGRAM-2:

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ifstream in("INVNTRY"); // input
if(!in) {
cout << "Cannot open INVENTORY file.\n";
return 1;
}
char item[20];
float cost;
in >> item >> cost;
cout << item << " " << cost << "\n";
in >> item >> cost;
cout << item << " " << cost << "\n";
in >> item >> cost;
cout << item << " " << cost << "\n";
in.close();
return 0;
}

OUTPUT:
EXPLANATION:

This program reads the inventory file created by the previous program
and displays its contents on the screen.

PROGRAM-3:

#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char *argv[])


{
if(argc!=2) {
cout << "Usage: output <filename>\n";
return 1;
}

ofstream out(argv[1]); // output, normal file


if(!out) {
cout << "Cannot open output file.\n";
return 1;
}

char str[80];
cout << "Write strings to disk. Enter ! to stop.\n";
do {
cout << ": ";
cin >> str;
out << str << endl;
} while (*str != '!');
out.close();
return 0;
}

OUTPUT:

EXPLANATION:
This program reads strings entered at the keyboard and writes them to
disk. The program stops when the user enters an exclamation point. To
use the program, specify the name of the output file on the
command line.
PROGRAM-4:
#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char *argv[])


{
char ch;
if(argc!=2) {
cout << "Usage: PR <filename>\n";
return 1;
}

ifstream in(argv[1], ios::in | ios::binary);


if(!in) {
cout << "Cannot open file.";
return 1;
}
while(in) { // in will be false when eof is reached
in.get(ch);
if(in) cout << ch;
}
return 0;
}

OUTPUT:
EXPLANATION:
This program displays the contents of any file, whether it contains text or
binary data, on the screen. It uses the get( ) function. The get( ) function
reads a single character from the invoking stream and puts that value in
ch. It returns a reference to the stream.

PROGRAM-5:
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
int i;
ofstream out("CHARS", ios::out | ios::binary);
if(!out) {
cout << "Cannot open output file.\n";
return 1;
}

// write all characters to disk


for(i=0; i<256; i++) out.put((char) i);
out.close();
return 0;
}

OUTPUT:

EXPLANATION:

The next program uses put( ) to write all characters


from zero to 255 to a file called CHARS. The put( )
function writes ch to the stream and returns a
reference to the stream.
PROGRAM-6:
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

struct status {
char name[80];
double balance;
unsigned long account_num;
};

int main()
{
struct status acc;strcpy(acc.name, "Ralph Trantor");
acc.balance = 1123.23;
acc.account_num = 34235678;
// write data
ofstream outbal("balance", ios::out | ios::binary);
if(!outbal) {
cout << "Cannot open file.\n";
return 1;
}
outbal.write((char *) &acc, sizeof(struct status));
outbal.close();

// now, read back;


ifstream inbal("balance", ios::in | ios::binary);
if(!inbal) {
cout << "Cannot open file.\n";
return 1;
}
inbal.read((char *) &acc, sizeof(struct status));
cout << acc.name << endl;
cout << "Account # " << acc.account_num;
cout.precision(2);
cout.setf(ios::fixed);
cout << endl << "Balance: $" << acc.balance;
inbal.close();
return 0;
}

OUTPUT:
EXPLANATION:
This program writes a structure to disk and then reads it back in:
It is using read() and write() functions to read and write blocks of binary
data. The read( ) function reads num characters from the invoking stream
and puts them in the buffer pointed to by buf. The write( ) function writes
num characters to the invoking stream from the buffer pointed to by buf.

PROGRAM-7:
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
double fnum[4] = {99.75, -34.4, 1776.0, 200.1};
int i;
ofstream out("numbers", ios::out | ios::binary);
if(!out) {
cout << "Cannot open file.";
return 1;
}
out.write((char *) &fnum, sizeof fnum);
out.close();
for(i=0; i<4; i++) // clear array
fnum[i] = 0.0;
ifstream in("numbers", ios::in | ios::binary);
in.read((char *) &fnum, sizeof fnum);
// see how many bytes have been read
cout << in.gcount() << " bytes read\n";
for(i=0; i<4; i++) // show values read from file
cout << fnum[i] << " ";in.close();
return 0;
}

OUTPUT:
EXPLANATION:
This program shows another example of read( ) and write( ) and
illustrates the use of gcount( ): If the end of the file is reached before num
characters have been read, then read( ) simply stops, and the buffer
contains as many characters as were available. You can find out how
many characters have been read by using another member function,
called gcount( ), which has this prototype:
streamsize gcount();

PROGRAM-8:
#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char *argv[])


{
if(argc!=2) {
cout << "Usage: Display <filename>\n";
return 1;
}

ifstream in(argv[1]); // input


if(!in) {
cout << "Cannot open input file.\n";
return 1;
}
char str[255];
while(in) {
in.getline(str, 255); // delim defaults to '\n'
if(in) cout << str << endl;
}
in.close();
return 0;
}
OUTPUT:

EXPLANATION:
This program demonstrates the getline( ) function. It reads the contents
of a text file one line at a time and displays it on the screen. Function that
performs input is getline( ). It is a member of each input stream class. Its
prototypes are shown here:
istream &getline(char *buf, streamsize num);
istream &getline(char *buf, streamsize num, char delim);

PROGRAM-9:
#include <iostream>
#include <fstream>
#include <cctype>
#include <iomanip>
using namespace std;

int main(int argc, char *argv[])


{
if(argc!=2) {
cout << "Usage: Display <filename>\n";
return 1;
}
ifstream in(argv[1], ios::in | ios::binary);

if(!in) {
cout << "Cannot open input file.\n";
return 1;
}
register int i, j;
int count = 0;
char c[16];
cout.setf(ios::uppercase);
while(!in.eof()) {
for(i=0; i<16 && !in.eof(); i++) {
in.get(c[i]);
}

if(i<16) i--; // get rid of eof


for(j=0; j<i; j++)
cout << setw(3) << hex << (int) c[j];
for(; j<16; j++) cout << " ";
cout << "\t";
for(j=0; j<i; j++)
if(isprint(c[j])) cout << c[j];
else cout << ".";
cout << endl;
count++;
if(count==16) {
count = 0;
cout << "Press ENTER to continue: ";
cin.get();
cout << endl;
}
}
in.close();
return 0;
}

OUTPUT:
EXPLANATION:
This program uses eof( ) to display the contents of a file in both
hexadecimal and ASCII.The end of the file is reached by using the member
function eof( ), which has this prototype:
bool eof( );
It returns true when the end of the file has been reached; otherwise it
returns false.

PROGRAM-10:
#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

int main(int argc, char *argv[])


{
if(argc!=4) {
cout << "Usage: CHANGE <filename> <character>
<char>\n";
return 1;
}
fstream out(argv[1], ios::in | ios::out | ios::binary);
if(!out) {
cout << "Cannot open file.";
return 1;
}
out.seekp(atoi(argv[2]), ios::beg);
out.put(*argv[3]);
out.close();
return 0;
}

OUTPUT:

EXPLANATION:
This program demonstrates the seekp( ) function. It allows you to change
a specific character in a file. Specify a filename on the command line,
followed by the number of the character in the file you want to change,
followed by the new character. The seekp( ) function moves the
associated file's current put pointer offset number of characters from the
specified origin, which must be one of these values:
ios::beg //beginning of file ios::cur //current location ios::end//end of file

PROGRAM-11:
#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

int main(int argc, char *argv[])


{
char ch;
if(argc!=3) {
cout << "Usage: SHOW <filename> <starting
location>\n";
return 1;
}

ifstream in(argv[1], ios::in | ios::binary);


if(!in) {
cout << "Cannot open file.";
return 1;
}

in.seekg(atoi(argv[2]), ios::beg);
while(in.get(ch))
cout << ch;
return 0;
}

OUTPUT:
EXPLANATION:
This program uses seekg( ). It displays the contents of a file beginning
with the location you specify on the command line. The seekg( ) function
moves the associated file's current get pointer offset number of
characters from the specified origin, which must be one of these three
values:
ios::beg //beginning of file ios::cur //current location ios::end//end of file

PROGRAM-12:
#include <iostream>
#include <fstream>

using namespace std;

void checkstatus(ifstream &in);

int main(int argc, char *argv[])


{
if(argc!=2) {
cout << "Usage: Display <filename>\n";
return 1;
}

ifstream in(argv[1]);
if(!in) {
cout << "Cannot open input file.\n";
return 1;
}

char c;
while(in.get(c)) {
if(in) cout << c;
checkstatus(in);
}

checkstatus(in); // check final status


in.close();
return 0;
}

void checkstatus(ifstream &in)


{
ios::iostate i;
i = in.rdstate();
if(i & ios::eofbit)
cout << "EOF encountered\n";
else if(i & ios::failbit)
cout << "Non-Fatal I/O error\n";
else if(i & ios::badbit)
cout << "Fatal I/O error\n";
}

OUTPUT:
EXPLANATION:
There are two ways in which you can obtain I/O status information. First,
you can call the rdstate( ) function. It has this prototype:
iostate rdstate( );
It returns the current status of the error flags. rdstate( ) returns goodbit
when no error has occurred. Otherwise, an error flag is turned on.
This program will always report one "error." After the while loop ends.
the final call to checkstatus( ) reports, as expected, that an EOF has been
encountered.

PROGRAM-13:
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
class phonebook {
char name[80];
char areacode[4];
char prefix[4];
char num[5];

public:
phonebook() { };
phonebook(char *n, char *a, char *p, char *nm)
{
strcpy(name, n);
strcpy(areacode, a);
strcpy(prefix, p);
strcpy(num, nm);
}
friend ostream &operator<<(ostream &stream,
phonebook o);
friend istream &operator>>(istream &stream,
phonebook &o);
};

// Display name and phone number.


ostream &operator<<(ostream &stream, phonebook o)
{
stream << o.name << " ";
stream << "(" << o.areacode << ") ";
stream << o.prefix << "-";
stream << o.num << "\n";
return stream; // must return stream
}

// Input name and telephone number.


istream &operator>>(istream &stream, phonebook &o)
{
cout << "Enter name: ";
stream >> o.name;
cout << "Enter area code: ";
stream >> o.areacode;
cout << "Enter prefix: ";
stream >> o.prefix;
cout << "Enter number: ";
stream >> o.num;
cout << "\n";
return stream;
}

int main()
{
phonebook a;
char c;
fstream pb("phone", ios::in | ios::out | ios::app);
if(!pb) {
cout << "Cannot open phone book file.\n";
return 1;
}
for(;;) {
do {
cout << "1. Enter numbers\n";
cout << "2. Display numbers\n";
cout << "3. Quit\n";
cout << "\nEnter a choice: ";
cin >> c;
} while(c<'1' || c>'3');
switch(c) {
case '1':
cin >> a;
cout << "Entry is: ";
cout << a; // show on screen
pb << a; // write to disk
break;
case '2':
char ch;
pb.seekg(0, ios::beg);
while(!pb.eof()) {
pb.get(ch);
if(!pb.eof()) cout << ch;
}
pb.clear(); // reset eof
cout << endl;
break;
case '3':
pb.close();
return 0;
}
}
}

OUTPUT:
EXPLANATION:
The other way that you can determine if an error has occurred is by using
one or more of these functions:
bool bad( ); bool eof( ); bool fail( ); bool good( );
The bad( ) function returns true if badbit is set. The eof( ) function was
discussed earlier. The fail( ) returns true if failbit is set. The good( )
function returns true if there are no errors. Otherwise, it returns false.
Once an error has occurred, it may need to be cleared before your
program continues. To do this, use the clear( ) function, which has this
prototype:
void clear(iostate flags=ios::goodbit);
If flags is goodbit (as it is by default), all error flags are cleared. Otherwise,
set flags as you desire.
This program do the same as mentioned above.

THANK YOU

You might also like