C++ Programs
C++ Programs
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:
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:
}
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:
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:
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:
PROGRAM-1:
#include<iostream>
#include<new>
using namespace std;
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:
PROGRAM-2:
#include<iostream>
#include<new>
using namespace std;
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 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:
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:
PROGRAM-5:
#include <iostream>
#include <new>
class powers {
int x;
public:
// overload constructor two ways
powers() { x = 0; } // no initializer
powers(int n) { x = n; } // initializer
powers *p;
int i;
return 0;
}
OUTPUT:
EXPLANATION:
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);
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()//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";
}
int main()
{
loc ob1(10, 20), ob2( 5, 30);
ob1.show(); // displays 10 20
ob2.show(); // displays 5 30
OUTPUT:
EXPLANATION:
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";
}
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:
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";
}
int main()
{
loc ob1(10, 20);
ob1.show(); // show 10 20
OUTPUT:
EXPLANATION:
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";
}
};
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:
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";
}
EXPLANATION:
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";
}
EXPLANATION:
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);
};
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:
PROGRAM-8:
#include <iostream>
#include <cstdlib>
#include <new>
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);
};
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:
(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:
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:
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"; }
};
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:
EXPLANATION:
PROGRAM-5:
#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"; }
};
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:
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";}
};
int main()
{
derived ob;
ob.set(10, 20); // provided by derived
ob.showx(); // from base1
ob.showy(); // from base2
return 0;
}
OUTPUT:
EXPLANATION:
PROGRAM-7:
#include <iostream>
using namespace std;
class base {
public:
base() { cout << "Constructing base\n"; }
~base() { cout << "Destructing base\n"; }
};
int main()
{
derived2 ob;
// construct and destruct ob
return 0;
}
OUTPUT:
EXPLANATION:
#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"; }
};
int main()
{
derived ob;
// construct and destruct ob
return 0;
}
OUTPUT:
EXPLANATION:
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:
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"; }
};
int main()
{
derived ob(3, 4, 5);
ob.show(); // displays 4 3 5
return 0;
}
OUTPUT:
EXPLANATION:
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; }
};
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:
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";
}
};
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";
}
};
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=<g;
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:
#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;
}
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;
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;
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;
}
OUTPUT:
EXPLANATION:
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();
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>
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;
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;
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]);
}
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>
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>
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>
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);
}
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);
};
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