155E1130 UNIX, C & C++
155E1130 UNIX, C & C++
155E1130 UNIX, C & C++
ANNAMALAI UNIVERSITY
DIRECTORATE OF DISTANCE EDUCATION
Copyright Reserved
(For Private Circulation Only)
Unix, C & C++
Table of Contents
1.0 Introduction 1
1.1 Objective 1
1.2 Content 1
1.2.1 Operating System – An Introduction 1
1.2.2 History of UNIX 2
1.2.3 UNIX Fundamentals 3
1.2.4 Text Processing 5
1.2.5 Communication 5
1.2.6 The UNIX Environment 6
1.2.7 Introduction to Shell Programming 7
1.2.8 Shell Variables 7
1.2.9 Shell Meta Characters 9
1.2.10 Text Processing 11
1.2.11 Program Development Tools 11
1.2.12 Debugging Tools 12
1.2.13 Program Maintenance Tools 13
1.3 Revision Points 13
1.4 Intext Questions 14
1.5 Summary 14
1.6 Terminal Exercises 14
1.7 Supplementary Materials 14
1.8 Assignments 15
1.9 Suggested Reading 15
1.10 Learning Activities 15
1.11 Keywords 15
UNIT – II
2.0 Introduction 16
2.1 Objective 16
2.2 ANNAMALAI
ANNAMALAI UNIVERSITY
Content UNIVERSITY
2.2.1 Introduction to Programming
16
16
2.2.2 C Character Set Instructions 18
2.2.3 Operators 19
2.2.4 Data Types 20
2.2.5 Console based I/O 20
2.2.6 Functions 22
2.2.7 Processor Directives 24
2.2.8 Programming Style in C 24
2.2.9 Control Structures 25
2.3 Revision Points 33
2.4 Intext Questions 33
2.5 Summary 33
2.6 Terminal Exercises 34
2.7 Supplementary Materials 34
2.8 Assignments 34
2.9 Reference books 35
2.10 Learning Activities 35
2.11 Keywords 35
UNIT – III
3.0 Introduction 36
3.1 Objective 36
3.2 Content 36
3.2.1 Structure 36
3.2.1.1 Declaration of Structure 37
3.2.1.2 Accessing and Initialization of Structure 38
3.2.1.3 Array of Structure 39
3.2.1.4 Nested Structure 40
3.2.1.5 Pointers and structure 41
3.2.2 Unions 42
3.2.3 File Handling 42
3.2.3.1 Text mode Unformatted I/O functions 44
3.2.3.2 Line Input and Output 45
3.2.3.3 Text mode Formatted I/O functions 47
3.2.3.4 Binary mode I/O Functions 47
3.3 Revision Points 48
3.4 Intext Questions 48
3.5 Summary 48
3.6 Terminal Exercises 49
3.7 Supplementary Materials 49
3.8 Assignments 49
3.9 Reference books 49
3.10 Learning Activities 50
3.11 Keywords 50
UNIT – IV
4.0 ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Introduction 51
4.1 Objective 53
4.2 Content 53
4.2.1 Object Oriented Programming 53
4.2.1.1 Features of OOPs 53
4.2.1.2 Basic Concepts of OOPs 53
4.2.1.3 Principles of OOP 55
4.2.1.4 Problems in Software Development 55
4.2.1.5 Applications of OOP 56
4.2.2 Introduction to C++ 56
4.2.3 Introduction to I/O 59
4.2.4 Operators & Manipulators 64
4.2.5 Basic Control Structures 71
4.2.6 Defining Classes and Objects 81
4.2.7 Functions and its Types 86
4.2.8 Function Overloading 89
4.2.9 Constructors 90
4.2.10 Constructor Overloading 92
4.2.11 Destructors 93
4.2.12 Dynamic initialization of objects 94
4.2.13 Copy Constructor 97
4.2.14 Friend Function 99
4.2.15 Operator Overloading 100
4.2.16 Type Conversions 104
4.3 Revision Points 107
4.4 Intext Questions 108
4.5 Summary 109
4.6 Terminal Exercises 111
4.7 Supplementary Materials 111
4.8 Assignments 111
4.9 Reference books 112
4.10 Learning Activities 112
4.11 Keywords 112
UNIT – V
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Unix, C & C++
UNIT - I
Snapshot
Operating System – An Introduction
History of Unix
Unix fundamentals
Text Processing
Communication
The Unix Environment
Introduction to the Shell Programming
Shell Variables
Shell Meta characters
Text Processing
Program Development Tools
Debugging Tools
Programming Maintenance Tools
1.0 Introduction
An operating system is an important part of a computer system. You can view a
computer system as being built from three general components: the hardware, the
operating system, and the applications. The hardware includes pieces such as a central
processing unit (CPU), a keyboard, a hard drive, and a printer. Applications are why you
use computers; they use the rest of the system to perform the desired task (for example,
play a game, edit a memo, send electronic mail). The operating system is the component
that on one side manages and controls the hardware and on the other manages the
applications. UNIX is an increasingly popular operating system. Traditionally used on
minicomputers and workstations in the academic community, UNIX is now available on
personal computers, and the business community has started to choose UNIX for its
openness. Previous PC and mainframe users are now looking to UNIX as their operating
system solution.
1.1 Objective
The objective of this lesson makes the learner aware of the fundamentals of UNIX
operating system, which consists a broad range of topics from operating system and
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
UNIX fundamentals. The fundamental concepts include text processing, communication,
UNIX environment, and introduction to shell programming and program development
and maintenance tools. Towards end of this lesson the student can get the basic
knowledge about UNIX operating system.
1.2 Content
1.2.1 Operating System – An Introduction
An operating system (OS) is a collection of software programs that coordinates
the operation of computer hardware and software.
Page 1
Unix, C & C++
Functions of an OS
An operating system provides various functions as depicted in the following
diagram.
Command
Interpretation
Memory
Management
1. Command Interpretation
The Command Interpreter reads the commands entered by a user at the
command prompt and translates the commands into instructions which the
computer’s CPU can understand.
2. Process Management
Process Management is required if a number of programs have to run
parallelly. The OS has to ensure that no program gets more than its share of
CPU time.
3. Peripheral Management
The Main function of the OS is the Peripheral Management, the
communication between the peripheral devices and the CPU is overseen by the
OS.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
4. Memory Management
The OS handles the job of allocating the memory for the various process
running on the system.
Page 2
Unix, C & C++
Page 3
Unix, C & C++
Getting Started
In order to use the UNIX system, first the user has to login. To login to the Unix
system the user needs to type in the user id in the login: prompt and then pressing the
Enter key prompts for a password which the user has to type to enter into the Unix
system.
Login: test <ret>
Password: ****
$
Once the user has successfully logged in, the Unix system will indicate that it is
ready to accept the command by displaying a dollar sign ($).
If the user enters a wrong password then, the Unix system will prompt a message
saying login incorrect and will display the login: prompt again for the user to re-enter the
user id and password.
Login: test
Password : ******
Login incorrect
Login:
UNIX allows user to create their own files by using a command called cat. The
cat command can also be used for appending content to an already existing file and also
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
to view the content of a file. The following format is used for creating a file using cat
command
cat > filename
To append text to an already existing file, the format is:
cat >> filename
To view the content of an already existing file, the format is:
cat filename
Page 4
Unix, C & C++
Text processing is one of the things which people spend most time doing on any
computer. It is important to distinguish text editing from word processing. Normally
word or WordPerfect are used for writing documents.
UNIX has a word-like program called lyx, but most of the UNIX users do not use
word processors. It is more common in the UNIX community to write all documents
using a non formatting text editor.
emacs myfile
Emacs is the most powerful text editor that exists on any system. It is not a word-
processor, it is not used for formatting printed documents, but it can be linked to almost
any other program in order to format and print text.
1.2.5 Communication
Unix system allows a user at one terminal to interact with another user at some
other terminal. Some of the commands used for interaction are discussed below.
write command
This command is used to send a message from one user to another user who is
currently working on the system. This is a means of on-line communication because the
recipient obtains the message immediately.
The other user can respond to the message, by invoking the write command and
typing a message to the system. The conversation between the users can be terminated by
pressing the ctrl+d command.
ANNAMALAI
ANNAMALAI UNIVERSITY
news command UNIVERSITY
Unix can communicate in off-line mode also by using the news command To send
news to all users even if they are not logged in, the news command is useful. Only one
file is created and all the users read that file. When the user logs on the contents of the
news command are displayed on screen.
news [-a][-n][-s][items]
-a displays all items regardless of whether the message are already viewed or not.
-n shows only the names of the current files.
Page 5
Unix, C & C++
mesg command
The mesg command controls the display of messages on the screen. The user can
decide whether a message can be received by the system or not. The syntax to restrict
messages is mesg [n] [y]
wall command
This command is used to send messages to all users. The command is placed in
the /etc directory. To invoke the wall command the full path name has to be specified.
Example
$/etc/wall
Ctrl +d
1.2.6 The UNIX Environment
UNIX operating system’s structure consists of Kernel, Shell and tools and
applications
HW
Kernel
Shell
Kernel
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Kernel forms the core of the UNIX operating system. The Kernel interacts with
the hardware. It is loaded into the memory when a system is booted.
The functions of Kernel are:
Page 6
Unix, C & C++
The Kernel does not interact with the user directly, instead it starts up a separate
file called SHELL.
Shell
UNIX’s shell interacts with the user and the computer. The features of shell are as
follows:
The shell can modify the environment in which commands run. Input and output
can be redirected to files and processes that communicate through ‘pipes’ can be invoked.
Commands are found by searching directories in the file system in a sequence that can be
defined by the user. Commands can be read either from the terminal or from a file, which
allows command created to be sorted for later use.
Variables in shell scripts do not have associated data types. All variables in shell
scripts are treated as character strings.
ANNAMALAI
ANNAMALAI UNIVERSITY
Creating variables
UNIVERSITY
Variables can be created either in shell scripts or at the shell prompt. Any variable
created within a shell script is lost when the script stops executing. A variable created at
the prompt, however, will remain in existence until the shell is terminated. The format for
creating a variable is:
<variable name> =<value>
Example
Name=”ram”
Page 7
Unix, C & C++
Variables do not have to be explicitly declared. They can be created at any point
of time by a simple assignment of values.
Environment Variables
This variable contains the system prompt, that is. the $ symbol. Changing the
value of the ps1 variable can change the system prompt.
Example
$ps1=”Hello” <ret>
Hello
A list of filenames that are to be searched for Unix commands execution are
contained in this variable. The echo command is used to display the content of the
variable.
This variable contains the Home directory where the login shell is initially located
after logging in.
This variable contains the user’s login name or user name. The contents of this
variable cannot be changed by the user but can be displayed.
Some environmental variables like the HOME and the LOGNAME variable are
set automatically each time the user logs in. The others, however, have to be set. The
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
.profile file is used for this purpose. This file is a special shell script that is executed as
soon as the user logs in. It is similar to the autoexec.bat batch file in DOS.
Referencing Variables
The braces are optional, but the $ is essential. To assign value of one variable to
another variable, the command would be: Variable1=$variable2
Page 8
Unix, C & C++
The read command is used to enter value into a variable from the keyboard during
execution of a shell script.
read variablename
The read command on execution waits for a user to input the value of the variable.
The read command does not display any message to the user to enter data.
If a new shell (child shell) is created, then the child shell cannot use the variables
available in the parent shell. The same variable name can be given a different value
without the parent knowing about it. Such a variable is called a local variable.
Example
$name = ram
$echo”${name}”
ram
$sh //creating a new shell//
$echo”${name}”
$name = sam //new value is assigned to name.//
$echo”${name}”
sam
$ctrl d //return to parent shell
$echo”${name}”
ram //parent unaware of the child variable value ‘sam’\\
$sh
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
$echo “${name}”
$ ctrl d
//child value destroyed //
The environment variable can be transferred to the child shell using the export
command. The export command causes a copy of the variable name and values to be
passed onto a child shell process.
UNIX offers the facility to perform an operation on a set of files without having
to list out the names of all the files on which the operation has to be performed.
Page 9
Unix, C & C++
This is made possible by the use of certain special characters in the command in
place of the actual file-names. These special characters are interpreted by UNIX as a
specific pattern of characters. Unix then compares all file-names under the directory
specified in the command to find out which file-names match that pattern. The command
is executed on files whose names match the pattern.
Example
To display the contents of the three files, sample, sampletest, samplesort. All the
three file-names begin with sample. Instead of writing all three file-names in the cat
command, the following command can be used:
The * wild-card
‘*’ is used for representing any number of characters when used in the prefix or in
the suffix.
Example
To display files which start with ‘sa’
$ ls sa*
sample
sample file
$
The ? wild-card
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
‘?’ is used to represent one character only either in the prefix or in the suffix of
the filename.
Example
To display a file called test.
$ ls tes?
test
$
Page 10
Unix, C & C++
A screen editor allows the user to see the portions of the file on the terminal
screen and to modify characters and lines by simply typing at the current cursor position.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Vi is the most popular screen editor. One important aspect of vi is that it does not
provide the user with the original copy of the file when invoked. It provides with a
“editing buffer”. All changes are done to that copy in the buffer. Only when the file is
saved and when the user quits the vi, then the original file is replaced.
The UNIX system provides a powerful program called make. This program is
particularly useful for the development of program systems that comprise more than one
file. make automatically keeps track of files that have changed and causes their
recompilation when necessary. It also automatically relinks the programs if required.
Page 11
Unix, C & C++
The make program takes a file, known as the makefile as its input. This file
describes the following to make:
The dbx debugger on one hand is a source level debugger. This means that even
though it is running the object code, it is smart enough to direct to the statement in the
source that has caused the problem in the object code. On the other hand it is a symbolic
debugger that it is smart enough to tell the name and value of the variable on which the
program is having its difficulties.
In order to use the debuggers one must first compile the entire program with the –
g option. One should run the debugger on nonoptimized code only.
Some of the subcommands given from within dbx include the following:
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Help Tell me what I may command.
Run Execute the program.
Print Display value of var.
Page 12
Unix, C & C++
There are more subcommand available for use with dbx, which can be got from
the help
utility.
Where the make_command_file is the name of the file containing the directives
for make and target is the name of the target. Some common targets are usually all
components to be compiled and linked. Usually, install causes all components to be
moved to a predetermined location on the system. If the components are not compiled, it
should also trigger the compilation as well. Clean usually deletes any files with an
extension of “.o” as well as the filename “Core”. Dist usually deletes the same files as
“Clean” would have and the actual executable version as well.
UNIX
The UNIX operating system was developed at AT&T Bell Laboratories by Ken
Thompson and Dennis Ritchie in 1969 and the early 1970s. UNIX is a multi-user system
that supports networking and distributed file systems such as Sun Microsystems’ NFS
(Network File System) or the Open Software Foundation’s implementation of the AFS
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
(Andrew File System).UNIX highly portable and it now contains system components
written in a common, well-known programming language that are easily recompiled to
work on a variety of systems.
Page 13
Unix, C & C++
1.5 Summary
The Unix Operating System can be broken down into three basic components,
namely the Scheduler, the File System and the Shell.
The UNIX scheduler is a program that allows several users to access the
system simultaneously.
UNIX operating system structure consists of Kernel, Shell and tools and
applications.
1. The operating system that allows only one program to run at a time is
__________.
2. Define Network file system.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
3. List out the functions of kernel.
4. What are the features of shell programming?
5. Mention the use of wall command.
1.7 Supplementary Materials
Page 14
Unix, C & C++
1.8 Assignments
1. http://www.opengroup.org
2. http://www.unix.org
3. http://www.yahoo.com/Computers_and_Internet/Operating_Systems/Unix
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Page 15
Unix, C & C++
UNIT – II
Snapshot
Introduction to Programming
C Character Set Instructions
Operators
Data types
Console based I/O
Functions
Preprocessor Directives
Control Statements
2.0 Introduction
There are many programming languages used currently. One of the most popular
programming language is C. C is a structured programming language. Dennis M Ritchie
first developed the C language in 1972 at AT&T Bell labs primarily as a system
programming language.
2.1 Objective
The objective of this lesson provides a detailed description about C programming
language and its concepts in detail. The content of this lesson starts with introduction to
programming language and ends with control structures.
2.2 Content
2.2.1 Introduction to Programming
As a programming language, C is rather like Pascal or FORTRAN. Values are
stored in variables. Programs are structured by defining and calling functions. Program
flow is controlled using loops, if statements and function calls. Input and output can be
directed to the terminal or to files. Related data can be stored together in arrays or
structures. Of the three languages, C allows the most precise control of input and output.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
C is also rather terser than FORTRAN or Pascal. This can result in short efficient
programs, where the programmer has made wise use of C's range of powerful operators.
It also allows the programmer to produce programs which are impossible to understand.
Programmers who are familiar with the use of pointers (or indirect addressing, to use the
correct term) will welcome the ease of use compared with some other languages. The
following example will illustrate a simple C program. This program which will print out
the message This is a C program
#include <stdio.h>
main()
{
Page 16
Unix, C & C++
printf("This is a C program\n");
}
Though the program is very simple, a few points are worthy of note. Every C
program contains a function called main. This is the start point of the program. #include
<stdio.h> allows the program to interact with the screen, keyboard and file system of
your computer. You will find it at the beginning of almost every C program. Main ()
declares the start of the function, while the two curly brackets show the start and finish of
the function. Curly brackets in C are used to group statements together as in a function, or
in the body of a loop. Such a grouping is known as a compound statement or a block.
Printf ("This is a C program\n");
prints the words on the screen. The text to be printed is enclosed in double quotes. The \n
at the end of the text tells the program to print a new line as part of the output.
Most C programs are in lower case letters. You will usually find upper case letters
used in preprocessor definitions (which will be discussed later) or inside quotes as parts
of character strings. C is case sensitive, that is, it recognizes a lower case letter and its
upper case equivalent as being different.
Variables
In C, a variable must be declared before it can be used. Variables can be declared
at the start of any block of code, but most are found at the start of each function. Most
local variables are created when the function is called, and are destroyed on return from
that function. A declaration begins with the type, followed by the name of one or more
variables. For example,
Declarations can be spread out, allowing space for an explanatory comment. Variables
can also be initialized when they are declared; this is done by adding an equal’s sign and
the required value after the declaration. Every variable has a name and a value. The name
identifies the variable, the value stores data. There is a limitation on what these names
can be.
Every variable name in C must start with a letter; the rest of the name can consist
of letters, numbers and underscore characters. C recognizes upper and lower case
characters as being different. Finally, you cannot use any of C's keywords like main,
while, switch etc as variable names.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Local variables are declared within the body of a function, and can only be used
within that function. This is usually no problem, since when another function is called, all
required data is passed to it as arguments. Alternatively, a variable can be declared
globally so it is available to all functions. Modern programming practice recommends
against the excessive use of global variables. They can lead to poor program structure,
and tend to clog up the available name space.
A global variable declaration looks normal, but is located outside any of the
program's functions. This is usually done at the beginning of the program file, but after
preprocessor directives. The variable is not declared again in the body of the functions
which access it.
Page 17
Unix, C & C++
Where a global variable is declared in one file, but used by functions from
another, then the variable is called an external variable in these functions, and must be
declared as such. The declaration must be preceded by the word extern. The declaration is
required so the compiler can find the type of the variable without having to search
through several source files for the declaration. Global and external variables can be of
any legal type. They can be initialized, but the initialization takes place when the program
starts up, before entry to the main function.
Another class of local variable is the static type. A static can only be accessed
from the function in which it was declared, like a local variable. The static variable is not
destroyed on exit from the function; instead its value is preserved, and becomes available
again when the function is next called. Static variables are declared as local variables, but
the declaration is preceded by the word static.
Static variables can be initialized as normal; the initialization is performed once only,
when the program starts up.
1. Alphabets:
A B C D E F G H …………………………………….. X Y Z
A b c d e f g h ………………………………………… x y z
2. Digits:
0123456789
3. Special Characters:
, comma < opening angle bracket > closing angle bracket
. period _ under score ( left parenthesis
; semicolon $ dollar sign ) right parenthesis
ANNAMALAI
ANNAMALAI UNIVERSITY
: colon
UNIVERSITY
? question mark [ left bracket
# number sign & ampersand ] right bracket
“ quotation mark * asterisk { left brace
| Vertical bar - minus sign } right brace
~ tilde + plus sign / slash
\ backslash
Page 18
Unix, C & C++
2.2.3 Operators
One reason for the power of C is its wide range of useful operators. An operator is
a function which is applied to values to give a result. You should be familiar with
operators such as +, -, /. Arithmetic operators are the most common. Other operators are
used for comparison of values, combination of logical states, and manipulation of
individual binary digits. In C operators can be classified into various categories based on
their utility and action. A list of operator types is given below:
Arithmetic operators
+ Addition
- Subtraction
* Multiplication
/ Division
% modulo division
Relational operators
ANNAMALAI
ANNAMALAI UNIVERSITY
Logical operatorsUNIVERSITY
&& logical AND
|| logical OR
! logical NOT
Bitwise operators
& bitwise AND
! bitwise OR
Page 19
Unix, C & C++
^ bitwise XOR
<< shift left
>> shift right
~ bitwise complement
Increment and decrement operators
++<variable name> <variable name>++
--<variable name> <variable name>--
Other operators
Sizeof
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
signed short int
unsigned short int
signed int
unsigned int
signed long int
unsigned long int
Page 20
Unix, C & C++
of input and output. This means that they'll not start reading any input until the return key
is pressed, and they'll not print characters on the terminal until there is a whole line to be
printed.
getchar
getchar returns the next character of keyboard input as an int. If there is an error then
EOF (end of file) is returned instead. It is therefore usual to compare this value against
EOF before using it. If the return value is stored in a char, it will never be equal to EOF,
so error conditions will not be handled correctly. As an example, here is a program to
count the number of characters read until an EOF is encountered. EOF can be generated
by typing Control - d.
#include <stdio.h>
main()
{ int ch, i = 0;
printf("%d\n", i);
}
Putchar
putchar puts its character argument on the standard output (usually the screen). The
following example program converts any typed input into capital letters. To do this it
applies the function toupper from the character conversion library ctype.h to each
character in turn.
main()
{ int ch;
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
while((ch = getchar()) != EOF)
putchar(toupper(ch));
}
printf
The printf function is a very versatile output function. It can handle any basic data type,
and offers several facilities with which you can specify the way in which the data must be
displayed. This offers more structured output than putchar. Its arguments are, in order; a
control string, which controls what, gets printed, followed by a list of values to be
substituted for entries in the control string.
Page 21
Unix, C & C++
%d A decimal integer
%c A character
%s A character string
It is also possible to insert numbers into the control string to control field widths for
values to be displayed. For example %6d would print a decimal value in a field 6 space
wide; %8.2f would print a real value in a field 8 space wide with room to show 2 decimal
places. Display is left justified by default, but can be right justified by putting a - before
the format information, for example %-6d, a decimal integer right justified in a 6 space
field.
scanf
scanf allows formatted reading of data from the keyboard. Like printf it has a control
string, followed by the list of items to be read. However scanf wants to know the address
of the items to be read, since it is a function which will change that value. Therefore the
names of variables are preceded by the & sign. Character strings are an exception to this.
Since a string is already a character pointer, we give the names of string variables
unmodified by a leading &. Control string entries which match values to be read are
preceeded by the percentage sign in a similar way to their printf equivalents.
2.2.6 Functions
Almost all programming languages have some equivalent of the function. You
may have met them under the alternative names subroutine or procedure. Some languages
distinguish between functions which return variables and those which don't. C assumes
that every function will return a value. If the programmer wants a return value, this is
achieved using the return statement. If no return value is required, none should be used
when calling the function. Here is a function which raises a double to the power of an
unsigned, and returns the result.
return(ret_val);
}
The function follows a simple algorithm, multiplying the value by itself pow
times. A for loop is used to control the number of multiplications, and variable ret_val
stores the value to be returned. Careful programming has ensured that the boundary
condition is correct too. ie
Page 22
Unix, C & C++
Let us examine the details of this function. double power(double val, unsigned pow)
This line begins the function definition. It tells us the type of the return value, the name
of the function, and a list of arguments used by the function. The arguments and their
types are enclosed in brackets, each pair separated by commas. The body of the function
is bounded by a set of curly brackets. Any variables declared here will be treated as local
unless specifically declared as static or extern types.
return(ret_val);
On reaching a return statement, control of the program returns to the calling function. The
bracketed value is the value which is returned from the function. If the final closing curly
bracket is reached before any return value, then the function will return automatically,
any return value will then be meaningless. The example function can be called by a line
in another function which looks like this
This calls the function power assigning the return value to variable result. Here is an
example of a function which does not return a value.
This is a variant on the printf statement; fprintf sends its output into a file. In this case,
the file is stderr. stderr is a special UNIX file which serves as the channel for error
messages. It is usually connected to the console of the computer system, so this is a good
way to display error messages from your programs. Messages sent to stderr will appear
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
on screen even if the normal output of the program has been redirected to a file or a
printer. The function would be called as follows
error_line(line_number);
Page 23
Unix, C & C++
world is through global variables. Local variables are declared within a function. They
are created anew each time the function is called, and destroyed on return from the
function. Values passed to the function as arguments can also be treated like local
variables. Static variables are slightly different; they don't die on return from the function.
Instead their last value is retained, and it becomes available when the function is called
again. Global variables don't die on return from a function. Their value is retained, and is
available to any other function which accesses them.
#include <stdio.h>
Another use for #include for the programmer is where multi-file programs are being
written. Certain information is required at the beginning of each program file. Local
header file names are usually enclosed by double quotes, " ". It is conventional to give
header files a name which ends in .h to distinguish them from other types of file.
Page 24
Unix, C & C++
Control structure is used to control the sequence of the program flow. They are of
two categories namely:
Selection
Loops
Selection
In this case a statement is executed based on whether a condition is true or false.
Following statements are used in selective execution of statements.
a. The if Statement
if (expression)
statement;
where statement may consist of a single statement or a set of statements. If the if
expression evaluates to true, the statement or block following the if is executed. For
example:
#include<stdio.h>
main()
{
int a=10,b=10;
if (b= =a)
printf( “ the 2 values are equal”);
}
Output:
the 2 values are equal
In the above code since the value of a and b are the same, the expression in the if
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
is true and hence the statement following the if expression is executed.
b. if …else
The if…else statement is used for decision-making. It executes a statement based
on the result of evaluation of an expression. The general form of the if ..else statement is
if (expression)
statement 1;
else
statement 2;
Page 25
Unix, C & C++
#include <stdio.h>
main()
{
int x, y;
x = 3;
y = 4;
if (x > y)
printf(" x is greater");
else
printf(" y is greater");
}
Output:
y is greater
In the above program, variable x has been assigned the value 3 and variable y has
been assigned the value 4. In this case, since the value of x is not greater than y, the if
expression is false and hence the statement following if is not executed while the
statement following else is executed.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY if (expression) statement;
…..
…..
else statement;
This construct is also known as the if-else-if ladder or if-else-if staircase.
Though the above indentation is easily understandable with one or two ifs, it
confuses as the number of if increases. This is because it gets deeply indented and so, the
if-else-if is generally indented as:
Page 26
Unix, C & C++
if (expression)
statement;
else if (expression)
statement;
.
else
statement;
The conditions are evaluated from top to bottom. As soon as a true condition is
found, the statement associated with it is executed and the rest of the ladder is bypassed.
If none of the conditions are true the final else is executed. If the final else is not present,
no action takes place if all other conditions are false.
The following example takes a choice from the user. If the choice ranges from 1
to 3 it prints the choice else it prints Invalid choice.
#include <stdio.h>
#include <conio.h>
main()
{
int x;
x = 0;
clrscr();
printf("Enter Choice (1 - 3) : ");
scanf("%d", &x);
if (x == 1)
printf("\nChoice is 1");
else if (x == 2)
printf("\nChoice is 2");
else if (x == 3)
printf("\nChoice is 3");
else
printf("\nInvalid Choice ");
}
Output:
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY Enter Choice (1 - 3) : 1
Choice is 1
If the first condition (x ==1) is true then, the following printf() will be executed
and the control will come out of the block. If the first condition is not true, the if
corresponding to the first else will be checked. In case this if condition is satisfied, the
printf() corresponding to this if will be executed and the block will be exited; otherwise
the else following this if will be executed.
Page 27
Unix, C & C++
switch (expression)
{
case constant1:
statement sequence
break;
case constant 2:
statement sequence
break;
case constant 3:
statement sequence
break;
default:
statement sequence }
where switch, case, break and default are the keywords and statement sequence can be
simple statement or a compound statement which need not be enclosed in parentheses.
The expression following switch must be enclosed in parentheses and the body of the
switch must be enclosed within the curly braces. The datatype of the expression given
and the datatype of the case constants given should be compatible. As suggested by the
name, case labels can be only integer or character constant or constant expressions,
which do not contain any variable names. ‘Case’ labels must all be different.
In the switch statement, the expression is evaluated and the value is compared
with the case labels in the given order. If a label matches with the value of the
expression, the statement mentioned will be executed. The break statement ensures
immediate exit from the switch statement. If a break is not used in a certain case, the
statements in the following case are also executed irrespective of whether that case value
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
is satisfied or not. This execution will continue till a break is encountered. Therefore,
break is said to be one of the most important statement while using a switch.
The statements against default will be executed, if none of the other cases are
satisfied. The default statement is optional. If it is not present and the value of the
expression does not match with any of the cases, then no action will be taken. The order
of the case labels and default is immaterial.
/* switch Statement */
#include<stdio.h>
#include<conio.h>
Page 28
Unix, C & C++
main()
{
char ch;
clrscr ();
printf("\n Enter a lower case alphabet (a-z): ");
scanf("%c", &ch);
if (ch < 'a' || ch >'z')
printf("\nCharacter not a lower case alphabet");
else
switch(ch)
{
case 'a':
case 'e':
case 'i' :
case 'o':
case 'u':
printf("\nCharacter is a vowel");
break;
case 'z' :
printf("\nLast Alphabet (z) was input");
break;
default:
printf("\nCharacter is a consonant");
break;
}
}
Output:
Enter a lower case alphabet (a – z): g
Character is a consonant
The program will take a lower case alphabet as an input and display whether it is
a vowel, the last alphabet or a consonant.
Loops
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Loops follow the iteration concept. Loops allow a set of instructions to be
performed until a certain condition becomes false. This condition may be predefined or
open ended. The loop structures available in ‘C’ are:
The for loop
The while loop
The do...while loop
a. for loop
It is an entry-controlled loop that provides a more concise loop control structure.
Page 29
Unix, C & C++
Initialization of the control variables is done by using the assignment statement such
as i= 1 and count =0. The variable i and count are known as loop-control variables.
The value of the control variable is tested using the test-condition. The test condition
is a relational expression, such as i < 10 that determines when the loop will exit. If the
condition is true, the body of the loop is executed; otherwise, the loop is terminated
and the execution continues with the statement that immediately follows the loop.
When the body of the loop is executed, the control is transferred back to the for
statement after evaluating the last statement in the loop. Now, the control variable is
incremented using an assignment statement such as i = i + 1 and the new value of the
control variable is again tested to see whether it satisfies the loop condition. If the
condition is satisfied, the body of the loop is again executed. This process continues
till the value of the control variable fails to satisfy the test-condition.
This for loop is executed 10 times and prints the digits 0 to 9 in one line.
Semicolons must separate the three sections enclosed within parentheses. Note that there
is no semicolon at the end of the increment section, x = x +1.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
#include <stdio.h>
main()
{
int num;
for(num =1 ; num <=10; num ++)
printf("%d", num);
}
Output:
12345678910
Page 30
Unix, C & C++
The while statement is used to carry out looping operations, in which a group of
statements is executed repeatedly, until some condition has been satisfied.
The general form of while statement is
while (expression )
{
statement
}
The statement will be executed repeatedly, as long as the expression is true. This
statement can be simple or compound, though it is usually a compound statement. It must
include some feature that eventually alters the value of the expression, thus providing a
stopping condition for the loop.
#include <stdio.h>
main() /* display the integers 0 through 9 */
{
int digit = 0;
Initially, digit is assigned a value 0. The while…loop then displays the current
value of digit, increase its value by 1 and then repeats the cycle, until the value of digit
exceeds 9. The net effect is that the body of the loop will be repeated 10 times, resulting
in 10 consecutive lines of output. Each line will contain a successive integer value,
beginning with 0 and ending with 9.
Page 31
Unix, C & C++
The do…while loop is sometimes referred to as do…loop in ‘C’. Unlike for and
while loops, this loop checks its condition at the end of the loop, that is, after the loop has
been executed. This means that do…while loop will execute at least once, even if the
condition is false initially. The general form of do…while is:
do {
statements;
} while (condition);
The curly brackets are not necessary when only one statement is present within
the loop, but it is a good habit to use them. do..while loop iterates until the condition
becomes false. In the do…while the statement (block of statements) is executed first, then
the condition is checked. If it is true, control is transferred to the do statement. When the
condition becomes false, control is transferred to the statement after the loop. Consider
the following:
ANNAMALAI
ANNAMALAI UNIVERSITY
Output:
Enter : 5 UNIVERSITY
No. is 5
Enter : 3
No. is 3
Enter : 0
No. is 0
The total numbers entered were 2
The above program accepts integers and display them until zero(0) is entered. It will then,
exit the do…while and print the number of integers entered.
Page 32
Unix, C & C++
Operators
C supports a rich set of operators. An operator is a symbol that tells the computer to
perform certain mathematical or logical manipulation. Operators are used in programs to
manipulate data and variables.
Control Statements
C language possesses such decision making capabilities and supports the following
statements known as control or decision making statements.
2.5 Summary
A variable is an entity that has value and is known to the program by a name.
In C, a variable must be declared before it can be used. Variables can be declared
at the start of any block of code, but most are found at the start of each function.
Most local variables are created when the function is called, and are destroyed on
return from that function.
Every variable has a name and a value. The name identifies the variable, the value
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
stores data. There is a limitation on what these names can be. Every variable name
in C must start with a letter; the rest of the name can consist of letters, numbers
and underscore characters.
Local variables are declared within the body of a function, and can only be used
within that function.
Alternatively, a variable can be declared globally so it is available to all functions.
Modern programming practice recommends against the excessive use of global
variables.
Page 33
Unix, C & C++
A global variable declaration looks normal, but is located outside any of the
program's functions. This is usually done at the beginning of the program file, but
after preprocessor directives.
An operator is a function which is applied to values to give a result. You should
be familiar with operators such as +, -, /.
Other operators are used for comparison of values, combination of logical states,
and manipulation of individual binary digits.
Operators and values are combined to form expressions. The values produced by
these expressions can be stored in variables, or used as a part of even larger
expressions.
A program consists of a number of statements which are usually executed in
sequence. Programs can be much more powerful if we can control the order in
which statements are run.
1. What are the various compilers available for C and the operating systems
they run on?
2. The maximum length of a variable in C is _______________.
3. Character constants should be enclosed between _______________.
4. The operator && is an example for ___ operator.
5. The associativity of ! Operator is _______________.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
1. Byron Gottfried, “Programming with C”, Second Edition, TMH, 1998.
2. Deitel & Deitel, “C How to program”, Pearson Education Ltd, 2001.
2.8 Assignments
1. Write a program to generate the first fifteen terms of the Fibonacci series and
print their sum and average.
Page 34
Unix, C & C++
2. Write a program to find second largest and second smallest element from the
set of elements.
2.11 Keywords
Stdio.h printf
Scanf main
if else-if
break continue
int c preprocessor.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Page 35
Unix, C & C++
UNIT – III
Snapshot
Introduction to Structure
Declaration of Structure
Array of Structure
Pointers & Structure
Unions
Introduction to Disk I/O
Text mode unformatted I/O functions
Line Input and Output
Text mode formatted I/O functions
Binary mode I/O functions
3.0 Introduction
This chapter is concerned with the use of structures within a C program. How
structures are defined, and how their individual members are accessed and processed
within a program. The relationship s between structures and pointers, arrays and
functions will also be examined. Closely associated with the structure us the union, which
also contains multiple members. Unlike a structure, however, the members of a union
share the same storage area, even though the individual members may differ in type. In
addition, this chapter is concerned with only with stream oriented data files.
3.1 Objective
The objective of this chapter makes the learner aware of the fundamentals
structures and Disk I/O functions. The fundamental concepts include structure, array of
structure, nested structure, pointers and structure and unions. Towards end of this chapter
the student can get the basic knowledge about structures and Disk I/O functions.
3.2 Content
ANNAMALAI
ANNAMALAI UNIVERSITY
3.2.1 Structure
UNIVERSITY
The main use of structure is to lump together collections of disparate variable
types, so that they can conveniently be treated as a unit. For example, while writing a
compiler or assembler, one might need for each identifier information like its name (a
character array), its source line number (an integer), some type information (a character,
perhaps) and probably a usage count (another integer).
char id[10];
int line;
char type;
int usage;
Page 36
Unix, C & C++
In this case, the structure is first defined, that is, what kinds of things it contains;
after that one can actually reserve storage for it, either in the same statement or
separately. The simplest thing is to define it and allocate storage all at once.
struct {
char id[10];
int line;
char type;
int usage;
} sym;
This defines sym to be a structure with the specified shape; id, line, type and usage are
the members of the structure.
};
Once, the new structure data type has been defined one or more variable can be
declared of that structure type. Consider a structure declared as follows:
struct student {
char name[10];
int rollno;
char sex; /* m or f */
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
};
int age;
This defines a new data type called student to be a structure with the specified
shape; name, rollno, sex and age. A variable of type struct student can be declared as
follows :
struct student collegestu, schoolstu;
This statement allocates space in memory and makes available space to hold
structure elements. A structure can be declared in any of the format given below.
Page 37
Unix, C & C++
Format one:
struct student {
char name[10];
int rollno;
char sex;
int age;
};
struct student collegestu,schoolstu;
Format two:
struct
{
char name[10];
int rollno;
char sex; /* m or f */
int age;
} collegestu, schoolstu;
Structure variable uses dot (.) operator to access structure element. Syntax to
access the structure elements is
structure_name . structure_element_name
collegestu.rollno = 1125;
collegestu.age = 21;
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The following program illustrates how structure members can be accessed.
#include<stdio.h>
struct stud
{
int rno;
char name[20];
};
main()
{
Page 38
Unix, C & C++
struct stud s;
printf(“Enter the student’s name:”);
scanf(“%s”,s.name);
printf(“Enter the student’s roll number:”);
scanf(“%d”,&s.rno);
printf(“The student’s details are:\n”);
printf(“Name : %s\n”,s.name);
printf(“Roll No. : %d\n”,s.rno);
}
Output:
Enter the student's name:Adithya
Enter the student's roll number:100
The student's details are:
Name : Adithya
Roll No. : 100
The above program accesses the members of the structure by declaring a structure
variable and accessing each member using a dot operator. In the above program, the
structure members name and rno are accessed using the structure variable s and dot
operator.
Just like an array of variable, an array of structure can also be declared. Suppose a
symbol table for 100 identifiers has to be made. The definitions can be extended like
char id[100][10];
int line[100];
char type[100];
int usage[100];
but a structure lets rearranging this spread-out information so that all the data identifier is
collected into one lump:
ANNAMALAI
ANNAMALAI UNIVERSITY
struct {
UNIVERSITY
char id[10];
int line;
char type;
int usage;
} sym[100];
This makes sym an array of structures; each array element has the specified
shape. Now, members can be referred to as
Page 39
Unix, C & C++
Thus, to print a list of all identifiers that have not been used, together with their
line number,
for( i=0; i<nsym; i++ )
if( sym[i].usage == 0 )
printf("%d\t%s\n", sym[i].line, sym[i].id);
#include<stdio.h>
#include<conio.h>
struct date
{
int dd;
int mm;
int yy;
};
struct stud
{
char name[20];
struct date d;
int m1,m2,m3;
float per;
};
main()
{
struct stud s;
printf("Enter the Details of student\n");
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
printf("\nName:");
scanf("%s",s.name);
printf("\nDate of Birth(dd mm yy):");
scanf("%d%d%d",&s.d.dd,&s.d.mm,&s.d.yy);
printf("\nMarks in 3 Subject:");
scanf("%d%d%d",&s.m1,&s.m2,&s.m3);
s.per=(s.m1+s.m2+s.m3)/3;
printf("\nStudent Result");
printf("\n%s has secured %f%%",s.name,s.per);
getch();
}
Page 40
Unix, C & C++
Output:
Enter the Details of student
Name:Ashwin
Marks in 3 Subject:98
97
95
Student Result
Ashwin has secured 96.000000%
Just like a variable of type structure, a pointer variable of type structure can
also be declared. The following program declares a pointer variable of type struct tag and
uses this pointer variable to access every member of the structure.
#include<stdio.h>
struct tag
{
char lname[20];
char fname[20];
}s; ANNAMALAI
ANNAMALAI UNIVERSITY
int age;
UNIVERSITY
main()
{
struct tag *t;
t=&s;
printf(“\nEnter the first name:”);
scanf(“%s”,t-> fname);
printf(“\nEnter the last name:”);
scanf(“%s”,t-> lname);
printf(“\nAge:”);
Page 41
Unix, C & C++
scanf(“%d”,&t->age);
printf(“\nThe details are:”);
printf(“Name:%s %s\nAge:%d”, t-> fname, t-> lname,t->age);
}
Output:
Age:60
3.2.2 Unions
Example
union int_or_long {
int i;
long l;
} a_number;
Unlike a struct, the variables a_number.i and a_number.l occupy the same
location in memory. Thus, writing into one will overwrite the other. Elements of a union
are accessed in the same manner as a struct.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
3.2.3 File Handling
Files are very useful in storing information for future analysis and retrieval. C
language defines a number of functions for handling files.
When a file has to be used either for writing to it or for reading from it, it has to
be opened in corresponding mode. The function fopen()is used for opening a file; certain
systems may also provide specialized ways of opening streams connected to I/O devices
in a more exotic ways.
Page 42
Unix, C & C++
a. fopen()
A successful call to fopen returns a pointer of type FILE *, that is, “pointer to
FILE”, where FILE is a special type defined by <stdio.h>. A FILE * (also called “file
pointer”) is handled by which an I/O stream in C is referred. I/O functions which do not
assume standard input or standard output accept a FILE * argument telling them which
stream to read from or write to. The prototype of fopen is as follows:
Here,
The first string is the file name, which can be any string (simple filename
or complicated pathname) which is acceptable to the underlying operating system.
The second string is the mode in which the file should be opened. The
simple mode arguments are
When a file has to be used for both reading and writing, the operator ‘+’ can be
used. Thus modes “r+” and “w+” lets reading and writing to the file. However, both
cannot be done at the same time; To read or write the read/write indicator must be
explicitly repositioned.
A normal program in C using files often uses most of the statements used in the
sample program given below :
#include <stdio.h>
main()
{
FILE *fptr;
fptr = fopen(“sample.dat”,”r+”);
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
if (fptr == NULL)
printf(“Cannot open the file”);
else
printf(“File opened successfully”);
fclose(fptr);
}
Page 43
Unix, C & C++
Output:
God helps those who help themselves
The above program would continue to read characters from the file and prints
them on the screen till the EOF (End of File) is reached.
Page 44
Unix, C & C++
The function gets() and puts() offer a simple alternative to the use of scanf() and
printf() for reading and displaying strings. In the case of gets(), the string will be entered
from the keyboard and will terminate with a newline character.
char* gets(char *line)
reads the next line of text from the standard input and places the characters in the
character array pointed to by line. It returns a pointer to the line, unless it reaches end-of-
file, in which case it returns a null pointer.
The function
writes the string pointed to by line to the standard output and writes a ‘\n’ to terminate it.
It returns a nonnegative value unless there is some kind of a write error, in which case it
returns EOF.
#include<stdio.h>
main()
{
char line[80];
gets(line);
puts(line);
}
Output:
How are you?
How are you?
The function
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
int fputs(char *line, FILE *fp)
writes the string pointed to by line to the stream fp. Like puts, fputs returns a nonnegative
value or EOF on error. Unlike puts, fputs does not automatically append a \n. Here is a
program which demonstrates the use of fputs().
#include<stdio.h>
#include<conio.h>
main()
Page 45
Unix, C & C++
{
FILE *a;
char b[21]="This is a test";
a=fopen("t.t","w+");
fputs(b,a);
getch();
}
Output:
The program has no output. It writes the text to the file
The function
reads the next line of input from the stream ‘fp’ and places the characters, including the
‘\n’, in the character array pointed to by line. The second argument, max, gives the
maximum number of characters to be written to the array and is usually the size of the
array. Like gets, fgets returns a pointer to the line it reads or a null pointer if it reaches
end-of-file. Unlike gets, fgets does include the ‘\n’ in the string and it copies to the array.
Therefore, the number of characters in the line, plus the \n, plus the \0, will always be less
than or equal to max.
In the following program, the file “t.t” contains 17 characters. The function fgets
accepts a number which is 1 more than the number of characters to be read.That is why it
accepts18 since it has to be more.
#include<stdio.h>
#include<conio.h>
main()
{
FILE *a;
char c[21];
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY a=fopen("t.t","r+");
fgets(c,18,a);
printf("The text from file is :\n %s",c);
}
Output:
The text from file is:
This is a test
Page 46
Unix, C & C++
#include<stdio.h>
FILE *fptr;
void main()
{
fptr = fopen(“temp.txt”, “w+”);
fprintf(fptr,”Hello world\n”);
fprintf(fptr,”This line contains numbers : %d\n”,20);
fprintf(fptr,“%d”,30);
}
Executing the above program result in a file called temp.txt containing the following text
Hello world
This line contains numbers: 20
30
#include<stdio.h>
FILE *fptr;
void main()
{
int x;
char ch[80];
fptr = fopen(“temp.txt”, “r”);
fscanf(fptr,”%s”,ch);
printf(“%s”, ch);
fscanf(fptr,”%s”,ch);
printf(“%s”, ch);
}
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Output:
Helloworld
When the above program is executed, it reads the data from the file called
temp.txt and displays the content of the file.
“Binary” or “b” mode means that no translations are done by the stdio library
when reading or writing the file. Normally, the newline character “\n” is translated to and
from some operating system dependent end-of-line representation (LF on Unix, CR on
Page 47
Unix, C & C++
Structure
A structure is a collection of variables under a single name. These variables can be of
different types, and each has a name which is used to select it from the structure. A
structure is a convenient way of grouping several pieces of related information together.
Union
A union is a memory location that is shared by two or more different types of variables.
A union provides a way of interpreting the same bit pattern in two or more different
ways. Declaring the union is similar to declaring the structure.
File Pointer
A file pointer is pointer to a structure of type FILE. It points to information that defines
various things about the file, including its name, status, and the current position of the
file.
3.5 Summary
A pointer in C refers to a variable that holds the address of another variable.
Page 48
Unix, C & C++
Files are very useful in storing information for future analysis and retrieval. C
language defines a number of functions for handling files.
3.8 Assignments
1. Summarizes the rules that apply to processing unions. Compare with the rules
apply to processing structures.
2. Describe two different approaches to updating a data file. Which approach is
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
better, and why?
3.9 Suggested Reading/Reference Books/Set Books
Page 49
Unix, C & C++
1. Collect information on Structures and union (not covered in this chapter) from
the internet.
2. Collect information on Disk I/O functions.
3.11 Keywords
Structure Struct
Union fopen
fclose fputs
fgets fprintf
fscanf MS-DOS
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Page 50
Unix, C & C++
UNIT - IV
Snapshot
Introduction to Object Oriented Programming
Features of OOPs
Basic Concepts of OOPs
Principles of OOPs
Applications of OOPs
Introduction to C++
Problems in software Development
Variables, Constants and data types
Keywords
Introduction to input and output
Simple C++ Program
Compiling and Executing a program
Operators
Introduction to Control Structures
Loops
The break and continue Statements
The goto statement
Defining Classes and Objects
Function & its Types
Function Overloading
Constructors
Destructors
Friend Function
Operator Overloading
Type Conversion
4.0 Introduction
A conventional programming language such as ‘C’ is known as procedure-
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
oriented programming. In the procedure-oriented approach, the problem is viewed as a
sequence of things to be done, such as reading, calculating and printing. A number of
functions are written to accomplish these tasks. The primary focus is on functions. In a
multi-function program, many important data items are placed as global so that they may
be accessed by all the functions. Each function may have its own local data. Global data
are more vulnerable to an inadvertent change by a function. In a large program it is very
difficult to identify what data is used by which function. Another serious drawback with
the procedural approach is that it does not model real world problems very well.
Page 51
Unix, C & C++
Until recently, programs were thought of as a series of procedures that acted upon
a set of data. A procedure or function is a set of specific instructions executed one after
the other. The data was quite separate from the procedures and the trick in programming
was to keep track of which functions calling other functions and what was the data that
was changed. To make sense of this potentially confusing situation, structured
programming was created. The principle idea behind structured programming is simple:
divide and conquer. A computer program can be thought of as consisting of a set of tasks.
Any task that is too complex would be broken down into a set of smaller component
tasks, until the tasks were sufficiently small and self-contained enough that they were
easily understood.
For example, consider a complex task of computing the average salary of every
employee of a company. It can be broken down into subtasks such as, finding out what
each person earns, counting the number of people, summing up all the salaries and
dividing the total by the number of people. The total of all the salaries can also be broken
down into subtasks such as, getting each employee’s record, accessing the salary, adding
the salary to the running total and getting the next employee’s record. Obtaining each
employee’s record can in turn be broken down as opening the file of employees, going to
the correct record and reading the data from disk.
Page 52
Unix, C & C++
4.1 Objective
The objective of this lesson is to understand the fundamentals of Object Oriented
Programming, which include a wide range of topics from fundamentals of Object
Oriented Programming and Features of OOPs to type conversion. The fundamental
concepts include defining classes and objects, Array of objects, function and its types,
function overloading and operator overloading. At the end of the lesson you learn about
constructors, destructors, copy constructor and friend function.
4.2 Content
Objects
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
When one approaches a programming problem in an object-oriented language,
one no longer ask how the problem will be divided into functions, but how it will be
divided into objects. Thinking in terms of objects, rather than functions, has a
surprisingly helpful effect on how easily programs can be designed. This results from the
close match between objects in programming sense and objects in the real world.
Page 53
Unix, C & C++
Object may represent a person, a place, a bank account, a table of data or any item
that the program must handle. When a program is executed, the objects interact by
sending messages to one another.
Classes
Classes use the concept of abstraction and are defined as a list of abstract
attributes such as size, weight, cost and functions to operate on these attributes. They
encapsulate all the essential properties of the objects that are to be created. Since the
classes use the concept of data abstractions, they are known as Abstract Data Types
(ADT).
Inheritance
Inheritance is the process by which objects of one class acquire the properties of
another class. The principle behind this sort of division is that each subclass shares
common characteristics with the class from which it was derived. In a similar way an
OOP class can be divided into subclasses. In C++ the original class is called the base
class. Other classes can be derived that has the characteristics of the base class along with
additional features. These are called derived classes.
Polymorphism
Polymorphism means the ability to take more than one form. For example, an
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
operation may exhibit different behavior in different instances. The behavior depends
upon the types of data used in the operation. Polymorphism plays an important role in
allowing objects having different internal structures to share the same external interface.
This means that a general class of operations may be accessed in the same manner even
though a specific action associated with each operation may differ. Polymorphism is
extensively used in implementing inheritance.
Dynamic Binding
Dynamic binding means that the code associated with a given procedure call is
not known until run-time. It is associated with polymorphism and inheritance.
Page 54
Unix, C & C++
Message Communication
An object-oriented program consists of a set of objects that communicate with
each other. The process of programming in an object-oriented language involves the
following basic steps:
Creating classes that define objects and their behavior.
Creating objects from class definitions.
Establishing communication among objects.
Objects communicate with one another by sending and receiving information in
the same way as people pass message to one another. The concept of message passing
makes it easier to talk about building systems that directly model or simulate their real-
world counterparts.
Inheritance is used to eliminate redundant code and extend the use of existing
classes.
The user can build programs from the standard working modules that
communicate with one another, rather than having to start writing the code from
first.
The Principle of data hiding helps the programmer to build secure programs that
cannot be invaded by code in other part of the program.
It is possible to have multiple instances of an object to co-exist without any
interface.
It is possible to map objects in the problem domain to these objects in the
ANNAMALAI
ANNAMALAI UNIVERSITY
program. UNIVERSITY
Based on the objects, it is easy to partition the work.
The data-centered design approach enables the user to capture more details of a
model in implementable form.
Object-oriented systems can be easily upgraded from small to large systems.
Software complexity can be easily managed.
Page 55
Unix, C & C++
software engineers to continuously look for new approaches to software design and
development, which is becoming more and more critical in view of the increasing
complexity of software systems as well as the highly competitive nature of the industry.
These things have created a serious crisis within the industry. The following issues need
to be resolved to overcome this crises:
Real-business systems are often much more complex and contain many more
objects with complicated attributes and methods. OOP is useful in this type of
applications because it can simplify a complex problem. The object-oriented paradigm
sprang from the language, has matured into design and has enabled software industry to
improve not only the quality of software systems but also its productivity.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The three most important facilities that C++ adds on to C are Classes, Function
Overloading and Operator Overloading. These features enable to create abstract data
types, inherit properties from existing data types and support polymorphism, thus making
C++ a truly object-oriented language.
Page 56
Unix, C & C++
Variables
Variables are storage units for values. They refer to a memory location where the
value will be stored. There are different types of variables. Depending on the type of
variable, the value stored in it will vary. This means that if a numeric value is to be
stored, only a numeric variable is to be used. In other words, a numeric variable can hold
only a number.
Naming a variable
Whenever a value stored in a variable is to be used, the name of the variable
should be mentioned. A variable name should confirm to certain rules.
The name of the variable should always start with an alphabet.
The characters other than the first character can be either number or alphabet.
Punctuation characters and spaces are not permitted.
A keyword (explained later) cannot be used as a name of the variable.
The name is case sensitive. This means that the upper case and lower case of the
same alphabet are different. Thus two variables can be defined having names as
“a” and “A” respectively.
Constants
A constant unlike variable cannot be assigned a new value once assigned. A
constant is assigned a value during declaration. The keyword const is used to create a
constant.
Example
const int a =5;
In this case ‘a’ is a constant. Notice the use of the keyword const. Also note that a
value 5 is assigned to the variable ‘a’. So ‘a’ will retain this value through out the
program and it can never be changed. If an attempt is made to change the value it will
result in error.
Data types
Every variable has a data type which decides the type of value, a variable can
hold. The data type of a variable is to be specified when the variable is first created. The
data type decides the type of the content a variable (and hence a memory location) can
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
hold and lays down certain rules about what kind of operation a variable can do . C++
supports seven basic data types as listed below.
Page 57
Unix, C & C++
Variable Declaration
Applying a name and a type to a variable is called variable declaration. A
declaration has the following form:
type list of variables
where, type refers to the data type of a variable.
list of variables refer to the variable names of that particular data type.
The variables in a list are separated by a comma. Each variable in a list is declared
to be of same type. Different types of variables are declared in different statements. A
variable should be declared at start of a program or atleast before it is used.
Example
int a;
In this case a variable called ‘a’ is declared to be of type int. This means that this variable
‘a’ can hold only whole numbers.
int a,b;
In this case two variables called ‘a’ and ‘b’ are declared to be of type int. Note that the
two variables are separated by a ‘,’. Both the variables in this case can hold only whole
numbers
Suppose the variable ‘b’ has to hold a real number then the above variable
declaration statement can be modified as
int a;
float b;
In the above example, the variable ‘a’ is assigned a value of 5 while the value 6.5
is assigned to b. Note that the variable should come on the left hand side of the ‘=’ sign
while the value to be assigned should come on the right hand side of the ‘=’ sign. A
variable can also be assigned to another variable provided the variable that comes on the
right hand side has a value. This is illustrated in the example given below.
Page 58
Unix, C & C++
Example
int a,b;
a=3;
b=a;
Keywords
Keywords are special words that have a specific meaning in a computer language.
They are reserved words that inform the compiler about the important constructs in a
program. The keywords cannot be used as names for program variables. The table below
lists the keywords used in C++.
Keywords in C++
asm auto break case Catch char
class const continue default Do double
else enum extern float For friend
goto if inline int Long new
operator private protected public Register return
short signed sizeof static Struct switch
template this throw try Typedef union
unsigned virtual void volatile While
cout statement
In C++, cout is used for output. Here is a statement that displays a line of text on
the screen.
cout<< “This text will appear on the screen.”;
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
In a cout statement, anything given within double quotes (“ ” symbol), will be
displayed as it is on the standard output device, the monitor. The operator << used
with cout is called the insertion operator.
When a value of a variable is to be displayed, then that variable name has to be
specified next to the insertion operator as shown in the example below:
Example
int a=5;
cout<<a;
Page 59
Unix, C & C++
The above example will display an output of 5, which is the value of the variable ‘a’,
on the screen.
endl
It is a keyword used along with cout statement to mark the end of a line. Once an
endl keyword is encountered, the contents that follow it will be displayed in the next line.
Example
cout<< “Hello”<<endl;
cout<< “World”;
The above statements will display Hello in the first line and World in the next line as
shown below:
Hello
World
Had endl not been used in the cout statement, both ‘Hello’ and ‘World’ would appear
in the same line.
cin statement
cin statement is used for input. A variable can be assigned a value directly using an
“=” sign as discussed earlier. If a variable has to be assigned a value when the
program is executed, cin statement is used. The general syntax of cin statement is:
cin>>list of variables
Example
int a,b;
ANNAMALAI
ANNAMALAI UNIVERSITY
cin>>a>>b;
UNIVERSITY
In this example, a and b are not assigned any initial value. When the program is
executed, the values for a and b are to be supplied by the user.
Any program will start its execution from the main() function. A function refers to
a set of statements grouped logically to perform certain task. The main() function consists
of a set of statements, which will be executed one after another. The statements that
constitute the main function are enclosed within curly braces ( { } ).
Page 60
Unix, C & C++
Consider a program for adding two numbers and displaying the result.
int a, b, c;
The above statement declares three variables a,b and c, all of type int. All statements
in C++ should end with a semicolon and hence the above statement also ends with a
semicolon.
Now, the two numbers have to be accepted before proceeding on to anything else.
These steps can be implemented using statements like:
a=5;
b=6;
Both these statements assign a value to the variable a and b. These are the values
whose sum has to be found out. Note in this case, the values are not accepted from the
user but a known value is directly assigned to each of the two variables using an “=”
symbol.
According to steps 3 and 4 in algorithm, the two variables should be added up and
the result has to be stored. Both these steps can be represented using a single statement as
follows in C++.
c=a+b;
The statement above first adds the values of a and b and then assigns the value to
c.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The last and the most important step is to get the answer. This can be achieved
using a cout<< as follows:
The above statement first displays the string enclosed in double quotes and then
prints the value stored in the variable c. With these steps the statements required for
writing a C++ program is complete. One important thing to be noted while writing a C++
program is that all the statements have to be enclosed within the function main() between
the two braces.
Page 61
Unix, C & C++
Thus, a complete C++ program will look like the one shown below:
#include<iostream.h>
main()
{
int a,b,c;
a=5;
b=6;
c=a+b;
cout<< “The sum is :”<<c;
}
Output:
The sum is : 11
The above program will always display the output as 11. If a different set of numbers
are to be added, it will be a better option to supply the values during run time. The
above program can be modified as follows:
#include<iostream.h>
main()
{
int a,b,c;
cout<< “Enter 2 numbers:”<<endl;
cin>>a>>b;
c=a+b;
cout<< “The sum is:”<<c;
}
Input:
Enter 2 numbers:
2
3
ANNAMALAI
ANNAMALAI UNIVERSITY
Output: UNIVERSITY
The sum is: 5
The second version of the program would be a better option if a sum of various
sets of numbers is to be computed.
Preprocessor directive
Page 62
Unix, C & C++
contents of the iostream.h file to the program. The file iostream.h is called header file.
Depending on the type of function to be performed, an appropriate header file has to be
included. There are different header files. If a mathematical function like sin() or cos()
has to be used, the header file math.h has to be included. The header file iostream.h has
to be included whenever cin and cout have to be used in the program.
#include<iostream.h>
#include<math.h>
main()
{
int a,b,c;
a=2;
b=3;
c=pow(a,b);
cout<< “Answer: ” <<c;
}
Output:
Answer: 8
In the above program a new function pow() has been used. This is for finding the
power of a number. This means that a statement pow(a,b) gives the value of ab . The
program hence displays the result as 8 as 23 =8. The function pow() is actually defined in
a header file called math.h. The program, therefore includes the header file <math.h>. If
this statement is omitted, the program cannot recognize the function pow() and will
display an error message.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
C++ Source file
COMPILER
Object file
Executable file
Page 63
Unix, C & C++
Comments
A comment is just some text enclosed in a pair of comment delimiters. The text
between the comment delimiters can be anything; whatever falls between the delimiters is
simply ignored by the compiler. The comments are used for conveying information about
what the code does in plain English. There are two of comments- multi line comment and
line end comment. Multi-line comments are used when the comment runs to more than 1
line. In such case the comment text is enclosed between /* and */.
Line end comment is one that begins somewhere within a line of C++ code and
then terminates at the end of the line. The line end comment delimiter is a double forward
slash, //. Here’s an example:
a=5; // a takes the value of 5
There is only one line-end comment delimiter; it doesnot enclose the text.
The following program uses comments in the program for the sake of clarity.
#include<iostream.h>
main()
{
int x,y,z; //Declaring 3 variables as integer
cout<< “Enter value for x and y numbers :”<<endl;
cin>>x>>y; //accepts value for x and y
z=x*y; // computes the product of x and y and stores in z
cout<< “The product is:”<<z; // this statement displays the output of z.
}
Output:
Enter value for x and y numbers:
5 6
The product is: 30
The above program uses comments along with most of the statements in the program.
This makes the program comprehensible for even people who do not know programming.
4.2.4 Operators & Manipulators
Data is manipulated by symbols called operators in the C++ programming
language. Much like the common math set of operators; C++ has its own operators for
the manipulation of data. Operators are commonly used in mathematical calculations and
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
in allocating or addressing a variable. They can also be used for logical comparison.
Operators can be classified into a number of categories. They are:
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Conditional Operator (Ternary operator)
Bitwise operators
Increment and decrement operators.
Page 64
Unix, C & C++
Besides the above classification, operators can be classified into two groups:
unary and binary. A unary operator works on one value also called an operand. An
example of a unary operator is the negation operator. The negation operator is placed
before a variable, and it returns the opposite sign of the variable. So if a variable 'x'
containing a value of -5 is prefixed with the negation operator, the result would be 5. A
binary operator requires two values to work with. There are more binary operators than
unary operators. Examples of binary operators include + addition, - subtraction, *
multiplication, / division and % modulus.
Every operator has two important properties called precedence and associativity.
Both the properties affect how operands are attached to operators. Operators of higher
precedence will operate first on the operands regardless the way they appear in the
expression. For example multiplication has higher precedence over addition, so the
expression 2+3*4 will be evaluated as (2+(3* 4)) = (2+12)=14 and not as (2+3)*4 =
5*4 = 20.
In cases where operators have same precedence the order is determined by
associativity. The grouping occurs either from right to left or from left to right depending
on the operator. The table shown below clearly states the precedence and associativity.
Description Operator Associativity
Function expression () Left to Right
Array expression [] Left to Right
Structure operator -> Left to Right
(indirection)
Structure operator (dot) . Left to Right
Unary minus - Right to Left
Increment/decrement ++, -- Right to Left
One’s complement ~ Right to Left
Negation ! Right to Left
Address of & Right to Left
Value at address * Right to Left
Type cast (type) Right to Left
Size in bytes sizeof Right to Left
Multiplication * Left to Right
ANNAMALAI
ANNAMALAI UNIVERSITY
Division
Modulo
UNIVERSITY /
%
Left to Right
Left to Right
Addition + Left to Right
Subtraction - Left to Right
Left shift << Left to Right
Right Shift >> Left to Right
Less than < Left to Right
Less than or equal to <= Left to Right
Greater than > Left to Right
Page 65
Unix, C & C++
The modulo (%) operator is used to obtain the remainder when one integer is
divided by another. So,
a%b
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
returns the remainder obtained when a is divided by b. a and b can be only of integer data
type.
For Example,
5%3 gives 2.
Relational Operators
Often it is required to compare two quantities and depending on their relation,
take decisions. These comparisons can be done with the help of relational operators.
Page 66
Unix, C & C++
The value of a relational expression is either one or zero implying, the relation is true or
false respectively. For example,
Logical Operators
(i>0) && (c<2) will be false while (i>0) || (c<2) will be true.
Assignment Operators
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
This is equivalent to saying
Consider an example
X += 5;
Page 67
Unix, C & C++
X = X + 5;
These shorthand assignment operators help to make the statement look more
concise and easier to read, which is very desirable in programming. The following are the
commonly used assignment combo operators:
+= Addition assignment
-= subtraction assignment
*= multiplication assignment
/= division assignment
%= modulus assignment (remainder from division)
This operator works as follows: exp1 is evaluated first. If it is nonzero (true), then
the expression exp2 is evaluated and becomes the value of the expression. If exp1 is zero
(false), exp3 is evaluated and becomes the value of the expression. Note that only one of
the two expressions (either exp2 or exp3) is evaluated. Consider the example:
If (a>b)
x = a*10;
else
x = b/5;
Bitwise Operators
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
C++ has a distinction of supporting special operators known as bitwise operators
for manipulation of data at the bit level. These bits are used for testing the bits or shifting
them from right to left
Page 68
Unix, C & C++
op2
| op1 | op2 bitwise or
^ op1^op2 bitwise xor
~ ~op2 bitwise complement
The shift operators simply shift the bits of the left-hand operand over by the
number of positions indicated by the right-hand operand. The shift occurs in the direction
indicated by the operator itself. For example, the following statement, shifts the bits of
the integer 13 to the right by one position:
13 >> 1;
The binary representation of the number 13 is 1101. The result of the shift
operation is 1101 shifted to the right by one position--110 or 6 in decimal. Thus, the bit
farthest to the right is lost. A right shift of 1 bit is equivalent to, but more efficient than,
dividing the left-hand operand by 2. A left shift of 1 bit is equivalent to multiplying by 2.
The bitwise and (&) operation performs the "and" function on each parallel pair of
bits in each operand. The "and" function sets the resulting bit to 1 if both operands are 1.
The following table shows the result of AND operation done on one ‘bit’.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
evaluate to 0 because either one or both bits in the operands are 0.
1101
& 1100
------
1100
Page 69
Unix, C & C++
Exclusive or means that if the two operand bits are different the result is 1,
otherwise the result is 0. The following table shows the results of exclusive or
operation.
And finally, the complement operator inverts the value of each bit of the operand:
if the operand bit is 1 the result is 0 and if the operand bit is 0 the result is 1.
The increment and decrement operators are very useful operators and are not
commonly found in other languages. They are represented as
++ and --
The operator ++ adds 1 to the operand while -- subtracts 1 from its operand. Both
are unary operators and take the following form:
Page 70
Unix, C & C++
The flow of a program depends on the flexibility offered by the language, in terms
of the functionality and programming control features. C++ offers a number of control
structures for this purpose. Control structures help in changing the flow of execution of
the program. There are several elegant and simple structures for looping and conditional
branching. They are:
The if Statement
The if-else Statement
The switch case Statement
The if Statement
The if statements allows branching (decision making) depending upon the value
or state of variables or result of an expression. This allows statements to be executed or
skipped, depending upon decisions. The basic format is,
if( expression )
program statement;
Example
if (marks = = 100)
{
cout << "mark is ";
cout << marks;
}
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
In this case, two statements are to be executed if the expression in if statement is
true. Hence these statements form a block and are enclosed within curly braces.
#include <iostream.h>
main()
{
int number;
Page 71
Unix, C & C++
int valid ;
cout<<"Enter a number between 1 and 10: ";
cin>>number;
valid = 1;
if( number < 1 )
{
cout<<"Number is below 1”<<endl;
valid = 0;
}
if( number > 10 )
{
cout<<"Number is above 10”<<endl;
valid = 0;
}
if (valid==1) cout<<"The number is %d\n", number ;
}
Output:
Enter a number between 1 and 10 : -78
Number is below 1.
The if-else is also used to carry out a logical test and then take one of the two
possible actions, depending on whether the outcome is true or false. In this case it is
possible to specify what has to happen if the condition is not fulfilled by using the
keyword else. Its form used in conjunction with if.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
/* An example of the if-else statements nested in loops */
#include<iostream.h>
void main()
{
int data;
cout<<“Type a number between 1 and 10 :”;
cin>>data;
if (data >=1&&data<=10)
{
cout<<"Data is between 1 and 10";
Page 72
Unix, C & C++
}
else
{
cout<<"Data is not between 1 and 10";
} /* end of if –else statement */
}
Output:
Type a number between 1 and 10: 11
Data is not between 1 and 10
Consider the if statement in the above example. It starts with the keyword if
followed by an expression in parentheses. If the expression is evaluated and found to be
true, the single statement following the if is executed and if the expression is false, the
statement following if is skipped and the statement following else is executed. The single
statement can be replaced by a compound statement composed of several statements
bounded by braces. The expression "data>=1&&data<=10" is simply checking if the
value of data lies between 1 and 10.
The if-else structures can be concatenated with the intention of verifying a range
of values. The following example shows its use telling if the present value stored in x is
positive, negative or none of the previous, that is to say, equal to zero.
#include<iostream.h>
void main()
{
int x;
cout<<” Enter value for x :”<<endl;
cin>>x;
if (x > 0)
cout << "x is Positive";
else if (x < 0)
cout << "x is Negative";
else
cout << "x is Zero";
ANNAMALAI
ANNAMALAI UNIVERSITY
} UNIVERSITY
Output:
Page 73
Unix, C & C++
if-else occurs. The main objective of switch case statement is to check several possible
constant values for an expression. The general format for this is,
switch ( expression ) {
case value1:
program statement;
program statement;
......
break;
case value N:
program statement;
.......
break;
default:
.......
.......
break;
}
The keyword break must be included at the end of each case statement. The
default clause is optional and is executed if the cases are not met. The right brace at the
end signifies the end of the case selections.
Rules for switch statement
Values for case must be integer or character constants
The order of the case statements is unimportant
The default clause may occur first (convention places default last)
One cannot use expressions or ranges
#include <iostream.h>
main()
{
int menu, numb1, numb2, total;
cout<<"Enter two numbers: ";
cin>>numb1>>numb2 ;
cout<<"Enter the choice”<<endl;
cout<<"1=Addition"<<endl;
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
cout<<"2=Subtraction"<<endl;
cin>>menu ;
switch( menu )
{
case 1: total = numb1 + numb2;
break;
case 2: total = numb1 - numb2;
break;
default: cout<<"Invalid option selected";
}
if( menu == 1 )
Page 74
Unix, C & C++
The above program uses a switch statement to validate and select upon the user’s
input choice, simulating a simple menu of choices.
Notice the inclusion of the break instructions at the end of each block. This is
necessary because, if break is not included after the block of instructions pertaining to
case-1, the program would not jump to the end of the switch selective block (‘}’) and it
would follow executing the rest of blocks of instructions until the first appearance of the
break instruction or the end of the switch selective block.
Loops
Loops are used for executing certain set of statements repeatedly for certain
number of times or until certain condition is true. There are three types of loops namely
The while Loop
The do…while Loop
The for Loop
The while Loop
The while loop continues to execute all the statements enclosed in a while block
repeatedly as long as the expression in the while is true. When the condition becomes
false, the looping is discontinued. The general format of this is:
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
while (expression) statement
and its function is simply to repeat statement while expression is true.
If more than one statement has to be repeated, enclose them within braces.
Page 75
Unix, C & C++
The above program defines an integer variable named count within the body of
the program. The variable is set to zero and the program enters the while loop. As long as
the expression in the parenthesis is true, all statements within the braces will be
repeatedly executed.
In this case, since the variable count is incremented by one every time the
statements are executed, it will eventually reach 6. When the variable count becomes 6,
the statement will not be executed because count is not less than 6 and the loop will be
terminated.
First, if the variable count were initially set to any number greater than 5,
the statements within the loop would not be executed at all, so it is
possible to have a while loop that is never executed.
Secondly, if the variable were not incremented in the loop, then in this
case, the loop would never terminate and the program would never be
completed.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Finally, if there is only one statement to be executed within the loop, it
does not need delimiting braces but can stand-alone.
In the while loop the condition is checked first and if it is true the statements
within the braces are executed until the condition becomes false. Some times it may be
needed that the statements must be executed before the condition is checked. That’s
exactly what do-while loop does.
The general format is:
do statement while (condition);
Page 76
Unix, C & C++
Its functionality is exactly the same as the while loop except that condition in the
do-while is evaluated after the execution of statement instead of before, granting at least
one execution of statement even if the condition is never fulfilled.
This program is nearly identical to the last one except that the loop begins with
the keyword do, followed by a compound statement in braces, then the keyword while,
and finally an expression in parentheses. The statements in the braces are executed
repeatedly as long as the expression in parentheses is true. When the expression in
parentheses becomes false, execution is terminated and control passes to the statements
following this statement.
Several things must be pointed out regarding the do-while loop. Since the test is
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
done at the end of the loop, the statements in the braces will always be executed at least
once. Secondly, if the variables were not changed within the loop, the loop would never
terminate, and hence the program would never terminate.
The for loop is used to repeat statements while condition remains true, like the
while loop. But in addition, for provides places to specify an initialization instruction and
an increment instruction. So this loop is specially designed to perform a repetitive action
with a counter. The general format is:
Page 77
Unix, C & C++
Output:
The value of the index is: 0
The value of the index is: 1
The value of the index is: 2
The value of the index is: 3
The value of the index is: 4
The value of the index is: 5
The for loop consists of the keyword for, followed by a rather large expression in
parentheses. This expression consists of three fields separated by semi-colons. The first
field contains the expression "index = 0" and is an initializing field. Any expressions in
this field are executed prior to the first pass through the loop. There is essentially no limit
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
as to what can go here, but good programming practice would require it to be kept
simple.
The second field, in this case containing "index < 6", is the condition which is
tested at the beginning of each pass through the loop. It can be any expression which will
evaluate to a true or false.
The expression contained in the third field is executed each time but it is not
executed until after those statements in the main body of the loop are executed. This
field, like the first, can also be composed of several operations separated by commas.
The while loop can be used conveniently when the number of times the loop has
to execute is not known and the for loop is usually used in those cases while doing a
Page 78
Unix, C & C++
The break statement enables the program to leave a loop even if the condition for
its end is not fulfilled. It can be used to end an infinite loop or to force it to end before its
natural end.
The continue instruction causes the program to skip the rest of the loop in the
present iteration as if the end of the statement block would have been reached, causing it
to jump to the following iteration.
Page 79
Unix, C & C++
The goto statement allows making an absolute jump to another point in the
program. To use a goto statement, the reserved word goto should be followed by the
symbolic name, placed elsewhere in the program followed by a colon. Execution of a
goto statement followed by a symbolic name will make the program jump to that
particular position where that symbolic name is placed followed by a colon.
Jumping can be nearly anywhere within a function, but jump into a loop is not
permitted, although jumping out of a loop is allowed.
#include<iostream.h>
void main()
{
int i,j,k;
for(i=0;i<20;i++)
ANNAMALAI
ANNAMALAI UNIVERSITY
{ UNIVERSITY
for(j=0;j<20;j++)
{
for(k=0;k<20;k++)
{
Page 80
Unix, C & C++
Output:
I am out of the loop!
However the use of ‘goto’ is not a good programming style. Of course, at some
places it can come quite handy.
A class is like a template from which objects can be created. Now what is an
object? It is an abstract concept and one cannot exactly define an object. An object,
however can be described by its behavior, state and identity. Every object will have a
state, an unique behavior and an identity.
Class definition
The class definition consists of the keyword class, the name of the class, an
opening brace, a closing brace, and a semicolon:
The braces (sometimes called curly brackets) are delimiters. They enclose the
body of the class specification so that one (and the C++ compiler) can see where exactly
the class begin and end.
Example
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
class class_name {
private:
variable declarations;
variable declarations;
public:
variable declarations;
function declarations;
};
The
Page 81
Unix, C & C++
keyword class specifies an abstract data of type class_name. The body of a class is
enclosed within braces and terminated by a semicolon. The class body contains the
declarations of variable and functions. These functions and variables are collectively
called members. They are usually declared under two sections namely, private and
public to denote which of the members are private and which of them are public.
The members that have been declared as private can be accessed only from
within the class. On the other hand, public members can be accessed from outside the
class also. The data hiding (using private declaration) is the key of object-oriented
programming. The use of the private keyword is optional. By default, the members are
private.
The variables declared inside the class are known as data members and the
functions are known as member functions. Only the member functions can have access
to the private data members and private functions.However, the public members(both
functions and data) can be accessed from outside the class. The binding of the data and
function together into a single class-type variable is referred to as encapsulation
Class members
A class is made up of variables and functions. These are called the members of
the class.The variables of the class provide the state to the object while functions of a
class provide the behavior to the given class.
Member functions
The member functions have a very important role to play as they define how an
object will behave. Typically a program calls an object’s member function to tell the
object to do something. This is why calling an object’s member function is also called
sending a message to the object.
Functions are expressions that execute an operation, allowing a programmer to
create several pieces of code and bunch them together to perform a particular task.
Functions accept information in the form of arguments and evaluate the arguments to
provide the result.
Example
int print( int x, int y)
{
int z=x+y;
return z;
ANNAMALAI
ANNAMALAI UNIVERSITY
}
UNIVERSITY
Objects
In C++, an object is a region of storage with associated semantics. The declaration
int i, specifies that i is an object of type int. In the context of the object model of C++, the
term object refers to an instance of a class. Thus a class defines the behavior of possibly
many objects (instances). Objects are usually referred to by references, which are aliases
for an object.
A C++ class definition generates a user-defined type. A class defines the
characteristics of its instances in terms of members- data members (state) and member
Page 82
Unix, C & C++
functions (methods or operations) and the visibility of these members to other classes.
The class defines the form of all objects that belong to that class. Each object of the class
that is created gets a copy of all the class data members, except for those declared as
static. All objects of a particular class share the member functions for that class.
Access Specifiers
The access specifier specifies the accessibility of the class members. It decides the
scope of the members of the class, thereby allowing certain members to be accessed only
inside the class while certain members of the class are allowed to be accessed from
outside the class also. There are different types of access specifiers namely: private,
public and protected.
Private: Members are accessible only to members of that class.
Protected: Members are accessible from members of its derived classes and from
members of the same class.
Public: Members are accessible from anywhere where the class is visible.
The access specifier is optional. A class can also be defined without using any
access specifier. In such case, the members of the class are not accessible outside the
class. This means that the members of the class become private. The scope of any
member of a class can be changed by using the corresponding access specifier before it.
This will change the scope of all the members following it. If the scope of one of them
has to be changed once again the required access specifier is used before it.
Example
#include<iostream.h>
class Sample
{
public:
void show()
{
cout<< “ Simple Function “;
}
};
main()
{ ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Sample ss;
ss. show();
}
Output:
Simple Function
Array of Objects
One can declare arrays of variables that are of the type class. Such variables are
called arrays of objects. Consider the following class definition:
Page 83
Unix, C & C++
class employee
{
char name[30];
int age;
public:
void getdata(void);
void putdata(void);
};
The identifier employee is a user-defined data type and can be used to create
objects that relate to different categories of the employees.
Example
employee manager [3]; // array of manager
employee foreman [5]; // array of foreman
employee worker [75]; // array of worker
Since an array of objects behaves like any other array, one can use the usual
array-accessing methods to access individual elements and then the dot member operator
to access the member functions. For example, the statement
manager[i].putdata();
will display the data of the i th element of the array manager. That is, this statement
request the object manager[i] to invoke the member function putdata().
Example
#include<iostream.h>
class employee
{
private:
char name[30]; // a class member
int age;
public:
ANNAMALAI
ANNAMALAI UNIVERSITY
};
UNIVERSITY
void getdata(void);
void putdata(void);
Page 84
Unix, C & C++
{
cout << “Name:” << name;
cout << “\n Age:” << age;
cout << “\n \n”;
}
main()
{
int i;
The coding for the function can be written in two different ways. One way is
within the class and another way is outside the class. Since the function is defined outside
the class, scope resolution operator (indicated by :: ) along with the class name is used.
The scope resolution operator binds the name of the function along with the class to
which it belongs; as otherwise the compiler would not know to which class that member
function belongs. The class definition should finally end with a semi-colon. The above
program begins an interactive program, the input data and the program output array is
shown below:
Interactive input:
Details of manager1
Enter name:aaa
ANNAMALAI
ANNAMALAI UNIVERSITY
Enter age:50
UNIVERSITY
Details of manager2
Enter name:ccc
Enter age:40
Details of manager3
Enter name:ddd
Enter age:45
Output:
Manager1
Page 85
Unix, C & C++
Name :aaa
Age :50
Manager2
Name :bbb
Age :40
Manager3
Name :ddd
Age :45
Like any other data type, an object may be used as a function argument. This can
be done in two ways:
A copy of the entire object is passed to the function
Only the address of the object is transferred to the function.
The first method is called pass-by-value. Since a copy of the object is passed to
the function, any change made to the object inside the function does not affect the
original object passed as argument to that function. The second method is called pass-
by-reference. When an address of the object is passed, the called function works directly
on the actual object passed as argument in the call. This means that any changes made to
the object inside the function will reflect in the actual object passed to that function. The
pass-by reference method is more efficient since it requires passing only the address of
the object and not the entire object. Objects can be used as a function argument in two
ways:
A copy of the entire object is passed to the function (pass-by-value)
Example:
Implemented in Operator Overloading
inline Function
Page 86
Unix, C & C++
Constant Function
Static Function
inline Function
Functions defined within the class are called inline functions. When a function is
inline, the compiler will replace the function call with a copy of the function body instead
of calling the function every time it is invoked. However all functions that is inline may
not be considered inline function by the compiler. It is always a good practice to inline
only those functions that has one or two statements.
The following example show a class in which the functions are defined inside the
class itself and these functions constitute the inline functions.
#include<iostream.h>
class Circle
{
int r;
public:
void input()
{
cout<< “Enter the value of the radius: ”;
cin>>r;
}
void area()
{
cout<< “Area=”<<3.14*r*r;
}
};
main()
{
Circle c;
c.input();
c.area();
}
ANNAMALAI
ANNAMALAI UNIVERSITY
Output:
UNIVERSITY
Enter the value of the radius: 5
Area=78.5
In this program, an object of class Circle is created in the main(). The class Circle
has two functions input() and area(), both defined inside the class. This means that both
the functions have been declared inline (i.e., inside the class).
Advantages
It requires fewer keystrokes to inline a function.
It is possible to speed up the program by inlining the right function.
Page 87
Unix, C & C++
Disadvantages
Since the compiler will copy the entire function body every time the function is
called, if it is a large function (more than three or four lines), inline function can
increase the size of the executable program significantly.
Although it is sometimes easier to read functions if they are inline, it is sometimes
harder to read inline functions. If a function is more than one or two lines, using
the function inline will more than likely distract a reader who is trying to
understand how the class works.
Constant Function
Constant Functions are the special kind of functions which are not allowed to
change the value of the instance variables. A function is made a constant function by
using the keyword const. Consider the following program:
#include<iostream.h>
class Circle
{
int r;
public:
void input()
{
cout<< “Enter the value of the radius”;
cin>>r;
}
void area() const
{
cout<< “Area=”<<3.14*r*r;
}
};
main()
{
Circle c;
c.input();
c.area();
}
ANNAMALAI
ANNAMALAI UNIVERSITY
Output:
UNIVERSITY
Enter the value of the radius12
Area=452.16
In this case the function area() is made a constant function. This means that it
cannot change the value of the instance variable. Suppose a statement like
r++;
is included in the function area, it will result in error. This way, it can be ensured that the
area of circle of given radius is only computed. The advantage of making a function
constant is that, the accidental change in value of the instance variable can be avoided.
Page 88
Unix, C & C++
Static Function
Static Functions are functions that are not confined to a single object but to the
class as such. In fact these functions can be called using the class name and scope
resolution operator and there is no need to create an object of a class to call the static
function of the class. A function is made a static function by using the keyword static.
The following program creates a static function for a class and calls it without even
creating the object.
#include<iostream.h>
class St
{
public:
static void stat()
{
cout<< “This is a static function”<<endl;
}
void display()
{
cout<< “ Not a static function”<<endl;
}
};
main()
{
St::stat();
//St::display();
St s;
s.stat();
s.display();
}
Output:
This is a static function
This is a static function
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Not a static function
Since the function stat() in the program above, is a static function it is called even
before an object could be created. Look at the second statement in the main block, this
statement has been commented. This is because that statement calls the function display()
directly without creating an object. This will lead to error as the function is only an
ordinary function and not a static function.
Page 89
Unix, C & C++
Function Overloading refers to the process of defining more than one function
with the same name inside the same class. Although the name of these functions remains
the same, either the number of arguments or the data type of the arguments passed to the
function must differ. It is based on these distinctions that the compiler will spot the
correct function.
#include<iostream.h>
class FuncOver
{
public:
float avg(int , int);
float avg( int, int, int);
};
float FuncOver::avg(int in1, int in2)
{
return (in1 + in2)/2.0;
}
float FuncOver::avg(int in1, int in2, int in3)
{
return (in1 + in2 + in3)/3;
}
main ()
{
FuncOver f;
cout << "Average of two numbers is: " << f.avg(23,25)<< endl;
cout << "Average of three numbers is: " << f.avg(23,25,24)<< endl;
}
Output:
Average of two numbers is: 24
Average of three numbers is: 24
The function avg() has been overloaded in the class FuncOver. The function avg()
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
accepts two integer arguments in one form while it accepts three integer arguments in the
other form. Thus depending on whether the average of two numbers has to be computed
or average of three numbers has to be computed, the corresponding function is called.
4.2.9 Constructors
A constructor is a special function, which is having the same name as that of the
class. The constructor will be called automatically when a new instance of the class is
created. The constructor also differs from the function in that it has no return type.
Page 90
Unix, C & C++
#include<iostream.h>
class Rectangle
{
int x, y;
public:
Rectangle();
void area ();
private:
int z;
};
Rectangle::Rectangle( )
{
cout<< “Enter x and y values ”<<endl ;
cin>>x;
cin>>y;
}
void Rectangle::area()
{
z=x*y;
cout<< “Area : ” << z;
}
main()
{
Rectangle r;
r.area();
}
Output:
Enter x and y values
2
3
Area: 6
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
In this program, there is no separate function for accepting the value for the
instance variables; a constructor is used instead. Hence, when the object is created as
shown in the first statement of the main(), the constructor is called automatically. The
programmer need not worry about ensuring if the functions are called in proper order.
The constructor then accepts the value for the instance variables and the final output is
got when the function area() is called.
Page 91
Unix, C & C++
Just like a function can be overloaded, the same way constructor can also be
overloaded. This means that a class can have more than one constructor but the number
of arguments or the data type of the arguments passed to them differs.
#include<iostream.h>
class Poly
{
int a,b,c;
public:
Poly()
{
a=0;
b=0;
c=0;
cout<< “ Not a polygon”<<endl;
}
Poly(int x)
{
a=x;
cout<< “ It is a square of side ”<< a<<endl;
cout<< “ Perimeter of the Square :”<< 4*a<<endl;
ANNAMALAI
ANNAMALAI UNIVERSITY
} UNIVERSITY
Poly(int x, int y)
{
a=x;
b=y;
cout<< “ It is a rectangle of height ”<< a<< “and width ”<< b<< endl;
cout<< “ Perimeter of the Rectangle :”<< 2*(a+b)<<endl;
}
Poly(int x, int y, int z)
{
a=x;
Page 92
Unix, C & C++
b=y;
c=z;
cout<< “ It is a Triangle ”<< endl;
cout<< “ Perimeter of the Triangle :”<< (a + b + c)<<endl;
}
};
main()
{
Poly p1,p2(5),p3(5,3),p4(1,2,3);
}
Output:
Not a polygon
It is a square of side 5
Perimeter of the Square :20
It is a rectangle of height 5and width 3
Perimeter of the Rectangle :16
It is a Triangle
Perimeter of the Triangle :6
The class Poly has four types of constructors. One of it uses no argument while
the others use one, two and three arguments. Depending on the requirement, the required
constructor is called by passing the corresponding number of arguments.
4.2.11 Destructors
The Destructor can be considered to be the opposite of constructor functionality
wise. It is automatically called when an object is released from the memory, either
because it goes out of scope or because it is an object dynamically assigned and is
released using operator delete. The destructor must have the same name as the class with
a tilde (~) as prefix and it must return no value.
The use of destructors is especially suitable when an object assigns dynamic
memory during its life and at the moment of being destroyed the memory that it has used
has to be released.
The following program uses a destructor. The destructor is called automatically
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
when the program terminates.
#include<iostream.h>
class Square
{
int a;
public:
Square();
~Square();
int peri();
};
Page 93
Unix, C & C++
Square::Square()
{
cout<< “Enter the length of the side of a square ”<<endl;
cin>>a;
}
int Square::peri()
{
int p;
p=4*a;
cout<< “ Perimeter of the square is : ” ;
return p;
}
Square::~Square()
{
cout<< “ \n Destructor called :End of program”;
}
main()
{
Square s;
cout<<s.peri();
}
Output:
Enter the length of the side of a square
5
Perimeter of the square is : 20
The above program uses only two statements in the main. The first statement in
the main() creates an object of class Square thereby calling the constructor. This is then
followed by a call to the member function peri() to compute the perimeter of the square.
The program then ends calling the destructor.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Constructor Destructor
Constructor has the same name as It has the same name as that of the class but the
that of the class. name is preceded by a tilde (~) symbol
Constructor is called Destructor is called automatically when the object
automatically when an object is goes out of scope.
created.
Page 94
Unix, C & C++
Class objects can be initialized dynamically too. That is, the initial values for the
object’s data member may be provided during run time. One advantage of dynamic
initialization is that various initialization formats can be provided, using overloaded
constructors. This provides the flexibility of using different format of data at run time
depending upon the situation.
Consider the long-term deposit schemes working in the commercial banks. The
banks provide different interest rates for different schemes as well as for different periods
of investment. The Program below illustrates how to use the class variables for holding
account details and how to construct these variables at run time using dynamic
initialization.
#include<iostream.h>
class Fixed_deposit
{
long int P_amount; //Principal amount
int Years; //Period of investment
float Rate; //Interest rate;
float R_value; //Return value of amount
public:
Fixed_deposit(){}
Fixed_deposit(long int p, int y, float r);
Fixed_deposit(long int p, int y);
void display(void);
};
Fixed_deposit :: Fixed_deposit(long int p, int y)
{
float r=0.21;
P_amount=p;
Years =y;
Rate =r;
R_value=P_amount;
for(int i=1;i<=y; i++)
R_value =R_value * (1.0 +r);
}
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Fixed_deposit :: Fixed_deposit(long int p, int y, float r)
{
P_amount=p;
Years =y;
Rate =r;
R_value=P_amount;
for(int i=1;i<=y; i++)
R_value =R_value * (1.0 +float (r)/100);
}
void Fixed_deposit ::display (void)
Page 95
Unix, C & C++
{
cout << “\n”;
cout << “Principal Amount =” << P_amount << “\n”;
cout << “Return Value =” << R_value << “\n”;
}
main()
{
Fixed_deposit FD1, FD2,FD3; //deposit created
long int p; //principal amount
int y; //investment period, years
float r; //interest rate, decimal form
int R; //interest rate, percent form
cout << “Enter amount, period, interest rate(in percent)” << “\n”;
cin >> p >> y >>R;
FD1=Fixed_deposit(p,y,R);
cout << “Enter amount, period, interest rate(decimal percent)” << “\n”;
cin >> p >> y >>r;
FD2 =Fixed_deposit(p,y,r);
FD3 =Fixed_deposit(p,y);
Page 96
Unix, C & C++
Deposit 3
Principal Amount =5000
Return Value=12968.7
The program uses three overloaded constructors. The parameter values to these
constructors are provided at run time. The user can provide input in one of the following
forms:
1. Amount, period and interest in decimal form.
2. Amount, period and interest in percent form.
3. Amount and period.
Since the constructors are overloaded with the appropriate parameters, the one
that matches the input values is invoked. For example, the second constructor is invoked
for the forms(1) and (2), and the third is invoked for the form(3). Note that, for
form(3),the constructor with default argument is used. Since input to the third parameter
is missing, it uses the default value for r.
Copying variables
For Example,
int a = 10;
int b=20;
With basic data types copying means creating a new variable of the same type and
giving it the same value. The above statement does not mean assigning a value to an
existing variable, they mean initializing variable. A different notation can be used for
copying one variable to another.
For Example,
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
instead of int a=b;
In the similar way objects can also be copied. Functional notation is widely used
in Copy Constructors. Copy constructors provide another way to create objects, by
making a copy of an existing object. They take a unique argument type.
Example
#include<iostream.h>
Page 97
Unix, C & C++
class CopyCon
{
private:
int intvar;
public:
CopyCon()
{
intvar = 10;
}
CopyCon(int v)
{
intvar=v;
}
CopyCon(CopyCon &obj)
{
intvar = obj.intvar;
cout << "I am a copy constructor \n" ;
cout << "intvar value inside copy constructor is " << intvar << endl;
}
void disp()
{
cout << "Value of intvar is " << intvar << endl;
}
};
void main()
{
CopyCon cobj;
CopyCon cobj1(27);
CopyCon cobj2 = cobj1;
CopyCon cobj3(cobj1);
cobj.disp();
ANNAMALAI
ANNAMALAI UNIVERSITY
cobj1.disp();
cobj2.disp();
cobj3.disp();
UNIVERSITY
}
Output:
I am a copy constructor
intvar value inside copy constructor is 27
Iam a copy constructor
intvar value inside copy constructor is 27
Value of intvar is 10
Page 98
Unix, C & C++
Value of intvar is 27
Value of intvar is 27
Value of intvar is 27
4.2.14 Friend Function
So far, it has been stated that the private members of a class are not accessible
anywhere outside the class. But these private members of a class are accessible to a
function declared to be a friend of that class. Thus a friend function of a class is that
function that has access to even the private members of the class. A function is declared a
friend function by using the keyword friend.
#include<iostream.h>
class Rectangle
{
int width, height;
public:
Rectangle();
int area () ;
friend void perimeter ();
};
int Rectangle::area ()
{
return (width * height);
}
Rectangle::Rectangle ()
{
cout<<”Enter the width and height values:” <<endl;
cin>>width;
cin>>height;
}
void perimeter ()
{
Rectangle r;
ANNAMALAI
ANNAMALAI UNIVERSITY
int p;
UNIVERSITY
p=2*(r.width + r.height);
cout<< “The perimeter of Rectangle is: ”<< p;
}
main ()
{
perimeter();
}
Output:
Enter the width and height values:
Page 99
Unix, C & C++
5
4
The perimeter of Rectangle is: 18
The program above illustrates the use of a friend function. In this case, the
function perimeter() is a friend function of the class Rectangle and hence can gain access
to the private members of the class Rectangle.
An operator is overloaded using the keyword operator. The general syntax for
overloading an operator is as follows:
where,
return_type: refers to the data type of the variable or object to which the call to
the overloaded operator is assigned. If the overloaded operator is not assigned to anything
its return type is void.
operator is a keyword.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
argument refers to the variable or object that is used along with the operator.
There should be a single argument in case of overloading a binary operator and there
should be no argument when overloading unary operator.
An overloaded operator is called by giving the name of the object followed by the
overloaded operator as follows:
Object_name overloaded_operator
Page 100
Unix, C & C++
The following example shows how a unary operator is overloaded. The program
uses the increment operator ‘++’. This operator requires only a single operand and hence
takes no argument when it is overloaded.
#include<iostream.h>
class Uno
{
int a;
public:
Uno()
{
a=1;
}
void operator ++()
{
a++;
}
int display()
{
return a;
}
};
main()
{
Uno u;
cout<< “ Initial Value of a : ” <<u.display()<<endl;
++u;
cout<< “ Final Value of a : ” <<u.display();
}
Output:
Initial Value of a :1
Final Value of a :2
The class Uno has a single instance variable “a”. Inside the overloaded operator
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
function, the value of the instance variable is incremented. Hence when the function ++ is
called using the object u, the instance variable a of object u is incremented and the
incremented value of a is then displayed when the function display() is called.
The following program shows overloading of binary operator ‘+’. This operator
takes a single argument.
#include<iostream.h>
class Bi
Page 101
Unix, C & C++
{
int x,y;
public:
Bi()
{
x=1;
y=2;
}
Bi operator +(Bi b1)
{
Bi b2;
b2.x=x+b1.x;
b2.y=y+b1.y;
return b2;
}
void display()
{
cout << “ x:”<<x<<endl<< “ y:” <<y<<endl;
}
};
main()
{
Bi u,v,z;
cout<< “ Initial Values:- ”;
u.display();
v.display();
z.display();
u=v+z;
cout<< “ Final Values:- ” ;
u.display();
v.display();
z.display();
}
Output:
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Initial Values:- x:1
y:2
x:1
y:2
x:1
y:2
Final Values:- x:2
y:4
x:1
y:2
Page 102
Unix, C & C++
x:1
y:2
This program creates three objects of class Bi. Each time the constructor is called
and the instance variables x and y of each of the object are assigned a value of 1 and 2
respectively. This is evident when the function display() of the class Bi is called using
each of these objects. Note the statement,
u=v+z;
Here, the object v calls the overloaded operator +. Hence the variables x and y
referred inside the function denotes the instance variable of the object v. The statement
also shows that an object z is also used along with the overloaded operator ‘+’ on the
right hand side. This object is passed as an argument to the overloaded operator function
‘+’. Thus the values of the instance variable of the object z are copied to the instance
variable of object b1. Thus the value of b1.x is same as that of z.x and the value of b1.y
is same as that of z.y.
Page 103
Unix, C & C++
Type conversion means converting a value in one data type to another. This is
necessary so that a value of one data type can be conveniently assigned to a variable of a
different data type.
1. An exact match. The argument matches the type of the function parameter
exactly.
2. Match with a type conversion. The argument does not directly match the type of
the parameter but can be converted to the destination type.
When selecting the best viable function for a function call, the compiler selects
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
the function for which the type conversions on the arguments are the “best”. Type
conversions are ranked as follows: an exact match is better than a promotion, a promotion
is better than a standard conversion, and a standard conversion, and a standard conversion
is better than a user-defined conversion.
Promotion Conversion
Page 104
Unix, C & C++
Standard Conversion
When the value of one object is assigned to another of the same type, such as
the values of all the member data items are simply copied into the new object. The
compiler knows how to do this automatically. Data conversion occurs when one type of
data is assigned to another of different type. The conversion can be implicit such as
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
intvar = floatvar;
intvar = static_cast<int>(floatvar);
Page 105
Unix, C & C++
# include <iostream.h>
const float MTF = 3.280833F;
class Distance
{
private:
int feet;
float inches;
public:
Distance()
{
feet=0;
inches=0.0;
}
Distance(float meters)
{
float fltfeet = MTF * meters;
feet = int(fltfeet);
inches = 12*(fltfeet-feet);
}
Distance(int ft, float in)
{
feet =ft;
inches = in;
}
void getdist()
{
cout << "\nEnter feet: "; cin >> feet;
ANNAMALAI
ANNAMALAI UNIVERSITY
}UNIVERSITY
cout << "Enter inches: "; cin >> inches;
Page 106
Unix, C & C++
}
};
void main()
{
float mtrs;
Distance dist1 = 2.35F;
cout << "\ndist1 = "; dist1.showdist();
dist1 = 1.00;
Output:
dist1 = 7'-8.51949"
dist1 = 3'-3.37"
dist2 = 1.78435 meters
dist1 = 1meters
Object
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Object may represent a person, a place, a bank account, a table of data or any item that
the program must handle. When a program is executed, the objects interact by sending
messages to one another.
Class
A class is a collection of similar objects.
Encapsulation
The winding up of data and function into a single unit (called class) is known as
encapsulation. Data encapsulation is the most striking feature of class.
Page 107
Unix, C & C++
Inheritance
Inheritance is the process by which objects of one class acquire the properties of another
class.
Polymorphism
Polymorphism plays an important role in allowing objects having different internal
structures to share the same external interface. This means that a general class of
operations may be accessed in the same manner even though a specific action associated
with each operation may differ. Polymorphism is extensively used in implementing
inheritance.
Inline function
Functions defined within the class are called inline functions. When a function is inline,
the compiler will replace the function call with a copy of the function body instead of
calling the function every time it is invoked.
Constant Function
Constant Functions are the special kind of functions which are not allowed to change the
value of the instance variables. A function is made a constant function by using the
keyword const.
Static Function
Static Functions are functions that are not confined to a single object but to the class as
such. In fact these functions can be called using the class name and scope resolution
operator and there is no need to create an object of a class to call the static function of the
class. A function is made a static function by using the keyword static.
Function Overloading
Function Overloading refers to the process of defining more than one function with the
same name inside the same class. Although the name of these functions remains the
same, either the number of arguments or the data type of the arguments passed to the
function must differ.
Constructor
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
A constructor is a special function, which is having the same name as that of the class.
The constructor will be called automatically when a new instance of the class is created.
Destructor
The Destructor can be considered to be the opposite of constructor functionality wise. It
is automatically called when an object is released from the memory, either because it
goes out of scope or because it is an object dynamically assigned and is released using
operator delete.
Operator Overloading
Page 108
Unix, C & C++
4.5 Summary
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
An object is an instance of a class.
Inheritance is the process by which objects of one class acquire the properties
of another class.
Page 109
Unix, C & C++
C++ has three different types of access specifiers namely: private, public and
protected.
In C++, the main() returns a value type int to the operating system.
Any program will start its execution from the main() function.
C++ handles data input and output using cin and cout statements respectively.
C++ supports the concept of comments which are text that give information to
the user about what a particular statement does in a program.
Operators are symbols that manipulate the data, which constitute the operand.
Every operator has two important properties called precedence and
associativity.
Operators are classified into unary and binary operators depending on the
number of operands.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Function Overloading refers to the process of defining more than one
function with the same name inside the same class.
Page 110
Unix, C & C++
A friend function of a class is that function that has access to even the private
members of the class.
The operators that cannot be overloaded are: . ,::, .*,?: and sizeof.
4.8 Assignments
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
1. What are objects? Describe the syntax for defining objects with examples.
Explain how C++ supports encapsulation and data abstraction.
2. Write a program illustrating class declaration, definition, and accessing class
members.
3. Write a note on different types of operators used in C++.
4. List the operators that cannot be overloaded and justify why they cannot be
overloaded.
Page 111
Unix, C & C++
5. Write a program that accepts 2 numbers and find their sum and difference.
6. Write a program that accepts 2 numbers from the user and print their product.
4.11 Keywords
Object Oriented Programming (OOP) Class
Object Inheritance
Polymorphism Encapsulation
Abstraction Constructor
Destructor Copy Constructor
Friend function Operator Overloading
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Page 112
Unix, C & C++
UNIT - V
Snapshot
Introduction
Kind of inheritance
C++ inheritance and Class Scope
Types of inheritance
Virtual Base Class
Pointers
Pointers to Objects
this Pointer
Pointers to Base and the Derived Classes
Virtual Functions
Abstract classes
Introduction to Files
Opening and closing of files
Random Access File
Command Line Argument
UNIX Shell Programming
Basic Unix Commands
Vi Editor
Programming the Shell
Advanced Shell Programming
5.0 Introduction
It is a fundamental aspect of human intelligence to seek out, recognize, and create
relationships among concepts. We build hierarchies, matrices, networks, and other
interrelationships to explain and understand the ways in which things interact. C++
attempts to capture this in inheritance hierarchies. Inheritance is a technique of
organizing information in a hierarchical form. Typically, the pure virtual functions in an
abstract base class are never implemented. Because no objects of that type are ever
created, there is no reason to provide implementations, and the ADT works purely as the
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
definition of an interface to objects which derive from it. Files are used to store
information permanently and to retrieve it whenever required. The file handling
techniques of C++ support file manipulation in the form of stream objects. UNIX is an
increasingly popular operating system. Traditionally used on minicomputers and
workstations in the academic community, UNIX is now available on personal computers,
and the business community has started to choose UNIX for its openness.
5.1 Objective
The objective of this lesson makes the learner aware of the fundamentals of
inheritance, pointers and files. The fundamental concepts include types of inheritance,
Page 113
Unix, C & C++
pointers to objects, this pointer, virtual functions and UNIX shell programming. Towards
end of this lesson the student can get the basic knowledge about command line argument
and advanced shell programming.
5.2 Content
5.2.1 Inheritance
One of the most useful features of classes is inheritance. It is possible to declare a
class, which inherits the properties of another class or classes. This means that, with good
class design, applications, which are based on proven re-usable code, can be built. Thus
classes extend the feature of reusability of code, particularly complex code.
Definition: Inheritance is the mechanism by which a new class inherits the
members of an already existing class.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
new_class is the name of the subclass that is to be created.
access specifier can be either public, private or protected.
existing class is the name of the superclass whose members are to be inherited by the
subclass.
members refer to the extra instance variables and functions that the subclass can include
in addition to the members of its superclass. If a subclass inherits from more than one
class then these classes along with an access specifier have to be separated by a comma
‘,’.
Page 114
Unix, C & C++
{
members;
};
where,
existing_class1 and existing_class2 are the already existing class that are to be inherited.
Example
Consider a class called Sphere defined as follows:
class Sphere
{
int r;
public:
Sphere();
int getDiameter();
float getVolume();
};
Sphere::Sphere()
{
cout<< “Enter radius”;
cin>>r;
}
int Sphere:: getDiameter()
{
return (r+r);
}
float Sphere:: getVolume()
{
return (4/3)*3.14*r*r*r;
}
Now to create a class for ball and since a "ball is a sphere" the members of the
sphere class can be inherited in creating the ball class. This way repeating the same set of
coding can be avoided.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The ball class is created as follows:
class ball: public Sphere
{
public:
void ballcolor();
};
void ball::ballcolor()
{
cout<< “ Ball color is red”;
Page 115
Unix, C & C++
The class "ball" has all the member functions present in Sphere. In addition to the
members r, getDiameter(), getVolume() inherited from the Sphere, an additional member
function has been added ("ballcolor()") to hold the color of the ball. When an object of
class ball is created in the main(), all the functions (getDiameter(), getVolume() and
ballcolor()) can be called using this object. However reverse is not true. This means that
using an object of class Sphere the function ballcolor() cannot be called.
#include<iostream.h>
class Sphere
{
int r;
public:
Sphere();
int getDiameter();
float getVolume();
};
Sphere::Sphere()
{
cout<< "Enter radius:";
cin>>r;
}
Page 116
Unix, C & C++
cout<< b.getDiameter()<<"\n";
cout<<b.getVolume()<<"\n";
b.ballcolor();
}
Output:
Enter radius: 12
24
5425.92
Ball color is red
When the object b of class ball is created the constructor of the super class is called. If
there exists a constructor for ball class, first the constructor of Sphere class is called and
then the constructor of the ball class is called. Through the constructor a value is assigned
to the instance variable r and then the diameter, volume and color are computed.
a. Private Inheritance
General form
class Derived:Base_Class
{
access specifier:
members;
};
or
class Derived: private Base_Class
ANNAMALAI
ANNAMALAI UNIVERSITY
{
UNIVERSITY
access specifier:
members;
};
In this case, the Derived class inherits the members of the Base_class in private
mode. So, all the members of the Base_class become private in Derived class. Thus,
Page 117
Unix, C & C++
b. Protected Inheritance
General form
In this case, the Derived class inherits the members of the Base_class in protected
mode. So, the protected and public members of the Base_class become protected in
Derived class. Thus,
c. Public Inheritance
General form
In this case, the Derived class inherits the members of the Base_class in public
mode. So, the public members of the Base_class become public in Derived class. Thus,
Note that the private members of a base class will never be accessible in the
derived class.
5.2.1.2ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
C++ Inheritance and Class Scope
Every class in C++ has its own individual scope even when it inherits members
from other classes. Those members that are explicitly defined in the class definition of a
derived class belong to the scope of that class, those members which are members in
virtue of inheritance belong to the scope of the super-class from which they were
inherited. The scope rules for C++ classes have a number of consequences.
1) Those member functions which belong to the scope of a derived class will only
have access to the data members within the scope of the derived and to those data
members which are inherited from the public or protected section of the super-
Page 118
Unix, C & C++
class.
2) Constructors for a derived type must make use of super-class constructors in order
to initialise the data members inherited from the super-class.
Where the data members of a superclass should not be accessible for all but
accessible to members of the subclass, those members should be declared in the protected
section of the superclass.
The inheritances seen so far come under the category of single inheritance. There
are five different types of inheritance namely:
Single Inheritance
Multilevel Inheritance
Multiple Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Single Inheritance
In this type of inheritance a new class called the derived class inherits the
members of a single class called the base class. There is only one level of inheritance.
This means that the newly created class does not have any derived class and has only a
single parent class.
class
A
ANNAMALAI
ANNAMALAI B UNIVERSITY
class
UNIVERSITY
Single Inheritance
Multi-level inheritance
In this type of inheritance a new class called the derived class inherits the
members of a single class called the base class. This newly created class becomes a
Page 119
Unix, C & C++
parent class for another class. Thus, there exists more than one level of inheritance. This
is diagrammatically represented as:
class
A
class
B
class
C
Multi-level inheritance
In this case class A is the super class of class B, which in turn is the base class of class C.
Multiple Inheritance
In this type of inheritance a new class called the derived class inherits the
members of more than one class. This is diagrammatically represented as follows:
class class
A B
ANNAMALAI
ANNAMALAI
class
UNIVERSITY
UNIVERSITY
C
Multiple inheritance
In this case, class C inherits the members of both class A as well as class B. Thus
class C has two parent classes.
Page 120
Unix, C & C++
Hierarchical Inheritance
In this type of inheritance more than one new class inherits the members of a
single base class. This is diagrammatically represented as follows:
class
A
class class
B C
Hierarchical inheritance
Hybrid Inheritance
class
A
class class
B C
class
D
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Hybrid Inheritance
In this case, class B and C inherit the members of class A through hierarchical
inheritance and these two classes (B and C) are in turn inherited by D through multiple
inheritance.
Multiple Inheritance
Single inheritance implies that a class has only one direct ‘super-class’; Multiple
inheritance allows the derivation of a class from more than one base class. Consider a
class as follows:
Page 121
Unix, C & C++
#include<iostream.h>
class Add
{
int x,y;
public:
Add()
{
cout<< “Constructor Inside Add class”<<endl;
cout<< “Enter two numbers”;
cin>>x>>y;
}
void sum()
{
cout<< “Sum”<<(x+y)<<endl;
}
};
class Subtract
{
int a,b;
public:
Subtract()
{
cout<< “ Constructor Inside Subtract class”<<endl;
cout<< “Enter two numbers”;
cin>>a>>b;
}
void diff()
{
cout<< “Difference”<<(a-b)<<endl;
}
};
ANNAMALAI
ANNAMALAI UNIVERSITY
{
Math()
UNIVERSITY
cout<< “ Constructor Inside Math class”<<endl;
}
};
main()
{
Math m;
m.sum();
m.diff();
}
Page 122
Unix, C & C++
Output:
Enter 2 numbers
5
6
Constructor Inside Math class
Sum7
Difference-1
The class Math has two base classes Add and Subtract. By creating an object of
class Math the members sum() and diff() of class Add and Subtract respectively can be
called. However, using an object of class Add, the function diff() cannot be accessed and
similarly using an object of class Subtract the function add() cannot be accessed.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
As can be seen from the diagram, classes B and C inherit the member function
fun() of class A using hierarchical inheritance. Class D inherits the members of class B
and class C through multiple inheritance. Ultimately, class D will have 2 copies of the
function fun()- one inherited from class B and the other inherited from class C. While
trying to access the function fun() in D, the compiler will not know which function to
Page 123
Unix, C & C++
access although both functions are the same. This will result in compilation error.
To avoid this problem the keyword virtual is included in the inheritance list:
class A
{
public:
int memberA; //etc.
};
class B : virtual public A
{
// B members ...
};
class C : virtual public A
{
// C members ...
};
class D : public B, public C
{
// has access to one and only one memberA
}
To illustrate this consider the following example:
#include<iostream.h>
class Grand
{
protected:
int data;
public:
Grand()
{
data =1;
}
};
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
class Mother : public Grand
{
};
class Father : public Grand
{
};
class Child : public Mother, public Father
{
public:
Page 124
Unix, C & C++
int getdata()
{
return data; // This is an error since the term data is ambiguous
}
};
void main()
{
Child c;
cout << c.getdata();
}
Output:
None- error in name resolving
In this case the class Child has two copies of the variable data of class Grand.
One it inherits through the class Father and the other through the class called class
Mother. When the function getdata() of the Child class is called the compiler gets
confused as it would not know which of the data it has to call, although both are the
same. This problem can be fixed by using the keyword virtual when deriving class
Mother and class Father from class Grand. The program is thus modified as follows:
Example
#include<iostream.h>
class Grand
{
protected:
int data;
public:
Grand()
{
data =1;
}
};
class Mother : virtual public Grand
{};
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
class Father : virtual public Grand
{};
class Child : public Mother, public Father
{
public:
int getdata()
{
return data;
}
};
Page 125
Unix, C & C++
void main()
{
Child c;
cout << c.getdata();
}
Output:
The virtual keyword tells the compiler to inherit only one sub-object into
subsequent derived classes.
5.2.3 Pointers
Pointers can be confusing and at times, one may wonder why one would ever
want to use them. The truth is, they can make some things much easier. For example,
using pointers is one way to have a function modify a variable passed to it; it is also
possible to use pointers to dynamically allocate memory, which allows certain
programming techniques, such as linked lists.
Pointers point to locations in memory. Picture a big jar that holds the location of
another jar. In the other jar holds a piece of paper with the number 12 written on it. The
jar with the 12 is an integer and the jar with the memory address of the 12 is a pointer
Pointer syntax can also be confusing, because pointers can both give the memory
location and give the actual value stored in that same location. When a pointer is
declared, the syntax is this: variable_type *name; Notice the *. This is the key to
declaring a pointer and it is used before the variable name.
There are two ways to use the pointer to access information about the memory
address it points to. It is possible to have it give the actual address to another variable. To
do so, simply use the name of the pointer without the *. However, to access the actual
value in that particular memory location pointed by the pointer, use the *. The technical
name for doing this is dereferencing.
In order to have a pointer actually point to another variable it is necessary to have
the memory address of that variable also. To get the memory address of the variable, put
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
the & sign in front of the variable name. This helps in retrieving the address of that
variable. This is called the reference operator, because it returns the memory address.
Example
#include <iostream.h>
int main()
{
int x;
int *pointer;
pointer =&x;
Page 126
Unix, C & C++
return 0;
}
Output:
Enter the input : 3
3
The cout outputs the value in x. Why is that? Well, look at the code. The integer
is called x. A pointer to an integer is then defined as "pointer". Then it stores the
memory location of x in pointer by using the ampersand (&) symbol. If you wish, you
can think of it as if the jar that had the integer had an ampersand (&) in it then it would
output its name (in pointers, the memory address) Then the user inputs the value for x.
Then the cout uses the * to put the value stored in the memory location of pointer. If the
jar with the name of the other jar in it had a * in front of it, then it would give the value
stored in the jar, the name of which is stored in this jar. It is not too hard, the * gives the
value in the location. The un astricked gives the memory location.
Notice that in the above example, pointer is initialized to point to a specific
memory address before it is used. If this was not the case, it could be pointing to
anything. This can lead to extremely unpleasant consequences to the computer. one
should always initialize pointers before you use them.
The keyword new is used to initialize pointers with memory from free store (a
section of memory available to all programs). The syntax looks like the example:
Example
int *ptr = new int;
It initializes ptr to point to a memory address of size int (because variables have
different sizes, number of bytes, this is necessary). The memory that is pointed to
becomes unavailable to other programs. This means that the careful coder will free this
memory at the end of its usage.
The delete operator frees up the memory allocated through new. To do so, the
syntax is as in the example.
ANNAMALAI
ANNAMALAI UNIVERSITY
Example
UNIVERSITY
delete ptr;
After deleting a pointer, it is a good idea to reset it to point to NULL. NULL is a
standard compiler-defined statement that sets the pointer to point to, literally, nothing.
By doing this, you minimize the potential for doing something foolish with the pointer.
Pointers to Objects
As stated earlier, a pointer can point to an object created by a class. Consider the
following statement:
Page 127
Unix, C & C++
item x;
where item is a class and x is an object defined to be of type item. Similarly one
can define a pointers it_ptr of type item as follows:
item *it_ptr;
Object pointers are useful is creating object at run time. Pointer is used to access
the public members of an object. Consider a class item defined as follows:
class item
{
int code;
float price;
public:
void getdata(int a, float b)
{
code = a;
price = b;
}
void show(void)
{
cout << “code :” << code << “\n” << “Price:” << price << “\n\n”;
}
};
Lets us declare an item variable x and a pointer ptr to x as follows:
item x;
item *ptr = &x;
The pointer ptr is initialized with the address of x.
One can refer to the member functions of item in two ways, one by using the dot
operator and the object, and another by using the arrow operator and the object pointer.
The statements,
x.getdata(100,75.50);
x.show();
are equivalent to
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
ptrgetdata(100,75.50);
ptrshow();
Since *ptr is an alias of x, one can also use the following method:
(*ptr).show();
The parenthesis is necessary because the dot operator has higher precedence than
the indirection operator *.
Create the objects using pointers and new operator as follows:
Page 128
Unix, C & C++
This statement allocates enough memory for the data members in the object
structure and assigns the address of the memory space to ptr. Then ptr can be used to
refer to the members as shown below:
ptrshow();
If a class has a constructor with arguments and does not include an empty
constructor, one must supply the arguments when the object is created.
Create an array of objects using pointers. For Example, the statement
item *ptr = new item[10];//array of 10 objects
create a memory space for an array of 10 objects of item. Remember, in such cases, if the
class contains constructors, it must also contain an empty constructor.
The following example illustrates the use of pointers to objects. One object is
assigned to another object rather than passing the values as an argument.
#include <iostream.h>
class item
{
int code;
float price;
public:
void getdata(int a, float b)
{
code = a; price = b;
}
void show(void)
{
cout << "Code : " << code << "\n";
cout << "Price : " << price << "\n";
}
};
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
const int size = 2;
main()
{
item *p = new item [size];
item *d = p;
int x, i;
float y;
for(i=0;i<size;i++)
{
cout << "Input code and Price for Item : " << (i+1);
Page 129
Unix, C & C++
Output:
‘this’ Pointer
C++ uses unique keyword called this to represent an object that invokes a
member function. this is a pointer that points to the object calls this function. For
example, the function call A.max() will set the pointer this to the address of the object
A. The starting address is the same as the address of the first variable in class structure.
This unique pointer is automatically passed to a member function when it is
called. The pointer this acts as an implicit argument to all the member functions.
Consider the following simple example:
class ABC
{
int a;
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
....
....
};
The private Variable a can be used directly inside a member function, like
a = 123;
The following statement is used to do the same job;
this -> a = 123;
Page 130
Unix, C & C++
Since C++ permits the use of shorthand form a = 123, programmers are not using
the pointer in this explicit manner. However, user have been implicitly using the pointer
this when overloading the operators using member function.
Recall that, when a binary operator is overloaded using a member function, one
passes only one argument to the function. The other argument is implicitly passed using
the pointer this. One important application of the pointer this is to return the object it
points to. For example, the statement
return *this;
inside a member function will return the object that invoked the function. This statement
assumes importance when we want to compare two or more objects inside a member
functions and return the invoking object as a result. Example:
person greater(person x)
{
if x.age > age;
return x; // argument object
else
return *this // invoking object
Invoke the above function by the call,
max = A.greater(B);
This function will return the object B (argument object) if the age of the person B
is greater than of A, otherwise, it will return the object A (invoking object) using the
pointer this. Remember, the dereference operator * produces the contents at the address
contained in the pointer. A complete program to illustrate the use of this is given below.
#include <iostream.h>
#include <string.h>
class person
{
char name[20];
int age;
ANNAMALAI
ANNAMALAI UNIVERSITY
public: UNIVERSITY
person (char *s, int a)
{
strcpy(name, s);
age = a;
}
person greater(person x)
{
if(x.age >= age)
return x;
Page 131
Unix, C & C++
else
return *this;
}
void display(void)
{
cout << "Name :" << name <<"\n";
cout << "Age :" << age << "\n";
}
};
main()
{
person P1("Arun",37), P2("Kumar",30), P3("Subash",40);
person P(" ",0);
P = P1.greater(P3);
//P3.greater(P1)
cout << "Elder person is:\n";
P.display();
P = P1.greater(P2); //P2.greater(P1)
cout << "Elder Person is :\n";
P.display();
getch();
}
Output:
Elder person is:
Name :Subash
Age :40.549999
Elder Person is :
Name :Arun
Age :37.5
#include<iostream.h>
class Base
{
public:
void fun_base()
Page 132
Unix, C & C++
{
cout << "\nBase";
}
};
class derv : public Base
{
public:
void fun_der()
{
cout << "\nDerv1";
}
};
void main()
{
derv dv1;
derv *ptr;
ptr=&dv1;
ptr->fun_base();
Output:
Base
When a virtual function is called from a pointer, the compiler does not always
know what type of object the pointer is pointing to. In this case, it may not know which
version of the function to call at compile time and this judgment is delayed until runtime.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
At runtime, when the function call is executed, the code finds out the type of object
whose address is in the pointer and calls the appropriate function, depending on the class
of the object.
Static Binding
Page 133
Unix, C & C++
Statbind.cpp
#include<iostream.h>
class Base
{
public:
void show()
{
cout << “\nBase”;
}
};
void main()
{
Base b;
b.show();
}
Output:
Base
Late Binding
Selecting a function during runtime is called late or dynamic binding. In this
program, the compiler does not know which version of show() to call since it depends on
which type of object ptr points to. It could be an object of derv1 or derv2 class. At
runtime the program sees which type of object ptr points to and accordingly calls either
derv1::show() or derv2::show.
dynabind.cpp
#include <iostream.h>
class Base
{
public:
virtual void show()
ANNAMALAI
ANNAMALAI UNIVERSITY
{
UNIVERSITY
cout << “\nBase”;
}
};
class derv1 : public Base
{
public:
void show()
{
cout << “\nDerv1”;
}
Page 134
Unix, C & C++
};
class derv2 : public Base
{
public:
void show()
{
cout << “\nDerv2”;
}
};
void main()
{
derv1 dv1;
derv2 dv2;
Base* ptr;
ptr = &dv1;
ptr-> show();
ptr = &dv2;
ptr->show();
}
Output:
Derv1
Derv2
Late binding increases the power and flexibility of the program. It is also used to
perform the same kind of action on different objects. However it requires some overhead
and excessive use of late binding results in loss in speed and reduced runtime efficiency
of code.
Abstract Classes
Abstract classes are classes from which no objects will be instantiated, but serve
as the base for derived classes. They are enforced in C++ using pure virtual functions. A
class that contains at least one pure virtual function is said to be an abstract class since it
contains one or more functions for which there are no definitions. No object of an
abstract class can be created. An abstract class is designed only to act as a base class,
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
upon which other classes may be built.
#include<iostream.h >
class A
{
public:
virtual void print() = 0;
};
void main()
Page 135
Unix, C & C++
{
A *a;
a = new A; // This object cannot be created
a->print();
}
Example
#include <iostream.h>
class number
{
protected:
int value;
public:
virtual void show() = 0; // pure virtual function
void Setvalue(int v)
{
}
};
class hexa : public number
{
public:
void show()
{
cout << “The number is : “ << value << endl;
}
};
void main()
{
hexa h;
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
h.Setvalue(15);
h.show();
}
Output:
The number is: 1
Since the class number has a function show() assigned zero (without code), it is
called as an abstract class and it cannot be instantiated.
Pure Virtual Functions
Page 136
Unix, C & C++
A pure virtual function is a virtual function with no body. This is so when there is
no need for the base class version of a particular function. The declaration of the pure
virtual function has an assignment-to-zero notation to indicate that there is no definition
for the function.
The prototype for this is
virtual return_type Function_name(parameter list)=0;
When a derived class does not redefine a virtual function, the version defined in
the base class will be executed. In situations like this, a base class may not be able to
define an object sufficiently to allow a base class virtual function to be created or like all
derived classes override a virtual function. To handle these kind of cases, C++ supports
pure virtual functions.
The compiler requires each derived class to either define the function or re declare
it as a pure virtual function. A class containing pure virtual functions cannot be used to
declare any objects of its own. If the derived class fails to override the pure virtual
function then an error is encountered.
Example
#include <iostream.h>
class number
{
protected:
int value;
public:
virtual void show() = 0; // pure virtual function
void Setvalue(int v)
{
value = v;
}
};
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
class hexa : public number
{
public:
void show()
{
cout << “The number is : “ << hex << value << endl;
}
};
void main()
{
Page 137
Unix, C & C++
hexa h;
h.Setvalue(15);
h.show();
}
Output:
The number is: f
Here show() is a pure virtual function and is not defined completely in the class
number. It is defined only in the subclass hex. As a result no instance of the class number
can be created (since it is not complete) and number is called an abstract class.
Disk files require a different set of classes than files used with standard input and
output. C++ has two basic classes to handle files, ifstream and ofstream. ifstream
handles file input (reading from files) and ofstream handles file output (writing to files).
There is another class called fstream which can handle both input and output. All these
classes are present in the header file fstream.h. Hence this header file has to be included
for programs pertaining to disk file handling. The following diagram illustrates the
stream class hierarchy.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Page 138
Unix, C & C++
open()
The first operation generally done on an object of one of the stream classes is to
associate it to a real file, that is to say, to open a file. The function used for this purpose is
open(). The general syntax of open() is:
where filename is a string of characters representing the name of the file to be opened and
openmode is a combination of the following flags:
The class ios is a virtual base class for the istream and ostream. The
iostream(input and output stream) is a class with multiple inheritance from both istream
and ostream. These flags can be combined using bitwise operator OR (|). For example, if
a file "example.bin" is to be opened in binary mode to add data it can be written as
follows:
ofstream file;
file.open ("example.bin", ios::app | ios::binary);
Suppose no mode is specified, this function will directly open an already existing
file in read mode when used with an object of ifstream and in write mode when used with
an object of ofstream. The member functions open of classes ofstream, ifstream and
fstream include a default mode when opening files that vary from one to other:
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY Class
ofstream
Default mode to parameter
ios::out
ifstream ios::in
fstream ios::in | ios::out
The default value is only applied if the function is called without specifying a
mode parameter. If the function is called with any value in that parameter the default
mode is stepped on, not combined.
close()
Page 139
Unix, C & C++
When reading, writing or data manipulation operations on a file are complete the
file has to be closed so that it can be used for some other application. The function
close()is used for this purpose and it terminates the connection between the stream and
buffer. The general syntax is:
eof()
The function eof() returns true (non-zero value) if end-of-file is encountered while
reading a file. Otherwise the function returns a false (zero) value. This function is
generally used while reading from a file.
The following program illustrates opening a file and writing a set of lines to the
specified file.
Note:
A file called “outfile.txt” with the specified text will be created. No output will appear on
the monitor.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The program first creates an object of ofstream. The open() function is called
using this object and a file by name outfile.txt is created. To write into this file the
insertion operator is used along with the object of ofstream. This is very similar to
writing into standard output except for the fact that the output is now directed to the file
instead of the monitor. The last statement
outfile.close();
disconnects the file document from the output stream outfile.The following program
accepts the input from the user and writes into a file. The program terminates when the
user inputs the character ‘0’.
Page 140
Unix, C & C++
#include <fstream.h>
void main()
{
ofstream of;
char c;
of.open (“abc.txt”);
cin>>c;
while(c!= ‘0’)
{
of << c;
cin>>c;
}
of.close();
}
The above program first accepts an input from the user. It checks if that character
is not equal to zero. If it is not, it enters the while loop and writes that character into a
file. This way, it accepts all the characters one by one and writes into the file until the
user inputs a zero.
ANNAMALAI
ANNAMALAI UNIVERSITY
void main() UNIVERSITY
{
ifstream infile;
char fname1[20];
char ch;
cout << "Enter the filename to be read \n";
cin >> fname1;
infile.open(fname1);
if (infile.fail())
{
Page 141
Unix, C & C++
} // end of program
Output:
Enter the filename to be read
outfile.txt
This is my first file
The program uses an object of ifstream for opening the file, as the contents from
the file are to be read. The program uses a while loop to check if all the contents of the
file are read. The expression “!infile.eof()” will return true as long as the end of file is not
reached. If the ‘!’ symbol is missed out the program will not read anything from the file.
Thus the while loop ensures that all the characters till the end of the file are read. Inside
the loop the object of ifstream is used along with the extraction operator to read the
content of the file. This is again similar to cin except that the contents are now read from
the file instead of keyboard. Once a character from the file is read it is printed on the
monitor using the cout statement. Care should be taken to ensure that both these
statements appear inside the loop as otherwise the output will not be proper.
It is always not necessary to use the “>>” operator for reading from a file. A
function called getline() can also be used for this purpose. The following program uses a
getline() function for reading from a file. The function getline() copies the content of a
file into a character array which is then printed.
int main () {
char buffer[256];
ifstream examplefile ("outfile.txt");
while (! examplefile.eof() )
{
examplefile.getline (buffer,100);
cout << buffer << endl;
}
Page 142
Unix, C & C++
}
Output:
This is my first file
C++ supports features for writing to and reading from the disk file objects
directly. The binary input and output functions read() and write() are designed to handle
the entire structure of an object as a single object, using the computer’s internal
representation of data.
These functions are included in the File streams. The function write() is a member
function of ostream, also inherited by ofstream. The function read() is member function
of istream and it is inherited by ifstream. Objects of class fstream have both the
functions.
The size parameter is an integer value that specifies the number of characters to
be read to/written from the buffer.
a. write()
The write() member function is used to save the stream of objects on a specified
file. The following program segment depicts how to write objects belonging to a class
into a file using the write() function.
#include <fstream.h>
class emp_info
{
private:
char name[30];
ANNAMALAI
ANNAMALAI UNIVERSITY
int age;
public:
UNIVERSITY
void input_data()
{
cout<< “Enter the name : ”<<endl;
cin>>name;
cout<< “Enter the age : ”<<endl;
cin>>age;
}
void show_data()
{
Page 143
Unix, C & C++
The program reads the already stored information from the file emp.doc. The
information from the file is first read from the file and then the show_data() function is
called to print the name and age of the employee. Care should be taken that information
has to be printed on the monitor only after accepting the value for the instance variables
from the file. Note that the function input_data() is never called in this case.
a. read()
The read() member function is used to get data for a stream of objects from a
specified file. The following program segment depicts how to read objects belonging to a
class using the read() function.
Page 144
Unix, C & C++
void main()
{
emp_info z; //object z of the base class emp_info
fstream f;
f.open ("emp.txt",ios::in);
f.read ((char*) &z, sizeof(z));
z.show_data();
f.close();
} // end of program
Output:
Name: Ashish
Age : 20
The program writes the object of class emp_info into a file called emp.doc. The
class emp_info has two functions input_data() and show_data(). The input_data()
function is first called to accept the name and age of the employee. Once these
information are got they are written down into the file emp.doc. Care should be taken that
information has to be written into the file only after accepting the value for the instance
variables.
The knowledge of the logical location at which the current read or write operation
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
occurs is of great importance in achieving faster access to information stored in a file.
Thus a file in which any record can be accessed at random is called a Random Access
file.
C++ I/O system supports four functions for setting a file pointer to any desired
position inside the file or gets the current file pointer. These functions allow the
programmer to have control over the position at which the read or write operations take
place. The seekp() and tellp() are member functions of class ofstream. The seekg() and
tellg() are member functions of class ifstream. All these four are available in fstream.
These functions can be used in manipulating the position of the stream pointers that point
to the reading or writing locations within a stream.
Page 145
Unix, C & C++
Initially the file is opened in read mode. The tellg() function returns the current
position of the stream pointer which will obviously be the first position and hence will
return 0.
The statement
Page 146
Unix, C & C++
#include <fstream.h>
void main()
{
char num[10];
fstream inout(“new.txt”, ios::out| ios::in);
for (int i=0;i<10;i++)
inout << i;
inout.seekp(4);
char var[5];
cout << “Enter a string of 4 characters: “;
cin >> var;
inout <<var;
inout.seekg(2);
inout>>num;
cout << num <<endl;
}
Output:
Enter a string of 4 characters: good
23good89
The program creates a file called new.txt and writes into it all the numbers from 0
to 9 using a for loop. The statement,
inout.seekp(4);
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
positions the pointer at the 4th location (numbering of location starts from 0). The
program then accepts a four letter string which is then written starting from that particular
location. Hence the number 4567 gets replaced by good (the entered string). The file
new.txt then contains the following content
0123good89
The program then starts reading the content of the file from location 2 which
produces the output as:
23good89
Page 147
Unix, C & C++
The stream classes form a powerful set of classes. They can be modified,
extended or expanded to incorporate user-defined data types or classes.
They are fully buffered, and thereby they reduce disk access.
They encapsulate their internal working from the user. The programmer need not
specify the type of data to be input or output. It is determined automatically by the
stream class.
In C++ it is possible to accept command line arguments. To do so, one must first
understand the full definition of int main (). It actually accepts two arguments, one is the
number of command line arguments and the other is a listing of the command line
arguments.
#include<iostream.h>
void main(int argc,char* argv[])
{
cout<<" Argc: " <<argc;
for(int i=0;i<argc;i++)
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
cout<<" Argv: " <<argv[i];
}
Output :( when run in dos prompt)
writefile 4 pop 45 67
Argc: 5 Argv: C:\BC5\BIN\WRITEFILE.EXE Argv: 4 Argv: pop Argv: 45 Argv: 67
Where writefile is the name of the file.
To read the command-line arguments the main() function must itself be given two
arguments. The first argc represents the total number of command line arguments. The
Page 148
Unix, C & C++
first command-line argument is always the pathname of the current program. The
remaining command-line arguments are those typed by the user.
date command
It displays the current date and time of the UNIX operating system.
Example
$ date
Thu Jun 19 15:29:19 IST 2002
who command
Example
$ who
student tty01 Aug 10 10:24
ls command
Example
$ ls
abc
file
xyz
ANNAMALAI
ANNAMALAI UNIVERSITY
cd command
UNIVERSITY
This command is used to change from current directory to another directory.
Example
$ cd /bin
Page 149
Unix, C & C++
mkdir command
Example
$ mkdir Abc
pwd command
Example
$ pwd
/usr/student
cp command
Example
$ cp s d
This command copies the content in file s to a new file called d. The file s remains
unchanged.
mv command
This command is used for renaming a file
Example
$ mv s d
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
This command renames the file s to a new file called d.
rm command
This command is used for removing a file.
Example
$ rm s
Page 150
Unix, C & C++
Example
$ rmdir abc
Information can be entered in file using cat command. One disadvantage in this is
that if the content has to be modified, the entire file content has to be retyped. This
disadvantage is overcome in the case of vi editor. vi stands for “Visual”.
vi is an editor which has a command mode and a typing mode. To open a file
using vi, the command vi is followed by the filename. To enter the text in it the mode has
to be changed to insert command i. When ever the mode has to be changed, escape button
has to be hit.
One important aspect of vi is that it does not provide the original copy of the file
when invoked. It provides a “Editing Buffer”. All changes are done to that copy in the
buffer. The original file is replaced when the user quits vi. vi functions in three different
modes. They are:
Command Mode
Insert Mode
Ex escape Mode
In the command mode, any key pressed by the user is assumed as commands of
the editor. No text is displayed on the screen when any key is pressed.
The insert mode helps to insert the text into the vi editor. This mode can be
invoked by using any of the insert, open or append mode command.
The ex escape mode is introduced to make the vi and the ex editors compatible.
When any command is typed in this mode it is shown on the command line. The bottom
line of the vi screen is called as the command line. Here messages are displayed and all
commands entered in the ex escape mode are displayed. vi emits a beep sound if there is
any error.
The vi editor can be invoked by typing vi at the $ prompt. vi can be invoked with
ANNAMALAI
ANNAMALAI UNIVERSITY
a filename.
The syntax is
UNIVERSITY
$ vi filename
Usage of General vi Commands
The usage of general vi commands is as follows:
a. Getting Started with vi
The editor can be invoked by typing vi at the $prompt. vi, when invoked without
a file name, takes input from the standard input. It is always better to invoke vi along
with a file name.
Page 151
Unix, C & C++
Example
$ vi new.txt
$ vi +3 flowers
The second line states that the new file “flowers” will be opened and places the
cursor on the third line. Important keys to remember are as follows:
Keys Description
Enter Executes commands in the ex escape mode and starts a new
Key line in the insert mode. In the command mode it goes to the
next line.
Esc Key Returns the vi editor to the command line
“/” Helps to search for a particular string within the file. The
string along to search the “/” has to be entered on the status
line
“?” Works the same way as “/” key
“:” Used when the user wants to specify a command in the ex
escape mode
:s/X/Y/g Used when the user wants to replace every occurrence of the
word or the character X with Y in the line where the cursor is
positioned
:g/X/s//Y/g Used when the user wants to replace every occurrence of the
word or the character X with Y in each line of the file
All vi commands involve alphabets and the shift and control keys. Since vi is case
sensitive, the user must make sure that the Caps lock is off. The cursor movements can be
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
described as follows:
Keys Direct
ions
h or backspace Left
l or space bar Right
k or - Up
j or + Down
However, before the user uses these commands, the user must check the
command mode.
Page 152
Unix, C & C++
d. Screen Commands
The table below lists few of the commands used to traverse the screen.
Keys Functions
Ctrl + F Moves forward by a screen. To have continuity the last two lines of the
previous screen are displayed.
Ctrl + B Moves backward by a screen. Here again two lines of the previous screen
are displayed.
Ctrl + D Moves the cursor half the screen forward.
Ctrl + U Moves the cursor half the screen backward.
Ctrl + L To clear any message that vi has displayed or to clear any system messages
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
that appear on the screen.
Ctrl + G Displays the status on the status line. Gives the name of the file that is
edited, the number of lines in the file, the current line number and the
percentage of file that precedes the cursor.
f. Text Insertion in vi
Page 153
Unix, C & C++
In order to insert a text within the file, first the user must type in ‘i’ to make sure
that the user is in insert mode. The following commands perform the insertion function.
Keys Functions
i/I Invokes insertion mode. Text insertion is possible only after invoking the
insert mode. The capital I invokes the insert mode and insertion takes place at
the beginning
o Allows insertion by creating a blank line above the current line
O Allows insertion by creating a blank line below the current line
a Used for appending the text .Text is appended after the current position
A Used for appending the text. Text is appended at the end of the line.
g. Deleting text in vi
If the user wants to delete a character or a word or a line that the user typed, use
the following delete commands.
Keys Functions
dd Deletes the line in which the cursor is positioned
ndd Deletes n Lines
dw Deletes the word from the cursor position to the end of the word. It stops at
any punctuation that appears in the word
dW Deletes the word from the cursor position to the end of the word. It ignores
any punctuations that appear with the word
D Deletes the line from the current cursor position to the end of the line
x Deletes current cursor position
X Deletes back one character
nX Deletes previous n characters
In case, the user deleted a word or a line by mistake and the user wants the same,
then the undo command is used. To use the undo command, ensure to be in the command
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
mode and then press “u”.
i. Joining lines of Text
Suppose the user wants to join any two lines of the text, then the user can make
use of the “J” command. To join any two lines, place the cursor at the end of the first line
and then press the letter “J”.
j. Line numbering of Text
Shell scripts and C programs are written using the vi editor. The programs and
coding may be very long. If the user wants to go to the fifth line of the Shell script or the
Page 154
Unix, C & C++
C program, it is better to have the text numbered. vi offers the facility of numbering text.
In order to utilize this facility, the user must ensure the command mode. Then press ‘:’ to
specify that the command is in the escape mode. As soon as the user presses colon, he is
taken to the command line of the vi editor. Now type the command as given below:
(Esc) : set number
Line numbers are then set and all the lines are arranged sequentially. If the user
deletes a line, the line numbers are changed automatically.
If the user does not want the numbering to be done, then the following command
is given.
(Esc) : set nonumber
The users working mode can be identified by the set showmode command, which
is executed like the set number command.
(Esc) : set showmode
k. Changing Text
The following commands are used to change the text.
Keys Functions
Cw Change word
Cc Change Line
C Change text from current position to end of line
P Insert last deleted text after cursor
p Insert last deleted text before cursor
Rx Replace character with X
Rtext Replace text beginning at cursor
S Substitute character
Ns Substitute n characters
S Substitute entire line
u Undo last changes
U Restore current line
l. ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Copy, Delete and Move the multiple lines
In order to make use of these facilities, the user must ensure the command mode.
These multiple lines depend on three major commands. They are:
Copy to the desired position
Move to the desired position
Delete desired number of line
m. Copy to the Desired Position
The user can copy a single line or block of lines to the desired lines.
Page 155
Unix, C & C++
Example 1
Suppose the user wants to copy the second line in the file below the fifth line
then,
(Esc) : 2 co 5
Example 2
If the user wants to copy the first three lines below the seventh line, then do the
following
(Esc) : 1,3 co 7
The user can move the lines in a file to the desired position using the following
commands. To move the third line of the file to the ninth line of the file, the
command is as follows
(Esc) : 3 mo 9
Example
If the user wants to move the fourth line and seventh line of a file to the end of the
file, then
(Esc) : 4 , 7 mo $
Example ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The user can delete the fifth line to the seventh line in a file, using the command
(Esc) : 5,7 d
It is also possible to delete the specified lines from the current position or above
the current position of the cursor using various notations like ‘+’ and ‘-’ respectively.
These notations follow the ‘. ’ symbol which stands for the current cursor position.
(Esc ): 5,7 d
To delete the fourth line from the current cursor position, the command is:
Page 156
Unix, C & C++
(Esc): +4 d
If the user wants to delete the fifth line above the current position, then type
(Esc) : -5 d
p. Save and Exit
Writing a file means saving the edited text and updating the file’s modification
time.
Keys Functions
ZZ Quit vi, writing the file only if changes were made
:x Same as ZZ
:wq Write and quit file
:w Write file
:w file Save copy to file
:w! Write file(overriding protection)
:w! file Overwrite file with current buffer
:w %.new Write current buffer named file as file.new
:q Quit file
:q! Quit file( discarding edits)
Q Quit vi and invoke ex
:vi Return to vi after Q commands
:e file2 Edit file2 without leaving vi
:n Edit next file
:e ! Return to version of current file at time of last write
:e# Edit alternate file
% Current Filename
# Alternate Filename
5.2.9 Shell Programming
A shell is a program that acts as an interface between the kernel and the user. For
example, when the user types in a program at the unix prompt, the shell searches the
PATH for the occurrence of that program name, then the shell instructs the kernel to load
the program, push the program parameters supplied at the command line onto the stack
and finally make the instruction pointer point to the entry point of the program and then
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
finally execute the program. Shell program is primarily used to automate routine systems
administration duties.
Shell Scripts
In DOS it is possible to group commands together in files, called batch files. This
feature is available in Unix too and such files are called Shell Scripts.
Page 157
Unix, C & C++
By default, files created in Unix has no execute permission. So the file has to be
granted executable permission and then execute the file.
But without granting the permission the user can run the file using the sh
command.
sh <filename>
The sh command creates a new shell which takes the specified filename as a
parameter and executes it. Upon the completion of the execution of the script, the shell
dies and the user are returned to the login shell.
Advanced shell programming makes use of loops apart from the preliminary
commands. UNIX supports loops for executing a set of statements repeatedly and also
selective control structures for selectively executing a set of statement.
The if Construct
if {condition}
then
commands
else
commands
fi
Example
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The example compares two strings, if the two strings are equal then the message
“The strings are equal” are displayed else the message “the strings are not equal” is
displayed.
Page 158
Unix, C & C++
Output:
Enter 2 strings
hello
hello
The strings are equal
if…elif
Unix also provides the if….elif construct for checking multiple conditions.
if condition(s)
then command(s)
elif condition
then command(s)
else command(s)
fi
The if construct program is used to execute date and then display good morning,
good afternoon or good evening.
Example
echo `date`
hour=`date|cut -c12-13`
echo $hour
if [ $hour -gt 0 -a $hour -lt 12 ]
then
echo "Good Morning"
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
elif [ $hour -gt 12 -a $hour -lt 14 ]
then
echo "Good Afternoon"
else
echo "Good Evening"
fi
Output:
Tue Aug 13 17:08:43 IST 2002
17
Good Evening
Page 159
Unix, C & C++
case value in
choice1) commands;;
choice2) commands;;
…
…
esac
In the above syntax choice1 and choice 2 are possible courses of action. The right
parenthesis is used to identify the label names. If the value is taken as choice1 then the
commands in choice1 is executed and so on.
Example
In this program, lower case alphabet is accepted as input and checked whether it is a
vowel or not.
echo "Enter a character"
read a
case $a in
a) echo "It is a vowel";;
e) echo "It is a vowel";;
i) echo "It is a vowel";;
o) echo "It is a vowel";;
u) echo "It is a vowel";;
*) echo "Not a vowel";;
esac
Output:
$sh s38
Enter a character
a
It is a vowel
$sh s38
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Enter a character
q
Not a vowel
Page 160
Unix, C & C++
commnd(s)
done
Any variable name can be assigned. The sequence of commands between do and
done are executed for the list of values.
Example
for i in 1 2 3 4 5
do
echo "*****"
done
Output:
*****
*****
*****
*****
*****
Each time the shell attempts to execute the control command, if the exit status of
control command is a Zero, that is, success, then the commands between do and done are
executed.
Example ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The following program is for printing the factorial of a number.
echo "Enter a number"
read n
f=1
i=1
while test $i -le $n
do
f=`expr $f \* $i`
Page 161
Unix, C & C++
i=`expr $i + 1`
done
echo " Factorial of $n is $f"
Output:
$sh s33
Enter a number
5
Factorial of 5 is 120
The loop statement is similar to the while loop except that it continues as long as
the control command fails.
The syntax for until Loop is:
until control command
do
command(s)
done
Example
The following program prints numbers from 1 to 9.
a=1
until [ $a -eq 10 ]
do
echo $a
a=`expr $a + 1`
done
Output:
1
2
3
4
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
5
6
7
8
9
Page 162
Unix, C & C++
The if, while and until statement are often used in conjunction with the test
command. This command can be used to test the values of variables. Some of the
operators and options used with string tests are given as follows:
s1=s2 True if string ‘s1’ and ‘s2’ are identical
s1!=s2 True if the strings are not identical
The exit command is used to exit from the shell script ( to stop execution and
return to the $ prompt) based on the result of a test command. The exit command can be
used as follows:
if test…
then …
else exit
fi
Example
The following shell scripts checks if an argument string contains anything so that
the script will stop executing if the argument string is empty.
if test $# = 0
then echo ”Error –no arguments entered”
exit
fi
The maximum number for positional parameters can be $9. The user can use the
argument $1 through $9 in the shell script at a time. Suppose if more than nine number of
positional parameters, then the “shift” command is used. The shift command discards the
first argument and renumbers the rest. The following example uses shift command to
display a pyramid of the command line argument.
ANNAMALAI
ANNAMALAI UNIVERSITY
Example
UNIVERSITY
The following program has to be executed with command line argument as 1 2 3 4 5.
for n in 1 2 3 4 5
do
i=1
while [ $i –le $n ]
do
echo –n $1
i=`expr $i + 1`
Page 163
Unix, C & C++
done
echo
shift
done
Output:
1
22
333
4444
55555
Inheritance
The technique of building new classes from the existing classes is called inheritance.
Single Inheritance
Derivation of a class from only one base class is called single inheritance.
Multiple Inheritance
Derivation of a class from several (two or more) base classes is called multiple
inheritance.
Pointers
A pointer is an entity, which contains a memory address.
this pointer
Using this pointer, any member function can find out the address of the object of which it
is a member. It can also be used to access the data in the object it points to.
Dynamic Binding
It is a process in which function calls are resolved at runtime.
ANNAMALAI
ANNAMALAI UNIVERSITY
Static Binding UNIVERSITY
It is a process in which the identifiers are associated with the physical address during the
process of compilation and linkage.
Virtual Function
A Virtual Function is a function, which does not exist but nevertheless appears real to
some parts of the program
5.4 Intext Questions
Page 164
Unix, C & C++
5.5 Summary
“this” Pointer contains the address of the current object through which the
function is being invoked.
Page 165
Unix, C & C++
Page 166
Unix, C & C++
5.8 Assignment
1. Define class person (A person has a name, address, telno, email, DOB etc).
Extend that class to define a classes called Official, Student; Staff each of
them having specific properties. Implement virtual functions for getting
details and calculating the performance.
2. Write a program that creates a file called Info.txt to write a string into it.
3. Write a program that reads the content of a file that has the following content.
“Reading the information from the file”
4. Write a program that writes an object of a class into a file and reads the same.
5. Write a shell program to display an output as follows
1
12
123
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
1234
12345
Page 167
Unix, C & C++
3. http://www.unixworld.com/unixworld
4. http://www.yahoo.com/Computers_and_Internet/Operating_Systems/Unix
5. http://www.att.com/isc/lib/unix.html
Collect Research reports and information on UNIX operating System from the
internet.
5.11 Keywords
Inheritance Pointer
Virtual function Abstract class
File read ()
Write () Shell
Date who
ls cd
mkdir pwd
cp mv
rmdir rm
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Page 168