Chapter 5
Example 1 : Program to find area of rectangle & Perimeter
#include<iostream.h>
#include<conio.h>
class rectangle
{
private :
int len, br;
public:
void area_peri( );
//prototype declaration, to be defined
void getdata ( )
{
cout<<endl<<"Enter length and breadth ";
cin>>len>>br;
}
void setdata (int l, int b )
{
len = l;
br = b;
}
void displaydata( )
{
cout<<endl<<"length = "<<len;
cout<<endl<<"breadth = "<<br;
}
};
//Member Function Definition
void rectangle :: area_peri( )
{
int a, p;
a = len * br;
p = 2 * (len +br);
cout<<endl<<"Area = "<<a;
cout<<endl<<"Perimeter = "<<p;
}
//Main Program..
void main( )
{
rectangle r1,r2,r3;
//define 3 objects of class rectangle
r1.setdata(10,20);
//set data in elements of the object
r1.displaydata( );
//display the data set by setdata( )
r1.area_peri( );
// calculates and print area and Perimeter
r2.setdata(5,8);
r2.displaydata( );
r2.area_peri( );
r3.getdata( );
r3.displaydata( );
r3.area_peri( );
}
//receive data from keyboard
Example 2 : Array of Objects
#include <iostream.h>
#include <string.h>
/*----------------------Class definition-----------------------*/
class student
{
int roll_no;
char name[20];
public :
// prototypes declared
void set_data(int, char *);
void print_data();
};
void student::set_data(int c, char *s)
{
roll_no = c;
strcpy(name, s);
}
void student::print_data()
{
cout << "Roll No. : " << roll_no << "\t";
cout << "Name : " << name << "\n\n";
}
/*--------------------Definition ends here-------------------*/
void main(void)
{
student array[10];
// Array of Objects declared
int i;
char names[10][10] = {"kush", "stavan", "poonam", "sachi", "samarth", "hetal",
"trupti",
"simone", "shalaka", "megha"};
// accessing member of an object where the object is an array element
for (i=0; i<10; i++)
array[i].set_data(i, names[i]);
cout << "The data output is :\n\n";
for (i=0; i<10; i++)
array[i].print_data();
}
Example 3 :
#include<iostream.h>
class Account
{
int acc_no;
float amount;
char acc_type;
public:
Account(){}
Account(int no,float bal,char type='S')
{
acc_no=no;
amount=bal;
acc_type=type;
}
void display()
{
cout<<"\nAccount No. : "<<acc_no;
cout<<"\nBalance : "<<amount;
cout<<"\nAccount Type : "<<acc_type;
}
};
void main()
{
Account a1,a2;
int no;
float bal;
char type;
cout<<"\nEnter Account Number, Balance and Account type";
cin>>no>>bal>>type;
a1=Account(no,bal,type);
cout<<"\nEnter Account Number, Balance";
cin>>no>>bal;
a2=Account(no,bal);
a1.display();
a2.display();
}
Example 4 :
#include<iostream.h>
#include<conio.h>
#include<string.h>
class bank
{
private:
char name[20],type[20];
int acno,bal,wit,dep;
public:
bank()
{
strcpy(name,"Rina");
acno=5;
bal=500;
strcpy(type,"Saving");
}
void deposit()
{
cout<<"\nEnter amt to deposit :";
cin>>dep;
bal=bal+dep;
show();
}
void withdraw()
{
cout<<"\nEnter amt to withdraw :";
cin>>wit;
if(bal-wit>=500)
bal=bal-wit;
else
cout<<"\nYou cannot withdraw";
show();
}
void show()
{
cout<<"\nDepositor name :"<<name<<endl;
cout<<"\nBalance :"<<bal<<endl;
}
};
void main()
{
bank bk;
clrscr();
bk.deposit();
bk.withdraw();
getch();
}
Example 5 : Overloading Binary '+' Operator as a friend function
#include <iostream.h>
#include<conio.h>
/*----------------------Class definition-------------------------*/
class sample
{
int a;
int b;
public :
sample() { }
// default empty constructor
sample(int, int);
// Overloaded binary addition operator as a friend
friend sample operator + (sample, sample);
void print();
};
sample::sample(int x, int y)
{
a = x;
b = y;
}
void sample::print()
{
cout << "a = " << a << "\n";
cout << "b = " << b << "\n";
}
/*----------------------Definition ends here---------------------*/
// Overloaded binary addition operator as a friend function
// Returns an object as a value of the addition
sample operator + (sample p, sample q)
{
sample temp;
temp.a = p.a + q.a;
temp.b = p.b + q.b;
return temp;
}
void main(void)
clrscr();
sample A(5,10), B(5,5), C;
cout << "The result of the addition is :\n";
C = A + B;
// invocation of the operator function
C.print();
cout << "\nSecond method of invocation of operator function-\n";
cout << "The result of the addition is :\n";
C = operator + (A,B); // different way of invocation
C.print();
Example 6 : Overloading Binary '+' Operator as a friend function
#include <iostream.h>
/*----------------------Class definition-------------------------*/
class sample
{
int a;
int b;
public :
sample() { }
sample(int, int);
// default empty constructor
// Overloaded binary addition operator as a friend
friend sample operator + (sample, sample);
void print();
};
sample::sample(int x, int y)
{
a = x;
b = y;
}
void sample::print()
{
cout << "a = " << a << "\n";
cout << "b = " << b << "\n";
}
/*----------------------Definition ends here---------------------*/
// Overloaded binary addition operator as a friend function
// Returns an object as a value of the addition
sample operator + (sample p, sample q)
{
return sample(p.a+q.a, p.b+q.b);
}
void main(void)
{
sample A(5,10), B(5,5), C;
cout << "The result of the addition is :\n";
C = A + B;
// invocation of the operator function
C.print();
cout << "\nSecond method of invocation of operator function-\n";
cout << "The result of the addition is :\n";
C = operator + (A,B); // different way of invocation
C.print();
}
Example 7 : Binary '+' Operator Overloading
#include <iostream.h>
/*----------------------Class definition-------------------------*/
class sample
{
int a;
int b;
public :
sample() { }
// default empty constructor
sample(int, int);
// Overloaded binary addition operator
sample operator + (sample);
void print();
};
sample::sample(int x, int y)
{
a = x;
b = y;
}
// Overloaded binary addition operator as a member function
// Returns an object as a value of the addition
sample sample::operator + (sample x)
{
sample temp;
temp.a = a + x.a;
temp.b = b + x.b;
return temp;
}
void sample::print()
{
cout << "a = " << a << "\n";
cout << "b = " << b << "\n";
}
/*----------------------Definition ends here---------------------*/
void main(void)
{
sample A(5,10), B(5,5), C;
cout << "The result of the addition is :\n";
C = A + B;
// invocation of the operator function
C.print();
cout << "\nSecond method of invocation of operator function- \n";
cout << "The result of the addition is :\n";
C = A.operator + (B); // different way of invocation
C.print();
}
Example 8 :
#include<iostream.h>
#include<conio.h>
class book
{
int bid;
int balance;
int received;
int sold;
public:
void getdata()
{
cout<<"\nEnter Book Id: ";
cin>>bid;
cout<<"\nEnter inventory balance at the begining of the month : ";
cin>>balance;
cout<<"\nNumber of copies received during the month : ";
cin>>received;
cout<<"\nNumber of copies sold during the month : ";
cin>>sold;
}
void display()
{
cout<<"\nBook Id: "<<bid;
cout<<"\nUpdated Balance : "<<balance;
}
void update()
{
balance=balance+received-sold;
}
};
void main()
{
book b[5];
clrscr();
for(int i=0;i<5;i++)
{
b[i].getdata();
b[i].update();
b[i].display();
}
getch();
}
Example 9 :
#include<iostream.h>
#include<conio.h>
class complex
{
float x,y;
public:
complex() { }
complex(float a) {x=y=a;}
complex(float real,float imag)
{x=real;y=imag;}
void show()
{
cout<<x<<"+j"<<y;
}
void sum(complex,complex);
};
void complex::sum(complex c1,complex c2)
{
x = c1.x + c2.x;
y = c1.y + c2.y;
}
void main()
{
clrscr();
complex A(8.7,2.5);
complex B(2.6);
complex C;
clrscr();
C.sum(A,B);
C.show();
getch();
}
Example 10 : Constructor with Default Arguments
#include <iostream.h>
#include<conio.h>
class real
{
int integer_part;
int fractional_part;
public :
real(int, int);
void print_data();
};
real::real(int in, int fr=0) // Constructor with default argument
{
integer_part = in;
fractional_part = fr;
}
void real::print_data()
{
cout << "Number : " << integer_part << ".";
cout << fractional_part << "\n";
}
void main(void)
{ clrscr();
real A1(12);
real A2(121,34);
A1.print_data();
A2.print_data();
}
Example 11 :
#include <iostream.h>
#include<conio.h>
class real
{
int integer_part;
int fractional_part;
public :
real(){}
real(int a)
{
integer_part=a;
fractional_part=a;
}
real(int a, int b)
{
integer_part=a;
fractional_part=b;
}
void sum(real,real);
void print_data();
};
void real::sum(real r1,real r2)
{
integer_part=r1.integer_part+r2.integer_part;
fractional_part=r1.fractional_part+r2.fractional_part;
}
void real::print_data()
{
cout << "Number : " << integer_part << ".";
cout << fractional_part << "\n";
}
void main(void)
{
clrscr();
real r1;
real r2(12);
real r3(121,34);
r2.print_data();
r3.print_data();
r1.sum(r1,r2);
r1.print_data();
getch();
}
Example 12 : Program : 'const' Objects
#include <iostream.h>
#include<conio.h>
class sample
{
int a, b;
public:
sample(int, int);
sample() { }
void display() const; // 'const' member function prototype
~sample() { }
};
sample::sample(int x, int y)
{
a = x; b = y;
}
void sample::display() const // 'const' member function defined
{
cout << "a = " << a << "\t";
cout << "b = " << b << "\n";
}
void main(void)
{
clrscr();
const sample A(10,20);
// 'const' Object declaration
A.display();
// 'const' object invoking 'const' member
function
getch();
}
Example 13 : 'const' Member Functions
#include <iostream.h>
#include<conio.h>
/*----------------------Class definition-------------------------*/
class sample
{
int num;
public :
void set(int);
void print_number( ) const; // 'const' member function prototype
};
void sample::set(int n)
{
num = n;
}
void sample::print_number( ) const // 'const' member function definition
{
cout << "Number = " << num << "\n";
}
/*----------------------Definition ends here---------------------*/
void main(void)
{
clrscr();
sample a;
a.set(10);
a.print_number( );
getch( );
}
Example 14 :
#include<iostream.h>
#include<conio.h>
class Sample
{
int a;
float b;
public:
Sample(); //constructor
Sample(Sample &ptr);
void display();
};// end of class
Sample::Sample()
{
a=10;
b=20.75;
}
// copy constructor
Sample::Sample(Sample &ptr)
{
a=ptr.a;
b=ptr.b;
}
void Sample::display()
{
cout<<"\na : "<<a<<endl;
cout<<"\nb : "<<b<<endl;
}
void main(void)
{
clrscr();
Sample s1;
s1.display();
Sample s2(s1);
s2.display();
getch();
}//end of main
Example 15 : Data Conversion using Type Operator
#include <iostream.h>
#include <string.h>
#include<conio.h>
/*----------------------Class definition-------------------------*/
class data
{
int no_of_items;
float cost_per_item;
public:
data(int, float);
// type operator
operator float() {return (no_of_items * cost_per_item);}
};
data::data(int a, float b)
{
no_of_items = a;
cost_per_item = b;
}
/*----------------------Definition ends here---------------------*/
void main(void)
{
clrscr();
data d(10, 2.5);
cout << "The result returned by the type operator : ";
cout << d.operator float() << "\n";
getch();
}
Example 16 : A Simple Constructor
#include <iostream.h>
#include <string.h>
#include<conio.h>
class sample
{
char itemname[20];
int cost;
public :
sample();
// Constructor declaration
void print_data();
};
sample::sample()
// Constructor definition
{
strcpy(itemname,"Pencil");
cost = 5;
}
void sample::print_data()
{
cout << "Item : " << itemname << "\n";
cout << "Cost : " << cost << "\n";
}
void main(void)
{
clrscr();
sample A;
A.print_data();
getch();
}
Example 17 : Program Destructor Illustrated
#include <iostream.h>
#include<conio.h>
int no_of_objects = 0;
// Global Declaration
class sample
{
public:
sample();
~sample();
// Destructor Declaration
};
sample::sample()
{
no_of_objects++;
cout << "No of object created " << no_of_objects;
cout << "\n";
}
sample::~sample()
// Destructor Definition
{
cout << "No of object Destroyed " << no_of_objects;
cout << "\n";
no_of_objects--;
}
void main(void)
{
clrscr();
void function();
// prototype
cout << "\nMAIN Entered\n";
sample s1, s2, s3;
{
cout << "\nBLOCK-1 Entered\n";
sample s4, s5;
}
function();
{
cout << "\nBLOCK-2 Entered\n";
sample s7;
}
cout << "\nMAIN Re-Entered\n";
getch();
}
void function()
{
cout << "\nFUNCTION Entered\n";
sample s6;
Example 18 : Program Destruction using 'delete' Operator
#include <iostream.h>
#include <string.h>
#include <stdlib.h>
#include<conio.h>
class string
{
char *s;
int length;
public:
string();
string(char*);
~string();
};
string::string()
{
length = 0;
s = new char[length + 1];
s[0] = '\0'; // empty string
}
string::string(char *str)
{
length = strlen(str);
s = new char[length + 1];
strcpy(s,str);
}
string::~string()
{
delete s;
cout << "One Object deleted...\n";
}
void main(void)
{
clrscr();
string s1("Good "),s2("Morning"),s3;
getch();
}
// Destructor declaration
// Destructor definition
Example 19 : Program Dynamic Construction of Objects
#include <iostream.h>
#include <string.h>
#include <stdlib.h>
#include<conio.h>
class string
{
char *s;
int length;
public:
string();
string(char*);
void concat(string&);
void print_string();
};
string::string()
{
length = 0;
s = new char[length + 1];
s[0] = '\0';
// empty string
}
string::string(char *str)
{
length = strlen(str);
s = new char[length + 1];
strcpy(s,str);
}
void string::concat(string& instring)
{
length = length + instring.length;
strcat(s,instring.s);
}
void string::print_string()
{
cout.width(12);
cout << s;
cout.width(11);
cout << "Length = " << length << "\n";
}
void main(void)
{
clrscr();
string s1("Good "),s2("Morning"),s3;
s3.concat(s1);
s3.concat(s2);
s1.print_string();
s2.print_string();
s3.print_string();
getch();
}
Example 20 : Friend Classes
#include <iostream.h>
#include<conio.h>
class time
{
int seconds;
friend class date;
// friend class declared
public :
void set(int);
};
void time::set(int n)
{
seconds = n;
}
class date
{
int day, month, year;
public :
void set(int, int, int);
void print_date();
void print_time(time);
};
void date::set(int d, int m, int y)
{
day = d; month = m; year = y;
}
void date::print_date()
{
cout << "Date : " << day << "/"
<< month << "/"
<< year << "\n";
}
void date::print_time(time t)
{
int h = t.seconds / 3600,
m = (t.seconds % 3600) / 60;
cout << "Time : " << h << ":" << m << "\n";
}
void main(void)
{
clrscr();
date todays_date;
time current_time;
todays_date.set(16,2,2002);
current_time.set(12000);
todays_date.print_date();
todays_date.print_time(current_time);
getch();
}
Example 21 : Friend Functions
#include <iostream.h>
#include<conio.h>
class time
{
int seconds;
public :
void set(int);
friend void print_time(time); // Friend function Declaration
};
void time::set(int n)
{
seconds = n;
}
void print_time(time dt) // Friend function definition
{
int h = dt.seconds / 3600,
// Friend function can access
m = (dt.seconds % 3600) / 60;
// private data members
cout << "Time : " << h << ":" << m << "\n";
}
void main(void)
{
clrscr();
time current_time;
current_time.set(12000);
print_time(current_time);
getch();
}
Example 22 : Friend function- bridge between classes
#include <iostream.h>
#include<conio.h>
class date;
// declaration to cater the forward reference
class time
{
int seconds;
public :
void set(int);
friend void print_datetime(date,time);
};
void time::set(int n)
{
seconds = n;
}
class date
{
int day, month, year;
public :
void set(int, int, int);
friend void print_datetime(date,time);
};
void date::set(int d, int m, int y)
{
day = d; month = m; year = y;
}
void print_datetime(date d, time t) // Friend function definition
{
int h = t.seconds / 3600,
m = (t.seconds % 3600) / 60;
cout << "Date : " << d.day << "/"
<< d.month << "/"
<< d.year << "\n";
cout << "Time : "
<< h << ":" << m << "\n";
}
void main(void)
{
clrscr();
date todays_date;
time current_time;
todays_date.set(16,2,2002);
current_time.set(12000);
print_datetime(todays_date, current_time);
getch();
}
Example 23 :
#include <iostream.h>
#include <conio.h>
class DB;
class DM
{
int meters;
float centimeters;
public:
void getdata()
{
cout<<"\nEnter Meter : ";
cin>>meters;
cout<<"\nEnter Centimeter : ";
cin>>centimeters;
}
friend void add(DM dm, DB db, int ch);
};
class DB
{
int feet;
float inches;
public:
void getdata()
{
cout<<"\nEnter Feet : ";
cin>>feet;
cout<<"\nEnter Inches : ";
cin>>inches;
}
friend void add(DM dm, DB db, int ch);
};
void add(DM dm, DB db, int ch)
{
if(ch==1)
{
//Result in meter-centimeter
dm.centimeters=dm.centimeters+(db.feet*30)+(db.inches*2.4);
while(dm.centimeters>=100)
{
dm.meters++;
dm.centimeters=dm.centimeters-100;
}
cout<<"\nMeter : "<<dm.meters;
cout<<"\nCentimeters : "<<dm.centimeters;
}
else
if(ch==2)
{
//Result in feet-inches
db.inches=db.inches+(dm.centimeters+dm.meters*100)/2.4;
while(db.inches>=12)
{
db.feet++;
db.inches=db.inches-12;
}
cout<<"\nFeet : "<<db.feet;
cout<<"\nInches : "<<db.inches;
}
else
cout<<"\nWrong input!!!";
}
void main()
{
DM dm;
DB db;
int ch;
int ans=1;
do
{
clrscr();
dm.getdata();
db.getdata();
cout<<"\n1.Meter-Centimeter";
cout<<"\n2.Feet-Inches";
cout<<"\nEnter your choice : ";
cin>>ch;
add(dm,db,ch);
cout<<"\nDo u want to continue?(1/0):";
cin>>ans;
}
while(ans==1);
getch();
}
Example 24 : Program : Global Constructor and Destructor
#include <iostream.h>
#include<conio.h>
/*----------------------Class definition-------------------------*/
class sample
{
int x;
public:
sample();
int get_data() { return x; }
~sample();
// Destructor Declaration
};
sample::sample()
{
cout << "Executing the Constructor...\n\n";
}
sample::~sample()
// Destructor Definition
{
cout << "\nExecuting the Destructor...\n";
}
/*----------------------Definition ends here---------------------*/
sample globalobj;
// global object
void main(void)
{
cout << "Entering MAIN...\n";
cout << "x = " << globalobj.get_data() << "\n";
cout << "Exiting MAIN...\n";
getch();
}
Example 25 : Inline Constructor
#include <iostream.h>
#include <string.h>
#include<conio.h>
class sample
{
char itemname[20];
int cost;
public :
sample(char* s, int c) // Inline Constructor
{
strcpy(itemname,s);
cost = c;
}
void print_data();
};
void sample::print_data()
{
cout << "Item : " << itemname << "\n";
cout << "Cost : " << cost << "\n";
}
void main(void)
{
clrscr();
sample A("MyItem", 100);
A.print_data();
getch();
}
Example 26 : Inline Constructor
#include <iostream.h>
#include <string.h>
#include<conio.h>
class sample
{
char itemname[20];
int cost;
public :
sample(char*, int);
void print_data();
};
inline sample::sample(char* s, int c) // Inline Constructor
{
strcpy(itemname,s);
cost = c;
}
void sample::print_data()
{
cout << "Item : " << itemname << "\n";
cout << "Cost : " << cost << "\n";
}
void main(void)
{
clrscr();
sample A("MyItem", 100);
A.print_data();
getch();
}
Example 27 : Inline Functions versus Macros
#include <iostream.h>
#include<conio.h>
#define sqr(a) a*a
// Macro definition
inline int square (int a)
// inline function definition
{
return (a*a);
}
void main(void)
{
clrscr();
cout << "Square(10) = " << square(10);
cout << "\nSquare(10+10) = " << square(10+10);
cout << "\nSqr(10) = " << sqr(10);
cout << "\nSqr(10+10) = " << sqr(10+10);
getch();
}
Example 28 : Inline Member Functions
#include <iostream.h>
#include<conio.h>
/*----------------------Class definition-------------------------*/
class sample
{
int a;
public :
// inline member functions
void setdata(int x)
{
a = x;
}
void print_square() {cout << "sqr(a) = " << a*a << "\n";}
void print_cube();
};
// inline member function
inline void sample::print_cube()
{
cout << "cube(a) = " << a*a*a << "\n";
}
/*----------------------Definition ends here---------------------*/
void main(void)
{
clrscr();
sample num;
num.setdata(10);
num.print_square();
num.print_cube();
getch();
}
Example 29 :
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<process.h>
const int true=1;
const int false=0;
class matrix
{
int maxrow;
int maxcol;
int m[10][10];
public:
matrix()
{
maxrow=0;maxcol=0; }
matrix(int row,int col)
{
maxrow=row;
maxcol=col;
}
void read();
void show();
void add(matrix a,matrix b);
void sub(matrix a,matrix b);
void mul(matrix a,matrix b);
int eq1(matrix b);
};
void matrix :: add(matrix a, matrix b)
{
int i,j;
maxrow=a.maxrow;
maxcol=a.maxcol;
if(a.maxrow!=b.maxrow ||a.maxcol!=b.maxcol)
{
cout<<"\nInvalid order of matrix";
exit(0);
}
for(i=0;i<maxrow;i++)
{
for(j=0;j<maxcol;j++)
m[i][j]=a.m[i][j]+b.m[i][j];
}
}
void matrix :: sub(matrix a, matrix b)
{
int i,j;
maxrow=a.maxrow;
maxcol=a.maxcol;
if(a.maxrow!=b.maxrow ||a.maxcol!=b.maxcol)
{
cout<<"\nInvalid order of matrix";
exit(0);
}
for(i=0;i<maxrow;i++)
{
for(j=0;j<maxcol;j++)
m[i][j]=a.m[i][j]-b.m[i][j];
}
}
void matrix :: mul(matrix a, matrix b)
{
int i,j,k;
maxrow=a.maxrow;
maxcol=a.maxcol;
if(a.maxcol!=b.maxrow)
{
cout<<"\nInvalid order of matrix";
exit(0);
}
for(i=0;i<maxrow;i++)
{
for(j=0;j<maxcol;j++)
{
m[i][j] =0;
for(k=0;k<maxcol;k++)
m[i][j]=m[i][j]+a.m[i][k]*b.m[k][j];
}
}
}
int matrix::eq1(matrix b)
{
int i,j;
for(i=0;i<maxrow;i++)
for(j=0;j<maxcol;j++)
if(m[i][j]!=b.m[i][j])
return 0;
return 1;
}
void matrix::read()
{
int i,j;
for(i=0;i<maxrow;i++)
for(j=0;j<maxcol;j++)
{
cout<<"matrix["<<i<<","<<j<<"]=";
cin>>m[i][j];
}
}
void matrix ::show()
{
int i,j;
for(i=0;i<maxrow;i++)
{
cout<<"\n";
for(j=0;j<maxcol;j++)
cout<<m[i][j]<<" ";
}
}
void main()
{
int m,n,p,q;
clrscr();
cout<<"\nEnter matrix A :";
cout<<"\nEnter rows : ";
cin>>m;
cout<<"\nEnter cols : ";
cin>>n;
matrix a(m,n);
a.read();
cout<<"\nEnter matrix B : ";
cout<<"\nEnter rows : ";
cin>>p;
cout<<"\nEnter cols : ";
cin>>q;
matrix b(p,q);
b.read();
cout<<"\nmatrix A is : ";
a.show();
cout<<"\nmatrix B is : ";
b.show();
matrix c(m,n);
c.add(a,b);
cout<<"\nC=A+B : ";
c.show();
matrix d(m,n);
d.sub(a,b);
cout<<"\nD=A-B : ";
d.show();
matrix e(m,q);
e.mul(a,b);
cout<<"\nE=A*B : ";
e.show();
if(a.eq1(b))
cout<<"\nA = B ?-yes";
else
cout<<"\nA = B ?-no";
getch();
}
Example 30 :
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class twodim;
class onedim
{
int array[100];
int row, col;
public:
void getdata();
void dispcolwise();
void disprowwise();
friend void matmul(onedim, onedim,twodim);
};
void onedim::getdata()
{
cout<<"\nEnter no. of rows : ";
cin>>row;
cout<<"\nEnter no. of columns : ";
cin>>col;
cout<<"\nEnter elements : ";
for(int i=0;i<row*col;i++)
cin>>array[i];
}
void onedim::disprowwise()
{
int i,j,in=0;
cout<<"\nMatrix B : ";
for(i=0;i<row;i++)
{
cout<<"\n";
for(j=0;j<col;j++)
cout<<array[in++]<<" ";
}
}
void onedim ::dispcolwise()
{
int i,j,in=0;
cout<<"\nMatrix A : ";
for(i=0;i<row;i++)
{
in=i;
cout<<"\n";
for(j=0;j<col;j++)
{
cout<<array[in]<<" ";
in=in+2;
}
}
}
class twodim
{
int prod[10][10];
int row,col;
public:
friend void matmul(onedim, onedim,twodim);
};
void matmul(onedim a, onedim b, twodim c)
{
int i,j,k,l,m;
if(a.col != b.row)
exit(0);
else
{
c.row = a.row;
c.col = b.col;
}
m=0;
for(i=0;i<c.row;i++)
{
k=0;
for(j=0;j<c.col;j++)
{
c.prod[i][j] =0;
int i1=k,i2=m;
for(l=0;l<a.row;l++)
c.prod[i][j]=c. prod[i][j]+a.array[i1++]*b.array[i2++];
k=k+2;
}
m=m+2;
}
cout<<"\n Product A*B: \n";
for(i=0;i<c.row;i++)
{
cout<<"\n";
for(j=0;j<c.col;j++)
cout<<c.prod[i][j]<<" ";
}
}
void main()
{
onedim a,b;
twodim c;
clrscr();
cout<<"\nEnter elements column wise : ";
a.getdata();
a.dispcolwise();
cout<<"\nEnter elements row wise : ";
b.getdata();
b.disprowwise();
matmul(a,b,c);
getch();
}
Example 31 : Program to illustrates Nesting of Member Functions
#include<iostream.h>
#include<conio.h>
class set
{
int m, n;
public:
void input(void);
void display(void);
int largest(void);
};
int set :: largest (void)
{
if (m>=n)
return(m);
else
return(n);
}
void set :: input (void)
{
cout<<"Input values of m and n : ";
cin>>m>>n;
}
void set :: display (void)
{
cout<<" Largest value = "
<<largest( ) <<"\n";
}
void main( )
{
set A;
A.input( );
A.display( );
getch( );
}
// calling member function
Example 32 : Objects as Function Arguments -by reference
#include <iostream.h>
#include<conio.h>
class Rational
{
int numerator;
int denominator;
public :
void set(int, int); // prototypes declared
void print();
void exchange (Rational*);
};
void Rational::set(int a, int b)
{
numerator = a;
denominator = b;
}
void Rational::print()
{
cout << numerator << " / " << denominator;
cout << "\n";
}
void Rational::exchange(Rational *n1)
{
int temp = 0;
temp=numerator;
numerator=(*n1).numerator;
(*n1).numerator=temp;
temp=denominator;
denominator=(*n1).denominator;
(*n1).denominator=temp;
}
void main(void)
{
Rational a, b;
clrscr();
a.set(2,5);
b.set(3,7);
a.exchange(&b);
cout << "a = "; a.print();
cout << "b = "; b.print();
getch();
}
// Objects passed as arguments
Example 33 : Objects as Function Arguments -by value
#include <iostream.h>
#include<conio.h>
class Rational
{
int numerator;
int denominator;
public :
void set(int, int); // prototypes declared
void print();
void sum (Rational, Rational);
};
void Rational::set(int a, int b)
{
numerator = a;
denominator = b;
}
void Rational::print()
{
cout << numerator << " / " << denominator;
cout << "\n";
}
void Rational::sum(Rational n1, Rational n2) // n1,n2 are objects
{
int temp = 0;
temp += n1.numerator * n2.denominator;
temp += n1.denominator * n2.numerator;
numerator = temp;
denominator = n1.denominator* n2.denominator;
}
void main(void)
{
Rational a, b, c;
clrscr();
a.set(2,5);
b.set(3,7);
c.set(0,0);
c.sum(a,b);
// Objects passed as arguments-by value
cout << "a = "; a.print();
cout << "b = "; b.print();
cout << "c = "; c.print();
getch();
}
Example 34 :
#include<iostream.h>
#include<conio.h>
class book
{
int bid;
int balance;
int received;
int sold;
public:
void getdata()
{
cout<<"\nEnter Book Id: ";
cin>>bid;
cout<<"\nEnter inventory balance at the begining of the month : ";
cin>>balance;
cout<<"\nNumber of copies received during the month : ";
cin>>received;
cout<<"\nNumber of copies sold during the month : ";
cin>>sold;
}
void display()
{
cout<<"\nBook Id: "<<bid;
cout<<"\nUpdated Balance : "<<balance;
}
void update()
{
balance=balance+received-sold;
}
};
void main()
{
book b[5];
clrscr();
for(int i=0;i<5;i++)
{
b[i].getdata();
b[i].update();
b[i].display();
}
getch();
}
Example 35 :
#include<iostream.h>
#include<conio.h>
class distance
{
int feet;
float inches;
public:
distance()
{ feet=0; inches=0.0;}
distance(int ft,float in)
{feet=ft;inches=in;}
void getdist()
{
cout<<"\nEnter feet:";
cin>>feet;
cout<<"\nEnter inches : ";
cin>>inches;
}
void showdist()
{
cout<<"Feet : "<<feet<<"Inches : "<<inches;
}
void operator +=(distance d2);
};
void distance::operator +=(distance d2)
{
feet+=d2.feet;
inches+=d2.inches;
while(inches>=12)
{
inches=inches-12;
feet++;
}
}
void main()
{
distance d1,d2;
clrscr();
d1.getdist();
d2.getdist();
d1+=d2;
cout<<"\nResult : ";
d1.showdist();
getch();
}
Example 36 :
#include<iostream.h>
#include<conio.h>
class Float
{
float num;
public:
Float(){ }
Float(float n)
{
num=n;
}
void display()
{
cout<<num<<endl;
}
float operator +(Float c)
{
return(num+c.num);
}
float operator *(Float c)
{
return(num*c.num);
}
float operator -(Float c)
{
return(num-c.num);
}
float operator /(Float c)
{
return(num/c.num);
}
};
void main()
{
Float f1(3.14);
Float f2(2.30);
Float f3;
clrscr();
f3=f1+f2;
f3.display();
f3=f1-f2;
f3.display();
f3=f1*f2;
f3.display();
f3=f1/f2;
f3.display();
getch();
}
Example 37 :
#include<iostream.h>
#include<conio.h>
class pow
{
int no;
public:
pow()
{}
void getno();
void dispno();
pow operator^(pow);
};
void pow::getno()
{
cout<<"\nEnter number : ";
cin>>no;
}
void pow:: dispno()
{
cout<<no;
}
pow pow::operator^(pow p1)
{
pow r;
int i,sum=1;
for(i=1;i<=p1.no;i++)
sum*=no;
r.no=sum;
return(r);
}
void main()
{
pow p1,p2,p3;
clrscr();
p1.getno();
p2.getno();
p3=p1^p2;
cout<<"\nResult : ";
p3.dispno();
getch();
}
Example 38 :
# include<iostream.h>
# include<conio.h>
class NUM
{
int a;
public:
void getdata()
{
cout<<"Enter value : " ;
cin>>a;
}
NUM operator +(NUM n)
{
NUM temp;
temp.a=a+n.a;
return (temp);
}
NUM operator -(NUM n)
{
NUM temp;
temp.a=a-n.a;
return (temp);
}
NUM operator *(NUM n)
{
NUM temp;
temp.a=a*n.a;
return (temp);
}
NUM operator /(NUM n)
{
NUM temp;
temp.a=a/n.a;
return (temp);
}
void operator ++()
{
a++;
}
void operator -()
{
a=-a;
}
void disp()
{
cout<<a;
}
};
void main()
{
NUM n1,n2,n3;
clrscr();
n1.getdata();
n2.getdata();
n3=n1+n2;
cout<<"\nn1+n2 : ";
n3.disp();
n3=n1-n2;
cout<<"\nn1-n2 : ";
n3.disp();
n3=n1*n2;
cout<<"\nn1*n2 : ";
n3.disp();
n3=n1/n2;
cout<<"\nn1/n2 : ";
n3.disp();
++n1;
cout<<"\n++n1 : ";
n1.disp();
-n2;
cout<<"\n-n2 : ";
n2.disp();
getch();
}
Example 39 :
#include <iostream.h>
#include<string.h>
#include<conio.h>
class string
{
private :
char* str;
public :
string(char* s)
{
int length = strlen(s);
str = new char[length +1 ];
strcpy(str,s);
}
~string()
{
delete str;
}
void display()
{
cout << str;
}
};
void main()
{
string s1 = "who knows nothing doubts nothing.";
clrscr();
cout <<endl<<"s1 = " ;
s1.display();
getch();
}
Example 40 : A Parameterised Constructor
#include <iostream.h>
#include <string.h>
#include<conio.h>
class sample
{
char itemname[20];
int cost;
public :
sample(char*, int);
// Constructor declaration
void print_data();
};
sample::sample(char* s, int c)// Constructor definition
{
strcpy(itemname,s);
cost = c;
}
void sample::print_data()
{
cout << "Item : " << itemname << "\n";
cout << "Cost : " << cost << "\n";
}
void main(void)
{
sample A1("Pencil", 5);
sample A2 = sample("Notebook", 20);
clrscr();
A1.print_data();
A2.print_data();
getch();
}
Example 41 :
#include<iostream.h>
#include<math.h>
#include<conio.h>
class polar
{
private:
double radius;
double angle;
double getx()
{
return radius*cos(angle);
}
double gety()
{
return radius*sin(angle);
}
public:
polar()
{
radius=0.0;
angle=0.0;
// implicit call to the constructor
// explicit call to the constructor
}
polar(float r,float a)
{
radius=r;
angle=a;
}
void display()
{
cout<<"("<<radius<<","<<angle<<")";
}
polar operator +(polar p2)
{
double x=getx()+p2.getx();
double y=gety()+p2.gety();
double r=sqrt(x*x+y*y);
double a=atan(y/x);
return polar(r,a);
}
};
void main()
{
polar p1(2.66,1.59),p3;
polar p2(3.16, 2.4);
clrscr();
p3=p1+p2;
p3.display();
getch();
}
Example 42 : Overloading Relational Operators
#include <iostream.h>
#include <string.h>
#include<conio.h>
/*----------------------Class definition-------------------------*/
class string
{
char *s;
int length;
public:
string();
string(char*);
// Overloaded Relational operator '=='
int operator == (string);
// Overloded '+' operator
friend string operator + (string, string);
void show();
};
string::string()
{
length = 0;
s = new char[length + 1];
s[0] = '\0';
// empty string
}
string::string(char *str)
{
length = strlen(str);
s = new char[length + 1];
strcpy(s,str);
}
// Overloaded '==' relational operator as a member function
int string::operator == (string x)
{
int flag = 0;
if (length == x.length)
{
flag = 1;
for (int i=0; i<length; i++)
{
if (s[i] != x.s[i])
{
flag = 0;
break;
}
}
}
return flag;
}
void string::show()
{
cout << s << "\t(Length = " << length << ")\n";
}
/*----------------------Definition ends here---------------------*/
// Overloded '+' (concatenation) operator as a friend function
string operator + (string x, string y)
{
string temp;
temp.length = x.length + y.length;
temp.s = new char[temp.length + 1];
strcpy(temp.s, x.s);
strcat(temp.s, y.s);
return temp;
}
void main(void)
{
string s1("Good "),s2("Morning"),s3, s4("Morning");
clrscr();
s3 = s1 + s2; // concatenation
cout << "The result of concatenation :\n";
s3.show();
cout << "\nThe result of comparison of s1 & s2 :\n";
cout << (s1 == s2);
cout << "\nThe result of comparison of s2 & s4 :\n";
cout << (s2 == s4);
getch();
}
Example 43 : Operator Function returning an object
#include <iostream.h>
#include<conio.h>
/*----------------------Class definition-------------------------*/
class sample
{
int a;
int b;
public :
sample() { }
// default empty constructor
sample(int, int);
// Overloaded unary minus as a friend
friend sample operator - (sample);
void print();
};
sample::sample(int x, int y)
{
a = x;
b = y;
}
void sample::print()
{
cout << "a = " << a << "\n";
cout << "b = " << b << "\n";
}
/*----------------------Definition ends here---------------------*/
sample operator - (sample x) // friend function definition
{
sample temp;
temp.a = -x.a;
temp.b = -x.b;
return temp;
}
void main(void)
{
sample A(5,10), B;
clrscr();
cout << "Result after first application of unary minus : \n";
B = -A;
// invoking operator function
B.print();
cout << "Result after second application of unary minus : \n";
B = operator - (B); // invoking operator function directly
B.print();
getch();
}
Example 44 : Function Returning Object
#include <iostream.h>
#include<conio.h>
class Rational
{
int numerator;
int denominator;
public :
void set(int, int);
int get_numerator () { return numerator; }
int get_denominator () { return denominator; }
void print();
Rational sum (Rational);
};
void Rational::set(int a, int b)
{
numerator = a;
denominator = b;
}
void Rational::print()
{
cout << numerator << " / " << denominator;
cout << "\n";
}
Rational Rational::sum(Rational n)
{
Rational Tobject;
int temp = 0;
temp += numerator * n.get_denominator();
temp += denominator * n.get_numerator();
Tobject.numerator = temp;
Tobject.denominator = denominator * n.get_denominator();
return Tobject;
}
void main(void)
{
Rational a,b,c;
clrscr();
a.set(2,5);
b.set(3,7);
c.set(0,0);
c = a.sum(b);
cout << "a = "; a.print();
cout << "b = "; b.print();
cout << "c = "; c.print();
getch();
}
Example 45 :
#include <iostream.h>
#include <conio.h>
class Runner
{
char name[20];
int time;
public:
void getdata()
{
cout<<"\nEnter name :";
cin>>name;
cout<<"\nEnter time in minutes : ";
cin>>time;
}
friend void result(Runner ,Runner, Runner);
};
void result(Runner r1,Runner r2 , Runner r3)
{
if(r1.time<r2.time)
if(r1.time<r3.time)
{
cout<<"\n First : "<<r1.name;
if(r2.time<r3.time)
{
cout<<"\n Second : "<<r2.name;
cout<<"\n Third : "<<r3.name;
}
else
{
cout<<"\n Second : "<<r3.name;
cout<<"\n Third : "<<r2.name;
}
}
else
{
cout<<"\n First : "<<r3.name;
cout<<"\n Second : "<<r1.name;
cout<<"\n Third : "<<r2.name;
}
else
if(r2.time<r3.time)
{
cout<<"\n First : "<<r2.name;
if(r1.time<r3.time)
{
cout<<"\n Second : "<<r1.name;
cout<<"\n Third : "<<r3.name;
}
else
{
cout<<"\n Second : "<<r3.name;
cout<<"\n Third : "<<r1.name;
}
}
else
{
cout<<"\n First : "<<r3.name;
cout<<"\n Second : "<<r2.name;
cout<<"\n Third : "<<r1.name;
}
}
void main()
{
Runner r1,r2,r3;
clrscr();
r1.getdata();
r2.getdata();
r3.getdata();
result(r1,r2,r3);
getch();
}
Example 46 : Program to process shopping list
#include<iostream.h>
#include<conio.h>
#include<process.h>
class item
{
int itemcode[50];
float itemprice[50];
int count;
public :
void cnt(void) { count = 0 ; }
void getitem(void);
void displaysum(void);
void remove(void);
void displayitems(void);
};
// initializes count to 0
void item :: getitem(void)
//assign values to data members of item
{
cout<<"Enter item code : ";
cin>>itemcode[count];
cout<<"Enter item cost : ";
cin>>itemprice[count];
count++;
}
void item :: displaysum(void)
//display total value of all items
{
float sum = 0;
for(int i = 0; i<count; i++)
sum=sum + itemprice[i];
cout<<"\n Total value :"<<sum<<"\n";
}
void item :: remove(void)
//deleting a specified item
{
int a;
cout<<" Enter item code : ";
cin>>a;
for(int i = 0; i<count; i++)
if (itemcode[i] == a)
itemprice[i] = 0;
}
void item :: displayitems(void)
//displaying items
{
cout<<"\n Code
Price \n ";
for(int i = 0; i<count; i++)
{
cout<<"\n"<<itemcode[i];
cout<<"
"<<itemprice[i];
}
cout<<"\n";
}
int main( )
{
item I;
I.cnt( );
int ch;
do
{
cout<<"\n Option are. \n";
cout<<"\n1. Add an item ";
cout<<"\n2. Display total value ";
cout<<"\n3. Delete an item";
cout<<"\n4. Display all items ";
cout<<"\n5. Exit";
cout<<"\n\n Enter your choice : ";
cin>>ch;
switch(ch)
{
case 1 : I.getitem( ); break;
case 2 : I.displaysum( ); break;
case 3 : I.remove( ); break;
case 4 : I.displayitems( ); break;
case 5 : exit(0);
default : cout<<"\n Error in input; try again \n";
}
} while(ch !=5);
}
Example 47 :
# include <iostream.h>
#include<conio.h>
class Sample
{
static int count;
int number;
public :
void getdata (int a)
{
number = a;
count ++;
}
void getcount (void)
{
cout << "Count : "<< count <<endl;
}
};
int Sample :: count;
void main ( )
{
Sample a, b, c;// count is initialized to zero display count
clrscr();
a.getcount ( );
b.getcount ( );
c.getcount ( );
a.getdata (10); // getting data into object a
b.getdata (20); // getting data into object b
c.getdata (30); // getting data into object c
cout << "After reading data" << "\n";
a.getcount ( ); // display count
b.getcount ( );
c.getcount ( );
getch();
}
Example 48 :
#include <iostream.h>
#include<conio.h>
class test
{
int code;
static int count;
// static member variable
public :
void setcode (void)
{
code = ++count;
}
void showcode (void)
{
cout << "Object number : " << code << "\n";
}
static void showcount(void)
// static number function
{
cout << "Count : "<<count<<"\n";
}
};
int test :: count;
int main()
{
test t1, t2;
clrscr();
t1.setcode();
t2.setcode();
test :: showcount();
test t3;
t3.setcode ( );
test :: showcount();
// accessing static function
t1.showcode();
t2.showcode();
t3.showcode();
getch();
}
Example 49 : Overloading Unary Operator as a Friend Function
#include <iostream.h>
#include<conio.h>
/*----------------------Class definition-------------------------*/
class sample
{
int a;
int b;
public :
sample() { }
// default empty constructor
sample(int, int);
// Overloaded unary minus as a friend
friend void operator - (sample&);
void print();
};
sample::sample(int x, int y)
{
a = x;
b = y;
}
void sample::print()
{
cout << "a = " << a << "\n";
cout << "b = " << b << "\n";
}
/*----------------------Definition ends here---------------------*/
void operator - (sample& x) // friend function definition
{
x.a = -x.a;
x.b = -x.b;
}
void main(void)
{
sample A(10,20);
clrscr();
cout << "Before the application of operator '-'(unary minus) :\n";
A.print();
-A;
// invoking operator function
cout << "After the application of operator '-'(unary minus) :\n";
A.print();
operator -(A); // another way of invoking - as a member function
cout << "After the second application of operator '-'(unary minus) :\n";
A.print();
getch();
}
Example 50 : Unary Operator Overloading
#include <iostream.h>
#include<conio.h>
/*----------------------Class definition-------------------------*/
class sample
{
int a;
int b;
public :
sample() { }
// default empty constructor
sample(int, int);
void operator - ();
// Overloaded unary minus
void print();
};
sample::sample(int x, int y)
{
a = x;
b = y;
}
void sample::operator - ()
{
a = -a;
b = -b;
}
void sample::print()
{
cout << "a = " << a << "\n";
cout << "b = " << b << "\n";
}
/*----------------------Definition ends here---------------------*/
void main(void)
{
sample A(10,20);
clrscr();
cout << "Before the application of operator '-'(unary minus) :\n";
A.print();
-A;
// operator function gets invoked
cout << "After the application of operator '-'(unary minus) :\n";
A.print();
A.operator -(); // another way of invoking - as a member function
cout << "After the second application of operator '-'(unary minus) :\n";
A.print();
getch();
}
Example 51 :
#include<iostream.h>
#include<conio.h>
class Floatvector
{
float v[100];
int n;
public:
void create();
void display();
void modify();
void multiply();
};
void Floatvector::create()
{
cout<<"\nEnter no. of elements : ";
cin>>n;
for(int i=0;i<n;i++)
cin>>v[i];
}
void Floatvector:: display()
{
cout<<"\nVector : ";
for(int i=0;i<n;i++)
cout<<v[i]<<",";
}
void Floatvector::modify()
{
int pos;
float num;
cout<<"\nEnter position : ";
cin>>pos;
cout<<"\nEnter new number : ";
cin>>num;
v[pos-1]=num;
display();
}
void Floatvector::multiply()
{
int factor;
float num;
cout<<"\nEnter scaling factor : ";
cin>>factor;
for(int i=0;i<n;i++)
v[i]=v[i]*factor;
display();
}
void main()
{
Floatvector fv;
clrscr();
fv.create();
fv.modify();
fv.multiply();
getch();
}