0% found this document useful (0 votes)
224 views45 pages

Annamalai University

The document provides an overview of how to use the Borland C++ integrated development environment (IDE) for writing, compiling, linking and running C++ programs, including details on creating and editing source code files, setting compiler options and paths, using projects, and troubleshooting common issues like graphics errors. It describes the different windows in the IDE and how to navigate between them, use menu options and keyboard shortcuts to compile, link and run programs, and set directories for header files, libraries and output.

Uploaded by

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

Annamalai University

The document provides an overview of how to use the Borland C++ integrated development environment (IDE) for writing, compiling, linking and running C++ programs, including details on creating and editing source code files, setting compiler options and paths, using projects, and troubleshooting common issues like graphics errors. It describes the different windows in the IDE and how to navigate between them, use menu options and keyboard shortcuts to compile, link and run programs, and set directories for header files, libraries and output.

Uploaded by

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

IT0215

ANNAMALAI UNIVERSITY
DIRECTORATE OF DISTANCE EDUCATION

MSc INFORMATION TECHNOLOGY


FIRST SEMESTER

PROGRAMMING LAB – I
OBJECT ORIENTED PROGRAMMING C++
Annamalai University

Copyright Reserved
(For Private Circulation Only)
Object Oriented Programming – C++

C/C++ Programming Using Borland C++

How to start?

Switch on the computer and login.


Go to DOS prompt: Start->Programs->MS-DOS Prompt
If not already on Z: drive, type ‘Z:’ at the prompt and then type ‘bc’ and press ENTER.
Z:\>bc<ENTER>

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

About the Borland’s IDE:


The Integrated Development Environment (IDE) is an editor, compiler, linker,
project manager, and debugger all in one. In it, you can create, compile, and debug
almost all your DOS and Windows applications without ever leaving the IDE. This
greatly speeds up your application development, especially during the debugging
(removing logical error) stage, when you are constantly testing, modifying, and

Page 1
Object Oriented Programming – C++

recompiling your source code.


BC++ also include help application, called THELP, which provides access to the IDE’s
help files if you choose to use an external text editor. This and many other facilities are
integrated into it.
The IDE centers around a fully functional text editor. The text editor in the IDE goes
beyond merely allowing you to enter text. You can select a block of text (code) by
holding SHIFT key and pressing ARROW keys and perform cut, copy, and paste
operations.

Different Windows of IDE:


There are different windows for the IDE. Each window will be having a double
border, a number and a title designating the window. You can switch between these
windows by pressing F6 key successively or

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.

Writing the C/C++ Program:

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”.

Compiling and Linking the Program:

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.

Setting Directory Paths for IDE:

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.

Problem with Graphics!

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.

Another problem with graphics is


BGI Error: Graphics not initialized (use ‘initgraph’)

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:

There are many advantages to using a project.


It keeps a list of file dependencies for you and is much easier to use than manually
recompiling changed files using the MAKE utility.
It keeps one set of compiler options for one project from affecting an application
compiled with different set of compiler options.
Each project file contains information on the compiler option settings.
Each project file also has an associated desktop file. This file keeps track of the screen
layout and cursor location for the editor windows
Select Options->Environment->Preferences->Desktop menu item. Now each time you
load a project, the screen will be laid out exactly as you left it last time to the correct
location of the cursor.
Project Manager takes care of many things like controlling the project (fatal errors,
warnings, etc;), checking auto-dependencies, linking default libraries appropriate to the
compiler settings, etc.
Also you can keep list of Project Notes. Select Windows->Project Notes.
This is the good place to keep notes on revision history, bug reports, or other information
related to the project. The contents of Project Notes Window are automatically saved
with the project file.

Creating a Project:

To create a new project you have to go through following steps:


From Project menu select Open project…; ‘Open Project File’ dialog box will appear.
In Open Project File text-area type-in the new project’s name and press ENTER. A new
project will be created and an empty Project Window will appear.
Next step is to add source files to the project. You can create new source files, if not
existing, and add to the project as follows:
From Project menu select Add item…; ‘Add to Project List’ dialog box will appear.
In that you can directly enter the filename into Name Box or choose from the Files List
and either press ENTER or click on Add Button. The selected file will be added to the
current project. Similarly add all the required files.
Click on Done Button. The dialog box will close and you will be brought to the Project
Window.
Now you can see the list of files belonging to the project in the Project Window. You can
Annamalai University
scroll through all the files using arrow keys. When you press ENTER key, that file will
be opened into the Edit Window.

Menu Options Provided by IDE:

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++

Save all: Saves all modified files


Change dir: Change the current working directory
Print: Print the contents of active window
DOS shell: Temporary exit to DOS
Quit: Quits the IDE
Edit Menu:

Undo: Undo the previous editor action


Redo: Redo the previously undone action
Cut: Remove the selected text and put it in the clipboard
Copy: Copy the selected text and put it in the clipboard
Paste: Insert selected text from clipboard at the cursor position
Clear: Delete the selected text
Copy example: Copy program example from Help Window into the clipboard
Show clipboard: Open the Clipboard Window and display its contents.
Search Menu:

Find: Search for the text in the source code


Find and replace: Search for the text and replace it with new text
Search again: Repeat the last Find or Replace operation
Go to line number: Move the cursor to a specific line number
Previous error: Move the cursor to the position of the previous message
Next error: Move the cursor to the position of the next message
Locate function: Search for a function declaration while debugging

Run Menu:
Compile Menu:
Debug Menu:
Project Menu:
Options Menu:
Window Menu:
Help Menu:

Executing Turbo C++ from Windows

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.

Notice the two numbers (1:1) in the lower left-hand

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

the result of raising the base to that power on standard output.

Note: Exponent must be a positive integer. */


Annamalai University
#include <iostream.h> // include the io stream header file.

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.

Please enter a base & exponent (integers):

You should now type 2 integers (i.e. , 3 3) then tap ENTER.

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 program, you will use Notepad. Choose Start/Programs/Programming


Languages/Notepad. In Notepad choose File/Open. Use the up arrow key icon near the
top of the Open dialog box. Click this key until you see "3 1/2 Floppy (A)" appear in the
large box. Double click on it. Then click on the down arrow scroller on the right of the
Files of Type text box. Click on All Files (*.*). Your file (power.cpp) should appear.
Double click on the file you want to print. Then choose File/Print to print it.

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.

Step 10. (Quitting your session.)

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.

Some important keys are:

Alt-X Exit C++

Alt-F5 View output screen

Alt-F Activate the file menu for loading and saving.

Page 11
Object Oriented Programming – C++

Ctrl-F9 Run the program

F2 Save the program

PrtSc Print the present screen

Esc Escape the present menu (often useful if you are lost in the menu system,

brings you back to a familiar screen, usually the editor).

F10 Get back to the Turbo menu (e.g. back to the File menu).

Ctrl-Break Stop a program from running (if it gets out of control).

Ctrl-F1 Help for the item on which the cursor is located.

F1 F1 Displays an index of help options.

F1 Displays help information relating to your current activity.

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

The C language is accompanied by a number of library function that carry


out various commonly used operations and calculation. These library functions are not
part of the language. Such functions are standardized in header files by ANSI committee.

The header files that are included in this Appendix are :-

<ctype.h> Character testing and conversion functions.

<math.h> Mathematical functions.

<stdio.h> Standard I/O library functions.

<stdlib.h> Utility functions such as string conversion routines, memory


allocation routines, random number generator, etc.

<string.h> String manipulation functions.

<time.h> Time manipulation functions.

Note: The following function parameters are used :


c- character type argument
d- double precision argument
f - file argument
i- integer argument
l- long integer argument
p- pointer argument
s- string argument
u- unsigned integer argument.
An asterisk ‘* ‘ denotes a pointer.

Function Data type Task

Annamalai University
Returned

<math.h>

ascos( d) double Return the arc cosine of d

asin( d) double Return the arc sine of d

atan(d) double Return the arc tangent of d

atan2(d1,d2) double Return the arc tangent of d1/d2

Page 13
Object Oriented Programming – C++

ceil(d) double Return a value rounded up to the next higher


integer.

cos(d) double Return the cosine of d.

cosh(d) double Return the hyperbolic cosine of d.

exp(d) double Raise e to the power d.

fabs(d) double Return the absolute value of d

floor(d) double Return a value rounded down to the next


lower integer.

fmod(d1,d2) double Return the remainder of d1/d2 (with same


Sign as d1).

labs(1) long int Return the absolute value of 1.

log10(d) double Return the logarithm (base10) of d.

pow(d1,d2) double Return d1 raised to the d2 power

sin(d) double Return the sine do d

sinh(d) double Return the hyperbolic sine of d.

sqrt(d) double Return the square root of d.

tan(d) double Return the tangent of d.


<stdio.h>

fclose(f) int Close file f. Return 0 if file is successfully


closed.

feof(f) Annamalai University


int Determine if an end-of-file condition has
been reached. If so, return a nonzero value;
otherwise, return 0.

fgetc(f) int Enter a single character form file f.

fgets(s, i, f) char* Enter a single character form file f.

fopen (s1,s2) file* Open a file named s1 of type s2. Return a


pointer to the file.

Page 14
Object Oriented Programming – C++

fprintf(f,…) int Send data items to file f.

fputc(c,f) int Send a single character to file f.

fputs(s,f) int Send a single s to file f.

fread(s, i1, i2, f) int Enter i2 data items, each of size i1 bytes,
from file f to string s.

fscanf(f,…) int Enter data items from file f.

fseek(f,l,1) int Move the pointer for file f a distance 1 bytes


from location i.

ftell(f) long int Return the current pointer position within


file f.

fwrite(s,i1,i2) int Send i2 data items, each of sixe i1 bytes


from string s to file f.

getc(f) int Enter a single character from file f.

getchar(void) int Enter a single character from the standard


input device.

gets(s) char* Enter string s from the standard input


device.

puts(s) int Send string s to the standard output device.

printf(…) int Send data items to the standard output dev.

putc(c,f) int Send a single character to file f.

putchar( c) int Send a single character to the standard


Annamalai University
output device.

rewind(f) void Move the pointer to the beginning of file f.

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++

atof(s) double Convert string s to a double precision qty.

atoi(s) int Convert string s to an integer.

atol(s) long Convert string s to a long integer.

calloc(u1, u2) void* Allocate memory for an array having u1


elements, each of length u2 bytes. Return a
pointer to the beginning of the allocated
space.

exit(u) void Close all files and buffers, and terminate the
program.( Value of u is assigned by the
function, to indicate termination status.)

malloc(u) void* Allocate au bytes of memory. Return a


pointer to the beginning of the allocated
space.

free(p) ` void Free a block of allocated memory whose


beginning is indicated by p.

rand(void) int Return a random positive integer.

Realloc(p,u) void* Allocate u bytes of new memory to the


Pointer variable p. Return a pointer to the
Beginning of the new memory space.

srand(u) void Initialize the random number generator.

system(s) int Pass command string s to the operating


system. Return 0 if the command is
successfully executed; otherwise, return a
nonzero value rypically –1.

<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.

strcmpi(s1,s2) int Compare two strings lexicographically,


Without regard to case. Return a negativ
Value if s1<s2; 0 if s1 and s2 are ident-
cal ; and a value if s1>s2.

Page 16
Object Oriented Programming – C++

strcpy (s1, s2) char* Copy string s2 to string s1.

strlen(s) int Return the number of char.s in string s.

strset(s,c) char* Set all characters within s to c(excluding


the terminating null character \0).

<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.)

time(p) long int Return the number of seconds elapsed


beyond a designated base time.

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++

1. Program for Generating Fibonocci Series using Classes

# 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++

2. Student Mark Processing Program

#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++

cout<<"If by rank, type 1;else if in roll no. order,


type 0 ";
cin>>c;
cout<<endl;
cout<<setw(21)<<setiosflags(ios::left)<<"Name";
cout<<setw(5)<<setiosflags(ios::left)<<"Roll";
cout<<setw(7)<<setiosflags(ios::left)<<"Sub 1";
cout<<setw(7)<<setiosflags(ios::left)<<"Sub 2";
cout<<setw(7)<<setiosflags(ios::left)<<"Sub 3";
cout<<setw(6)<<setiosflags(ios::left)<<"Total";
cout<<setw(8)<<setiosflags(ios::left)<<"Average";
cout<<setw(4)<<setiosflags(ios::left)<<"Rank";
cout<<endl;
if(c==1)
outrank(s);
else
outroll(s);
getch(); }

3. Program to demonstrate Time functions

# 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++

cout <<"\n\t 4. EXIT ";


cout <<"\n\t ENTER CHOICE:";
cin >> choice;
switch (choice)
{
case 1:
day.print();
break;
case 2:
cout <<"\n\tENTER TIME TO ADD";
cout <<"\n\tENTER HOURS: ";
cin >> h;
cout <<"\n\tEMTER MINUTES: ";
cin >> m;
cout <<"\n\tENTER SECONDS: ";
cin >> s;
day.advance(h,m,s);
break;
case 3:
cout <<"\n\tENTER TIME TO RESET";
cout <<"\n\tENTER HOURS: ";
cin >> h;
cout <<"\n\tEMTER MINUTES: ";
cin >> m;
cout <<"\n\tENTER SECONDS: ";
cin >> s;
day.resent(h,m,s);
break;
case 4:
cout <<"\n\tTHANK YOU FOR ACCESSING!BYE";
exit(0);
break;
default:
cout <<"\n\tWRONG CHOICE! TRY AGAIN";
}
} while (choice);

}
Annamalai University
getch();

4. Program to demonstrate Inheritance

/ A PROGRAM IN C++ USING INHERITANCE


// =====================================

# 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";

if(marks3 <0 || marks3>100)


cout<<" INVALID MARKS ";
} while(marks3<0 || marks3>100);

do
{
cout<<"\n MARKS FOR CHEMISTRY" ;
cin>> marks4;
if(marks4<0 || marks4>100)

Page 25
Object Oriented Programming – C++

cout<<" INVALID MARKS ";


}while(marks4<0 || marks4>100);

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);

};

void student :: calculate(void)


{
float total;
total= marks1+ marks2 + marks3 + marks4 + marks5;
perc=total/5;
if (perc > 96 && perc <=100)
cout<<" STREAM IS COMPUTER SCIENCE ";

{
if (perc >91 && perc< 95)
cout<<" STREAM IS ELECTRONICS ";
}

if (perc >86 && perc< 90)


cout<<" STREAM IS MECHANICAL ";

if (perc >81 && perc <85)


Annamalai University
cout<<" STREAM IS ELECTRICAL ";

if (perc >76 && perc < 80)


cout<<" STREAM IS CHEMICAL ";

if (perc >71 && perc < 75)


cout<<" STREAM IS CIVIL ";

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 student:: prnresult(void)


{
cout<<"\n\t rollno"<< rollno<<"\n";
cout<<"name:";
cout<<name;
cout<<"\n";
cout<<"marks in subject 1:"<< marks1<<"\n";
cout<<"marks in subject 2:"<< marks2<<"\n";
cout<<"marks in subject 3:"<< marks3<<"\n";
cout<<"marks in subject 4:"<< marks4<<"\n";
cout<<"marks in subject 5:"<< marks5<<"\n";
cout<<"total
marks:"<<(marks1+marks2+marks3+marks4+marks5)<<"\n";
cout<<"percentage marks"<<perc<<"\n";
}

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++

6. Sorting of Objects using Classes


//Sorting of objects using classes

# 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++

7. Program to demonstrate Friend Function

#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++

cout<<"\nThe merged array: "<<endl;


for(i=1; i<=2*A2.n; i++)
cout<<c[i]<<" ";
}

void main()
{
clrscr();
A1.inputa();
B1.inputb();
merge (A1,B1);
getch();
}

8. Program to demonstrate Nested Classes

#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;

void employee ::initialise()


{ cout<<"\nEnter no. of records:";
cin>>n;
for(i=1;i<=n;i++)
{
cout<<"\nEnter your name. designation, Basic pay,
Special pay, GIS, IT, PF:";
cin>>name[i]>>des[i]>>bp[i]>>sp[i]>>gis[i]>>it[i]>>pf[
i];
}
}
void employee :: DA()
{ for (i=1;i<=n;i++)
if(bp[i]<=3500)
da[i]=1.14 * bp[i];
else if(bp[i]>3500 && bp[i]<=6000)
da[i]=.85 * bp[i];
else
da[i]= .74 * bp[i];
}

void employee :: HRA()


{ for(i=1;i<=n;i++)
if(bp[i]<1500)
hra[i]=250;
else if(bp[i]>=1500 && bp[i]<2800)
hra[i]=450;
else if(bp[i]>=2800 && bp[i]<3500)
hra[i]=800;
else
hra[i]=1000;
}

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();
}

9. Program to demonstrate Function Overload

#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(int l,int b)


{ cout<<"The area of the rectangle is :"<<l*b<<endl;
}

void area(float s)
{cout<<"The area of the square is :"<<s*s<<endl;
}

10. Program to demonstrate File Processing

#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();
}
}
}

11. Program to demonstrate Operator Overloading

Operator overloading is a beautiful concept in C++. At times it is little confusing also.


But actually they are quite easy. Anyway, here is an example for overloading the stream
operators.

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.

12. File Handling in C++

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.

C++ File I/O Classes and Functions:


There are 3 File I/O classes in C++ which are used for File Read/Write operations.
They are

 ifstream - Can be used for File read/input operations


 ofstream - Can be used for File write/output operations
 fstream - Can be used for both read/write c++ file I/O operations

The most important methods which will be used for any file operations are:

1. fstream::open method - to open the file


2. fstream::Operator >> and fstream::Operator << - For reading from or writing to
the file.
3. fstream::close - Flushes all buffer and close the file

Reading a text file using fstream class:


Annamalai University
There are several ways of reading the text from a file. But all of them have a common
approach as follows.

1. Open the file


2. Read the data
3. Close the file

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 using fstream class:

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);

file_op<<"Test Write to file";


file_op.close();
return 0;
}

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.

13. Multiple inheritance

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:

class CRectangle: public CPolygon, public COutput;


class CTriangle: public CPolygon, public COutput;

here is the complete example:

// 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);
};

void COutput::output (int i) {


cout << i << endl;
}

class CRectangle: public CPolygon, public COutput {


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

class CTriangle: public CPolygon, public COutput {


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

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++

14. Constructors and destructors

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:

CRectangle rect (3,4);


CRectangle rectb (5,6);

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.

// example on constructors and destructors


#include <iostream>
using namespace std;

Page 41
Object Oriented Programming – C++

class CRectangle {
int *width, *height;
public:
CRectangle (int,int);
~CRectangle ();
int area () {return (*width * *height);}
};

CRectangle::CRectangle (int a, int b) {


width = new int;
height = new int;
*width = a;
*height = b;
}

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;
}

15. Pointers to classes

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.

As it happened with data structures, in order to refer directly to a member of an object


pointed by a pointer we can use the arrow operator (->) of indirection. Here is an example
with some possible combinations:

// pointer to classes example


#include <iostream>
using namespace std;

class CRectangle {

Page 42
Object Oriented Programming – C++

int width, height;


public:
void set_values (int, int);
int area (void) {return (width * height);}
};

void CRectangle::set_values (int a, int b) {


width = a;
height = b;
}

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++

// A function try block with a member


// initializer
A() try : i(0) {
throw E("Exception thrown in A()");
}
catch (E& e) {
cout << e.error << endl;
}
};

// A function try block


void f() try {
throw E("Exception thrown in f()");
}
catch (E& e) {
cout << e.error << endl;
}

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:

Exception thrown in f()


Exception thrown in g()
Exception thrown in A()

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

You might also like