Annamalai University
Annamalai University
ANNAMALAI UNIVERSITY
DIRECTORATE OF DISTANCE EDUCATION
PROGRAMMING LAB – I
OBJECT ORIENTED PROGRAMMING C++
Annamalai University
Copyright Reserved
(For Private Circulation Only)
Object Oriented Programming – C++
How to start?
Borland C++’s IDE (Integrated Development Environment) will open. It may look
something like this if no other file is previously opened.
At the top is a menu-bar providing you different menus to help carry out all the tasks in
the program development process.
At the bottom is the status bar the contents of which change accordingly as we move at
different components of IDE. It is a sort of online help.
Pressing Alt-key and any of the hotkeys (letters in red color e.g. F in File, E in Edit) will
activate that menu.
From File menu select New. A new window will open. Write your source code in this
window.
Annamalai University
Page 1
Object Oriented Programming – C++
Edit Window:
This window is where you write your source code. Whenever you open any
source file it is opened in the Edit Window. As you can have more than one file
opened, there can be more than one Edit Windows opened but only the active
window can be edited.
Message Window:
This window reports the status of compilation and linkage mechanism. Also it
reports all the errors in the code and warnings along with the line numbers and
source.
Clipboard Window:
This window contains the block of text on which Cut and Copy operations are
performed.
Output Window:
This window displays the output of your program and it is not visible within IDE.
It cannot be switched using F6 Key; instead you have to use Alt-F5 key
combination. Pressing any key will return to the IDE. This window will be blank
if the last compilation has graphics output.
Project Window:
Annamalai University
In this window all the files included in the current project are listed. Its title
indicates the current project.
Start the BC, create a new file. You will be presented with an empty window. You
have to type-in your program’s source code into it.
To start with there must be only one main() function in the program as the
execution starts from main() function and any number of other user-defined functions(not
compulsory).
Page 2
Object Oriented Programming – C++
In this main() function you may use any of the standard C/C++ library function.
So you need to specify which of those functions you are going to use in your program.
For that, you have to include appropriate header file in your source code.
e.g. hello.c : C Program to display “Hello, World” String
#include <stdio.h>
#include <conio.h>
void main()
{
printf(“\nHello, World”);
getch();
}
In the above program, two header files are included namely: stdio.h and conio.h.
stdio.h file contains all standard input output related functions and conio.h file contains
all the console(interfacing devices - screen and keyboard) related functions.
In our program we have used two standard C library functions: printf() declared in
stdio.h and getch() declared in conio.h.
Remember this file contains C source code. So, you should save this file with .c
extension; otherwise, you may get an error. Although, Borland compilers will not report
any error. The program will run smoothly. But, if the same program is written in C++ and
extension is not .cpp, then the compiler will definitely report an error.
Imp: When any of the library function is used, you have to include appropriate
header file. Otherwise, you will get an error from the compiler: “…function not found”.
After typing in the source code, you need to compile and link the program. The
compiler will check for any syntactical (grammatical) errors in the code. If not found, it
creates an intermediate file called object file with the same name as filename and
extension .obj. The object file(s) obtained are then linked with other object file(s)
provided with the library by the linker and executable file with .exe extension is created.
This executable file can now be run directly on DOS prompt. Following diagram
summarizes the above discussion:
To compile the program choose Compile->Compile or simply press Alt-F9.
For linking the program with the Standard C Library, choose Compile->Link.
Annamalai University
Now, you can execute your program and see the output. To do so, choose Run->Run or
press Ctrl-F9. It will perform all the three tasks: compiling, linking and running in one
shot.
When you try to compile the program, compiler may report an error: “Unable to
open include file ‘….h’” or “Cannot find ‘….lib’ file”. The only thing is you have specify
where the include (header) files and library (.obj and .lib) files can be located. To set this
directory paths:
Select Options->Directories… option. It has four directories to be specified:
Page 3
Object Oriented Programming – C++
Include Directories:
Specify the path where the header files are stored. Multiple paths, if any, are
separated by semi-colon(;)
Library Directories:
Specify the path where library and startup files can be found. Again, if these files
are dispersed into various directory paths or different subdirectories, specify all
the directories separated by semi-colon.
Output Directory:
All the intermediate files and output files(executables) will go into this path.
Source Directories:
Specify where from the source files have to be fetched or where to be stored by
default.
If you do not know where these files are stored on the network, give the ‘map’
command at the prompt. This will list out all the drives on the network specifying
the different packs such as DOSPACK, WINPACK, etc. From this you can make
out, where the include files and library files are located.
If, still you are unable to locate the required files, consult the Lab Assistant.
Sometimes you may not be able to run graphics on a system. That may be
because, you may not have configured the IDE to include or support graphics library.
You can enable the Graphics Library from
Options->Linker->Libraries…
Using arrow keys move to “[ ] Graphics Library” option and press SPACE-BAR
to select it. The cross will appear in the brackets.
You have to include graphics.h header file in your source file.
You might have used initgraph() function. Actually this is not the problem with
Annamalai University
initgraph or the graphics library. Firstly, you may not have specified the correct path to
.BGI files. Secondly, while giving the path in double-quotes you have to put double-slash
twice as shown below. Otherwise, the compiler will treat it as an escape sequence.
e.g.
int gd=DETECT,gm;
initgraph(&gd,&gm,”q:\\winpack\\bc31\\bgi”);
Page 4
Object Oriented Programming – C++
Projects:
Creating a Project:
File Menu:
New: Create a new file in a new Edit Window
Open: Locate and open an existing file
Save: Save the file in a active Edit Window
Save as: Save a file in active window under new name
Page 5
Object Oriented Programming – C++
Run Menu:
Compile Menu:
Debug Menu:
Project Menu:
Options Menu:
Window Menu:
Help Menu:
This information will tell you how to enter and run a program. It will not give you any in-
Annamalai University
depth knowledge about Turbo C++, or about how to write programs. It is intended for the
first time user, who needs to know what keys to press to make things work.
Step 1. Logging In
You will have to log in to the machines. Your User Id and Password should be assigned
to you before you go to use the machines.
When you arrive at a machine you should see a window containing 3 data areas: Server,
User Id or Student Id, and Password or Pin.
Page 6
Object Oriented Programming – C++
Select Server by using the Tab key. Use the up and down arrow keys to choose
mail.caps.maine.edu as the server.
Use the tab key to get to User Id or Student Id. Enter your User Id. Again use the tab
key to get to Password or Pin. Enter your password, then press Enter. The machine will
transfer directly to Windows95.
Click on Start, click on Programs, then click on Programming Languages Then double
click on the Turbo C++ for Dos icon.
Step 2.
Now you should be in Turbo C++. If the Turbo C++ window is too big or too small click
on the down arrow on the upper left of the screen (to the right of the word "Auto"). Using
7 X 14 is a good choice, but it is up to you. Also, you can type Alt-Enter for a full screen
Turbo C++ window.
You should have a disk in drive a: (or b:). High-density disks are best in the lab. Put your
disk in the drive.
Step 3
At this point it is a good idea to get things ready for saving your work to the disk in drive
a:. Use the mouse to activate the File menu option at the top of the screen. A "pull down"
menu appears. Any of the options listed in the submenu are available. Use the mouse to
select File/Change dir.. . Now type a: (this will automatically overwrite the C:\TEMP
entry shown) to change to the drive that contains your floppy disk and hit the ENTER key
(or click on OK). Now when you save your file (using the F2 key or the File/Save menu
item) the file will be saved to your disk. If you do not do this, you will save the file to a
system disk and it will be deleted when you leave. All your work will then be lost.
Step 4
Now choose File/New. Another window appears. Enter a file name. You may type any
name, but for the sake of the following example we choose the name power.cpp to
Annamalai University
designate this C++ program. The *.cpp display will disappear when you start to type.
After typing power.cpp, press ENTER.
Since power.cpp is a new file, the screen should look like the following screen. The
window labeled POWER.CPP is your edit window. This is where you will enter your
program and make any corrections to it.
Page 7
Object Oriented Programming – C++
po
rtion of the window. The number on the left side of the colon tells you which row the
cursor is in, while the number on the right side of the colon tells you which column your
cursor is in.
Further down in this help information you will find a list of the keys that will be of use to
you while using this editor -- keys to move the cursor, insert and delete text, and move
around from window to window. You will need to refer to them as you begin and
memorize them by constant use.
Step 5
Now you should type in your program. For example, you can type the following brief
program that will read in a base and exponent and compute the result. Type the program
as it appears below, starting at the left margin of the screen. If you make a mistake, hit
the Backspace key.
/* This program reads a base and exponent from standard input and prints
main(void)
{
int exponent, i;
float base, result;
cout << "\nPlease enter base & exponent (integers): ";
cin >> base >> exponent;
if ( base == 0 )
result = 0;
Page 8
Object Oriented Programming – C++
else {
result = 1;
for ( i = 1 ; i <= exponent ; i++ )
result = result * base;
}
cout << "The result is: " << result << "\n";
return 0;
}
The above is a complete, although brief, Turbo C++ program. In Step 6, you will learn
how to compile and run it.
The screen should now appear as shown below. (Notes: 1. The return 0; statement is
missing from the listing below, but you should put it in your program. 2. Some white
space was eliminated to fit the entire program onto one screen.) If the program does not
fill the entire Turbo screen, you can click on the double arrow on the line to the right of
\POWER.CPP. This should increase the size of your edit window in the Turbo
environment.
Annamalai University
Program Explanation:
The sentences within /*...*/ are comments. Also, comments start at a // and continue to
the end of that line. They tell the person reading the program what the program does. The
first line after the comment is used to include the stream I/O header file in this program.
The first line of the function starts with the word main. This identifies it as the function
to be run when the program is started. The { and } signify the begin and end of a function
or block. The next two lines start with int and identify the variables used in the program.
We will use the three variables named base, exponent, result, and i. Each of these
Page 9
Object Oriented Programming – C++
variables is of type int (integer) or float (floating point) as indicated. The next line starts
with cout, which displays the user prompt (instructions as to what the user should type)
to standard output. Then, the cin command reads the entered values into variables base
and exponent. from standard input. Once the result is calculated we use cout to display a
label and the result.
Step 6.
Now you can compile and run your program by pressing Ctrl-F9 (hold the Ctrl key down,
then tap the F9 key). You may also choose Run/Run with the mouse.
(You may get error messages from the compiler, telling you things that at first don't seem
to make sense. This means that you must RE-EDIT the program code to remove the
errors. If you have errors, press any key and the errors will be listed. Read them. If you
double click on any of the messages, you will return to the edit screen with the cursor
near where the error is. Try to figure it out, in this case just compare your program to the
one above, and fix the error. You can test if the program works now by running the
program again (use Ctrl-F9).)
If the program compiles correctly, the following message will be displayed on the output
screen.
The output (e.g., The result is: 27) will appear briefly.
Step 7.
Press ALT-F5 to display the output window. This allows you to check your output. To
get back to the IDE, press any key.
Step 8.
Annamalai University
Be sure to save your program by pressing F2 or choosing File/Save. Also be sure that the
directory has been changed to a: or b:. If it is E:, you will lose all your work when you
leave the session.
After your program has compiled and run successfully, be sure to Save it. After you save
the file, it remains in memory as well. You can continue making changes to it as you
wish, but if you do, remember that you must save it again to avoid losing your changes.
Please note that F2 saves the work in the current window, so be sure that your cursor is in
the correct window.
Page 10
Object Oriented Programming – C++
Step 9.
To print your output, first make sure that your are in a window, not the full screen. If you
are in a full screen, press Alt-Enter. Now press ALT-F5 to bring up the output screen.
Click on the MS-DOS icon in the upper left had corner of your MS-DOS screen. Click
Edit/Mark. Click and drag the mouse to highlight the area of the output screen you want
to print. Click MS-DOS icon/Edit/Copy to copy the highlighted area into the clipboard.
Reduce your MS-DOS screen by clicking the _ button in the upper right-hand corner of
the screen. (Do not click the X button, it will try to shut down your MS_DOS session.) In
the Programming Languages window, click on Notepad. Click Edit/Paste then File/Print
then File/Exit. Finally click on the MS-DOS icon on the Start bar to get back to Turbo
C++. When you are done, press any key to return from the output screen to your Turbo
C++ screen.
You can get your print jobs from the assistants at the main desk in the front of the
microcomputer center. Tell them your pod number (e.g. PD4) and they will get your
printed material.
When ready to quit work, press Alt-X (or choose File/Quit) to quit the Turbo C++
Environment (and save your work if you forgot). Then press Ctrl-c to get back to
Windows 95. Then double click on the Logout icon. Be sure to complete these steps. If
you do not, someone else can come in and use your Id.
Note: Occasionally a program will get into an infinite loop in which it will run forever
unless stopped. To halt a program in an infinite loop, type Ctrl-Break.
Annamalai University
Editing: Use the mouse and the Edit menu as you would with a word processor. You can
cut, paste, copy, etc.
Page 11
Object Oriented Programming – C++
Esc Escape the present menu (often useful if you are lost in the menu system,
F10 Get back to the Turbo menu (e.g. back to the File menu).
Alt-Enter Toggles between a full screen and a window for the Turbo C++ screen.
Annamalai University
Page 12
Object Oriented Programming – C++
LIBRARY FUNCTION
Annamalai University
Returned
<math.h>
Page 13
Object Oriented Programming – C++
Page 14
Object Oriented Programming – C++
fread(s, i1, i2, f) int Enter i2 data items, each of size i1 bytes,
from file f to string s.
scanf(…) int Enter data items from the standard input dev
<stdlib.h>
absi(s) int Return the absolute value of I
Page 15
Object Oriented Programming – C++
exit(u) void Close all files and buffers, and terminate the
program.( Value of u is assigned by the
function, to indicate termination status.)
<string.h>
Annamalai University
strcmp(s1,s2) int Compare two strings lexicographically.
Return a negative value if s1<s2; 0 if s1
And s2 are identical; and a positive value
If s1>s2.
Page 16
Object Oriented Programming – C++
<time.h>
difftime(11, 12) double Return the time difference 11-12, where
11 and 12 represent elapsed times beyond
a designated base time (see the time fun.)
Exercise Programs
1. Program for Generating Fibonocci Series using Classes
2. Student Mark Processing Program in C++
3. Program to demonstrate Time functions
4. Program to demonstrate Inheritance
5. Program to demonstrate Arrays of Objects
6. Sorting of Objects using Classes
7. Program to demonstrate Friend Function
8. Program to demonstrate Nested Class
9. Program to demonstrate Function Overload
10. Program to demonstrate File Processing
11. Program to demonstrate Operator Overloading
12. File Handling in C++
13. Multiple inheritance
14. Constructors and destructors
15. Pointers to classes
Annamalai University
Page 17
Object Oriented Programming – C++
# include<iostream.h>
# include<conio.h>
class fib
{private:
long int a,b,c;
public:
fib(int x,int y)
{a=x;
b=y;
c=a+b;
}
fib(fib &ptr)
{a=ptr.a;
b=ptr.b;
c=ptr.c;
}
void inc()
{a=b;
b=c;
c=a+b;
}
void display()
{cout<<c<<"\t";
}
};
void main()
{clrscr();
int n;
fib obj1(0,1);
fib obj2(obj1);
cout<<"Enter the term upto which you want to generate the
series : ";
cin>>n;
for(int i=0;i<n;i++)
Annamalai University
{obj2.display();
obj2.inc();
}
}
Page 18
Object Oriented Programming – C++
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
struct student
{ int roll,rank,m[3];
char name[20];
float tot,avg;
}s[4],temp;
void tot_avg(student s[4])
{int i=0;
for(i=0;i<4;i++)
{s[i].tot=0;
s[i].tot=s[i].m[0]+s[i].m[1]+s[i].m[2];
s[i].avg=s[i].tot/3;
} }
void rank(student s[4])
{int i=0,j=0;
for(i=0;i<3;i++)
{for(j=i+1;j<4;j++)
{if(s[i].tot < s[j].tot)
{temp=s[j];
s[j]=s[i];
s[i]=temp;
} } }
int r=1;
for(i=0;i<4;i++)
{s[i].rank=r;
r++;
} }
void outroll(student s[4])
{int i=0,j=0;
for(i=0;i<3;i++)
{for(j=i+1;j<4;j++)
{if(s[i].roll>s[j].roll)
Annamalai University
{temp=s[j];
s[j]=s[i];
s[i]=temp;
} } }
for(i=0;i<4;i++)
{cout<<setw(21)<<setiosflags(ios::left)<<s[i].name;
cout<<setw(4)<<setiosflags(ios::right)<<s[i].roll;
cout<<setw(6)<<setiosflags(ios::right)<<s[i].m[0];
cout<<setw(6)<<setiosflags(ios::right)<<s[i].m[1];
cout<<setw(6)<<setiosflags(ios::right)<<s[i].m[2];
cout<<setw(6)<<setiosflags(ios::right)<<s[i].tot;
Page 19
Object Oriented Programming – C++
cout<<setw(8)<<setprecision(2)<<setiosflags(ios::right)<<s[
i].avg;
cout<<setw(5)<<setiosflags(ios::right)<<s[i].rank;
cout<<endl;
} }
void outrank(student s[4])
{int i=0;
for(i=0;i<4;i++)
{if(s[0].tot<s[i].tot)
{temp=s[i];
s[i]=s[0];
s[0]=temp;
} }
for(i=0;i<4;i++)
{cout<<setw(21)<<setiosflags(ios::left)<<s[i].name;
cout<<setw(4)<<setiosflags(ios::right)<<s[i].roll;
cout<<setw(6)<<setiosflags(ios::right)<<s[i].m[0];
cout<<setw(6)<<setiosflags(ios::right)<<s[i].m[1];
cout<<setw(6)<<setiosflags(ios::right)<<s[i].m[2];
cout<<setw(6)<<setiosflags(ios::right)<<s[i].tot;
cout<<setw(8)<<setprecision(2)<<setiosflags(ios::right)<<s[
i].avg;
cout<<setw(5)<<setiosflags(ios::right)<<s[i].rank;
cout<<endl;
} }
void main()
{clrscr();
int i=0,c=0;
for(i=0;i<4;i++)
{cout<<"Name : ";
cin>>s[i].name;
cout<<"Roll : ";
cin>>s[i].roll;
cout<<"Sub 1: ";
Annamalai University
cin>>s[i].m[0];
cout<<"Sub 2: ";
cin>>s[i].m[1];
cout<<"Sub 3: ";
cin>>s[i].m[2];
cout<<endl;
}
tot_avg(s);
rank(s);
clrscr();
cout<<"How do you want to sort?"<<endl;
Page 20
Object Oriented Programming – C++
# include <iostream.h>
# include <conio.h>
# include <stdlib.h>
class time
{
private:
int hours;
int minutes;
int seconds;
protected:
void normalize();
public:
time()
Annamalai University
{
hours = 0;
minutes = 0;
seconds = 0;
}
void advance(int,int,int);
void resent (int,int,int);
void print (void);
};
void time :: advance (int h,int m,int s)
{
Page 21
Object Oriented Programming – C++
hours += h;
minutes += m;
seconds += s;
normalize();
}
void time :: resent (int h,int m,int s)
{
hours = h;
minutes = m;
seconds = s;
}
void time :: print()
{
cout <<"\n\t THE CURRENT TIME IS:";
cout << "\n\t "<< hours << " HOURS,";
cout << minutes << " MINUTES,";
cout << seconds << " SECONDS";
}
void time :: normalize()
{
if ( seconds >= 60 )
{
minutes += seconds / 60 ;
seconds = seconds % 60 ;
}
if ( minutes >= 60 )
{
hours += minutes / 60 ;
minutes = minutes % 60;
}
if ( hours >= 24 )
{
hours = hours % 24;
}
}
Annamalai University
void main()
{
class time day;
int choice,h,m,s;
clrscr();
cout <<"\n\t WELCOME TO THE WORLD OF TIME ";
do
{
cout <<"\n\t 1. DISPLAY TIME ";
cout <<"\n\t 2. ADVANCE TIME ";
cout <<"\n\t 3. RESET TIME ";
Page 22
Object Oriented Programming – C++
}
Annamalai University
getch();
# include<iostream.h>
# include<conio.h>
# include<stdlib.h>
Page 23
Object Oriented Programming – C++
class base1
{
protected:
char name[10];
int acc_no;
public:
void get_data();
void put_data();
};
void base1::get_data()
{
cout<<"\n\t enter the name:";
cin>>name;
cout<<"\n\t enter the acc_no: ";
cin>>acc_no;
}
void base1::put_data()
{
cout<<"\n\t Mr/Ms "<<name<<" of accession number
"<<acc_no;
}
class base2
{
protected:
char title[15],pub[10];
int year;
public:
void get_data();
void put_data();
};
Annamalai University
5. Program to demonstrate Arrays of Objects
# include<iostream.h>
# include<conio.h> //for clrscr()
class student
{
int rollno;
char name[21];
float marks1,marks2,marks3,marks4,marks5;
Page 24
Object Oriented Programming – C++
float perc;
char stream;
public:
void getinfo(void)
{
char ch;
cout<<" ENTER DATA: ";
cout<<"\n -----------------";
cout<<"\n"<< " ROLL NO : ";
cout<<"\n _________________";
cin >> rollno;
cin.get(ch);
cout<<"\n"<<" NAME: ";
cout<<"\n _________________";
cin>>name;
do
{
cout<<"\n MARKS FOR ENGLISH" ;
cin>> marks1;
if (marks1 <0 || marks1>100)
cout<<" INVALID MARKS";
} while(marks1<0 || marks1>100 );
do
{
cout<<"\n MARKS FOR MATHS" ;
cin>> marks2;
if(marks2<0 || marks2>100)
cout<<" INVALID MARKS";
} while(marks2 <0 || marks2>100);
do
{
Annamalai University
cout<<"\n
cin>> marks3;
MARKS FOR PHYSICS";
do
{
cout<<"\n MARKS FOR CHEMISTRY" ;
cin>> marks4;
if(marks4<0 || marks4>100)
Page 25
Object Oriented Programming – C++
do
{
cout<<"\n MARKS FOR COMPUTER SCIENCE" ;
cin>> marks5;
if(marks5<0 || marks5>100)
cout<<" INVALID MARKS ";
}while(marks5<0 || marks5>100);
cout<<"\n ";
void calculate(void);
void prnresult(void);
};
{
if (perc >91 && perc< 95)
cout<<" STREAM IS ELECTRONICS ";
}
if(perc< 71)
cout<<" SORRY! NO STREAM IS AVAILABLE FOR
PERCENTAGE < 71";
Page 26
Object Oriented Programming – C++
{
if(perc >100)
cout<<"SORRY!!!! WRONG DETAILS";
void main()
{
int ch;
clrscr();
student st[5];
for(int i=0;i<5;i++){
st[i].getinfo();
st[i].calculate();
Annamalai University
st[i].prnresult();
}
cout<<"continue y/n : ";
ch = getche();
Page 27
Object Oriented Programming – C++
# include<iostream.h>
# include<conio.h>
# include<iomanip.h>
# include<string.h>
int n;
class itemlist
{int itno;
char name[20];
float price;
public:
void getdata();
void sort_name();
void sort_price();
void display();
}item[5],temp[5];
void itemlist :: getdata()
{cout<<"\nItem name : ";
cin>>name;
cout<<"Item no : ";
cin>>itno;
cout<<"Item price: ";
cin>>price;
cout<<"\n";
}
void itemlist :: sort_name()
{int j,i,ptr;
for(i=0;i<n;i++)
{for(j=0;j<n;j++)
{ptr=strcmp(item[i].name,item[j].name);
if(ptr<0)
{temp[i]=item[j];
item[j]=item[i];
}
Annamalai University
item[i]=temp[i];
}
}
}
void itemlist :: sort_price()
{int j,i;
for(i=0;i<n;i++)
{for(j=0;j<n;j++)
{if(item[i].price<item[j].price)
Page 28
Object Oriented Programming – C++
{temp[i]=item[j];
item[j]=item[i];
item[i]=temp[i];
}
}
}
}
void itemlist :: display()
{cout<<"\n";
cout<<setw(7)<<setiosflags(ios::left)<<name;
cout<<setw(15)<<setiosflags(ios::right)<<itno;
cout<<setw(15)<<setiosflags(ios::right)<<price;
}
void main()
{clrscr();
int ch,i;
cout<<"Enter the no: of items : ";
cin>>n;
cout<<"\nEnter the details:- ";
for(i=0;i<n;i++)
{item[i].getdata();
}
cout<<"\nHow do you want to sort ?";
cout<<"\n1.Sort by item name\n2.Sort by price";
cout<<"\nEnter your choice : ";
cin>>ch;
if(ch==1)
{for(i=0;i<n;i++)
{item[i].sort_name();
}
}
else
{for(i=0;i<n;i++)
{item[i].sort_price();
}
}
Annamalai University
cout<<setw(21)<<setiosflags(ios::left)<<"\nName";
cout<<setw(15)<<setiosflags(ios::left)<<"Item no";
cout<<setw(20)<<setiosflags(ios::left)<<"Price";
for(i=0;i<n;i++)
{item[i].display();
}
}
Page 29
Object Oriented Programming – C++
#include <iostream.h>
#include <conio.h>
class B;
class A
{
int a[10];
public:
int n;
void inputa();
friend void merge (A, B);
}A1;
void A:: inputa()
{
cout<<"\nEnter the no. of elements in the arrays: ";
cin>>n;
cout<<"\nEnter array 1: ";
for(int i=1; i<=n; i++)
cin>>a[i];
}
class B
{
int b[10];
public:
void inputb();
friend void merge(A,B);
}B1;
void B:: inputb()
{
cout<<"\nEnter array 2: ";
for(int i=1; i<=A1.n; i++)
cin>>b[i];
}
Annamalai University
void merge ( A A2, B B2 )
{
int c[20], x=1, y=2;
for(int i=1; i<=A2.n; i++)
{
c[x]= A2.a[i];
c[y]= B2.b[i];
x+=2;
y+=2;
}
Page 30
Object Oriented Programming – C++
void main()
{
clrscr();
A1.inputa();
B1.inputb();
merge (A1,B1);
getch();
}
#include <iostream.h>
#include <conio.h>
class employee
{class date
{
public:
int dd[5], mm[5], yyyy[5];
void input ()
{ cout<<"\n";
for(int i=1;i<=e1.n; i++)
{
cout<<"Input Date of birth (dd mm yyyy) of employee
"<<i<<": ";
cin>>dd[i]>>mm[i]>>yyyy[i];
}
}
};
char name[5][10], des[5][12];
Annamalai University
int bp[5], sp[5];
int it[5], gis[5], pf[5], hra[5];
float da[5], gross[5], net[5];
public:
int i, n;
date d;
void initialise ();
void DA();
void HRA();
void GROSS();
void NET();
Page 31
Object Oriented Programming – C++
void print();
}e1;
Annamalai University
void employee :: GROSS()
{ int cca=250;
for(i=1;i<=n;i++)
gross[i]=bp[i]+ sp[i]+ hra[i]+ da[i]+ cca;
}
void employee :: NET()
{ for(i=1;i<=n;i++)
net[i]=gross[i]- (pf[i]+ gis[i]+ it[i]);
}
void employee :: print ()
{
Page 32
Object Oriented Programming – C++
for (i=1;i<=n;i++)
{cout<<"\n\tNAME: "<<name[i]<<"\tDESIGNATION:
"<<des[i]<<"\tDOB: "<<d.dd[i];
cout<<" "<<d.mm[i]<<" "<<d.yyyy[i]<<"\n\tDearness
Allowance: "<<da[i];
cout<<"\n\tHouse Rent allowance: "<<hra[i]<<"\n\tGross:
"<<gross[i]<<"\n\tNet amount: "<<net[i]<<endl;
}
}
void main()
{ clrscr();
e1.initialise();
e1.d.input();
e1.DA();
e1.HRA();
e1.GROSS();
e1.NET();
e1.print();
getch();
}
#include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
void area(int);
void area(int,int);
void area(float);
int r,l,b;
float s;
cout<<"Enter the radius of the circle :";
cin>>r;
cout<<"Enter the lenght & breadth of the rectangle :";
cin>>l>>b;
Annamalai University
cout<<"Enter the side of the square :";
cin>>s;
area(r);
area(l,b);
area(s);
getch();
}
void area(int r)
{cout<<""<<endl<<"*************** Area***********"<<endl;
cout<<"The area of the circle is :"<<3.14*r*r<<endl;
Page 33
Object Oriented Programming – C++
void area(float s)
{cout<<"The area of the square is :"<<s*s<<endl;
}
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
struct student
{
double Rno;
char Name[20];
float Marks[3];
float Total;
};
void create()
{
clrscr();
student S;
fstream fout("STUD.DAT",ios::app);
cout<<"Enter student details:";
clrscr();
cout<<"Enter student roll number:";
cin>>S.Rno;
cout<<"Enter student name:";
cin>>S.Name;
cout<<"Enter student marks:";
cout<<endl<<"Subject 1:";
Annamalai University
cin>>S.Marks[0];
cout<<"Subject 2:";
cin>>S.Marks[1];
cout<<"Subject 3:";
cin>>S.Marks[2];
S.Total=S.Marks[0]+S.Marks[1]+S.Marks[2];
fout.write((char *) &S,sizeof(S));
fout.close();
getch();
}
void search()
Page 34
Object Oriented Programming – C++
{
double roll;
student S;
cout<<"Enter roll no:";
cin>>roll;
ifstream fin("STUD.DAT",ios::in);
while(!fin.eof())
{
fin.read((char *) &S,sizeof(S));
if(S.Rno==roll)
{
cout<<endl<<"Record found...";
cout<<endl<<"Roll number:"<<S.Rno;
cout<<endl<<"Name:"<<S.Name;
cout<<endl<<"Total:"<<S.Total;
getch();
goto end;
}
}
cout<<"Record not found...";
getch();
end:
}
int menu()
{
clrscr();
int opt;
cout<<endl<<"~~~~~~~~~~~~~~~~~MENU~~~~~~~~~~~~~~~~~";
cout<<endl<<"1)CREATE A RECORD";
cout<<endl<<"2)SEARCH FOR A RECORD";
cout<<endl<<"3)EXIT";
cout<<endl<<"~~~~~~~~~~~~~~~~~MENU~~~~~~~~~~~~~~~~~";
cout<<endl<<"Enter your choice:";
cin>>opt;
return opt;
}
void main()
{
Annamalai University
int ch;
while(ch!=3)
{
ch=menu();
switch(ch)
{
case 1:
create();
break;
Page 35
Object Oriented Programming – C++
case 2:
search();
break;
case 3:
getch();
}
}
}
The best way to overload the stream operators is not to make them members of any class,
but to keep them as friends. i.e., wherever there is a need to use the stream operators, use
them as friend functions with the suitable parameters.
The following example shows the use of these operators for a class.
#include <iostream.h>
#include <string.h>
class Base
{
char strVal[100];
public:
Base(){ strcpy(strVal,"");}
Base(char *val){ strcpy(strVal,val);}
~Base(){*strVal = '\0';}
friend istream& operator >>(istream &is,Base &obj);
friend ostream& operator <<(ostream &os,const Base
&obj);
};
Annamalai University
istream& operator >>(istream &is,Base &obj)
{
is>>strVal;
return is;
}
ostream& operator <<(ostream &os,const Base &obj)
{
os<<obj.strVal;
return os;
}
void main()
Page 36
Object Oriented Programming – C++
{
Base b;
cin>>b;
cout<<"Printing the value\n";
cout<<b<<endl;
}
Note: If there are derived classes which need to use the stream operators, one way is to define
some more versions of the stream operators with the derived class Parameters.
File handling is an important part of all programs. Most of the applications will have their
own features to save some data to the local disk and read data from the disk again. C++
File I/O classes simplify such file read/write operations for the programmer by providing
easier to use classes.
The most important methods which will be used for any file operations are:
This sample code snippet explains how to use the c++ file i/o stream operators to read
data from a file. In all cases the header file fstream.h must be included.
Page 37
Object Oriented Programming – C++
#include<fstream.h>
int main()
{
char str[2000];
fstream file_op("c:\\test_file.txt",ios::in);
while(file_op >> str)
cout <<STR;
< str ;
file_op.close();
return 0;
}
The class fstream, which is used above is the one which is commonly used for c++ file
i/o manipulations. The constructor of fstream takes 2 parameters. One is the file path and
the second is the File Open mode. There are several open modes, each of them with a
different purpose. Some of them are ios::in for reading, ios::out for writing, ios::app for
appending to the end of file, ios::binary for opening in binary mode etc.,
Now for the purpose of this article, as the data is read from the file, the flag ios::in is
used. After this, the read operation is continued till the end of the file. The while loop
ensures a continuous read till the end of the file or it encounters any abnormal break. If
the program is built and run , it displays all the data read from the file. The C++ File I/O
read job is done.
But if we look at the output closely, there is a draw back in using this stream operator
read. The output misses the white spaces and the end of line characters. In order not to
miss these characters we can either use fstream::get() or fstream::getline() methods. Here
is the example for using fstream getline method.
#include <fstream.h>
int main()
{
char str[2000];
fstream file_op("c:\\test_file.txt",ios::in);
Annamalai University
while(!file_op.eof())
{
file_op.getline(str,2000);
cout <<str;
} file_op.close();
cout <<endl;
return 0;
}
Page 38
Object Oriented Programming – C++
Writing to a text file can also be achieved with the stream operators. This also follows
the same order of operations, though with a slight difference.
1. open a file - in write mode
2. Write to a file
3. close the file
Look at the following sample code to see the difference.
#include <fstream.h>
int main()
{
fstream
file_op("c:\\CoderSource_file.txt",ios::out);
Note: To modify the data or to seek to a different position inside the file, the c++ file i/o
class fstream provides member functions like seekg() etc., These functions can be used to
relocate the record insert position to the desired locations.
After all the C++ File I/O operations we do a fstream::close(), to close the file pointer.
This is not mandatory. Even if this function is not called by the application, the destructor
of the fstream class will close the file when the object goes out of scope.
In C++ it is perfectly possible that a class inherits members from more than one class.
This is done by simply separating the different base classes with commas in the derived
Annamalai University
class declaration. For example, if we had a specific class to print on screen (COutput) and
we wanted our classes CRectangle and CTriangle to also inherit its members in addition
to those of CPolygon we could write:
// multiple inheritance
Page 39
Object Oriented Programming – C++
#include <iostream>
using namespace std;
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b;}
};
class COutput {
public:
void output (int i);
};
int main () {
CRectangle rect;
CTriangle trgl;
rect.set_values (4,5);
Annamalai University
trgl.set_values (4,5);
rect.output (rect.area());
trgl.output (trgl.area());
return 0;
}
Page 40
Object Oriented Programming – C++
Objects generally need to initialize variables or assign dynamic memory during their
process of creation to become operative and to avoid returning unexpected values during
their execution. For example, what would happen if in the previous example we called
the member function area() before having called function set_values()? Probably we
would have gotten an undetermined result since the members x and y would have never
been assigned a value.
In order to avoid that, a class can include a special function called constructor, which is
automatically called whenever a new object of this class is created. This constructor
function must have the same name as the class, and cannot have any return type; not even
void.
As you can see, the result of this example is identical to the previous one. But now we
have removed the member function set_values(), and have included instead a constructor
that performs a similar action: it initializes the values of x and y with the parameters that
are passed to it.
Notice how these arguments are passed to the constructor at the moment at which the
objects of this class are created:
Constructors cannot be called explicitly as if they were regular member functions. They
are only executed when a new object of that class is created.
You can also see how neither the constructor prototype declaration (within the class) nor
the latter constructor definition include a return value; not even void.
The destructor fulfills the opposite functionality. It is automatically called when an object
is destroyed, either because its scope of existence has finished (for example, if it was
defined as a local object within a function and the function ends) or because it is an
object dynamically assigned and it is released using the operator delete.
Annamalai University
The destructor must have the same name as the class, but preceded with a tilde sign (~)
and it must also return no value.
The use of destructors is especially suitable when an object assigns dynamic memory
during its lifetime and at the moment of being destroyed we want to release the memory
that the object was allocated.
Page 41
Object Oriented Programming – C++
class CRectangle {
int *width, *height;
public:
CRectangle (int,int);
~CRectangle ();
int area () {return (*width * *height);}
};
CRectangle::~CRectangle () {
delete width;
delete height;
}
int main () {
CRectangle rect (3,4), rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}
It is perfectly valid to create pointers that point to classes. We simply have to consider
that once declared, a class becomes a valid type, so we can use the class name as the type
for the pointer. For example:
CRectangle * prect;
Annamalai University
is a pointer to an object of class CRectangle.
class CRectangle {
Page 42
Object Oriented Programming – C++
int main () {
CRectangle a, *b, *c;
CRectangle * d = new CRectangle[2];
b= new CRectangle;
c= &a;
a.set_values (1,2);
b->set_values (3,4);
d->set_values (5,6);
d[1].set_values (7,8);
cout << "a area: " << a.area() << endl;
cout << "*b area: " << b->area() << endl;
cout << "*c area: " << c->area() << endl;
cout << "d[0] area: " << d[0].area() << endl;
cout << "d[1] area: " << d[1].area() << endl;
delete[] d;
delete b;
return 0;
}
The following is an example of a function try block with a member initializer, a function
try block and a try block:
#include <iostream>
using namespace std;
class E {
Annamalai University
public:
const char* error;
E(const char* arg) : error(arg) { }
};
class A {
public:
int i;
Page 43
Object Oriented Programming – C++
void g() {
throw E("Exception thrown in g()");
}
int main() {
f();
// A try block
try {
g();
}
catch (E& e) {
cout << e.error << endl;
}
try {
A x;
}
catch(...) { }
}
Annamalai University
The following is the output of the above example:
The constructor of class A has a function try block with a member initializer. Function f()
has a function try block. The main() function contains a try block
Page 44