0% found this document useful (0 votes)
0 views173 pages

155E1130 UNIX, C & C++

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 173

DMSCSE13

ANNAMALAI UNIVERSITY
DIRECTORATE OF DISTANCE EDUCATION

M.Sc COMPUTER SCIENCE


FIRST SEMESTER

UNIX, C & C++


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY

Copyright Reserved
(For Private Circulation Only)
Unix, C & C++

Table of Contents

UNIT – I Page No.

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

5.0 Introduction 113


5.1 Objective 113
5.2 Content 114
5.2.1 Inheritance 114
5.2.1.1 Kinds of Inheritance 117
5.2.1.2 C++ Inheritance & Class Scope 118
5.2.1.3 Types of Inheritance 119
5.2.2 Virtual Base Class 123
5.2.3 Pointers 126
5.2.4 Virtual Functions 133
5.2.5 File Class and Hierarchy 138
5.2.5.1 Opening and Closing a File 139
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
5.2.5.2 Random Access File
5.2.6 Command Line Arguments
145
148
5.2.7 Basic UNIX Commands 149
5.2.8 Vi Editor 151
5.2.9 Shell Programming 157
5.3 Revision Points 164
5.4 Intext Questions 164
5.5 Summary 165
5.6 Terminal Exercises 166
5.7 Supplementary Materials 167
5.8 Assignments 167
5.9 Suggested Reading 167
5.10 Learning Activities 168
5.11 Keywords 168

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

Process Operating Peripheral


Management
Management System

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.

1.2.2 History of UNIX


Unix is the most popular multi-user operating system.

Page 2
Unix, C & C++

In 1969, the research department of Bell Laboratory used an operating system


called MULTICS. The disadvantage of this was it retained the batch code of the previous
operating system. In 1973, Thompson and Ritchie reworte the Unix operating system in
C, breaking away from the tradition of writing operating systems in assembly language.
Around 1974, Unix was licensed to universities for educational purposes and a
few years later, was made commercially available.
Some of the popular versions of Unix are:
Version Developed by
Unix System AT&T
Unix BSD(4.xx) Berkeley Software Distribution of
Berkeley University
XENIX Microsoft for micros
ULTRIX DEC for minis
AIX IBM

1.2.3 UNIX fundamentals


The Unix Operating System can be broken down into three basic components,
namely the Scheduler, the File System and the Shell.
The Unix Scheduler
The UNIX scheduler is a program that allows several users to access the system
simultaneously. The scheduler shares computer resources among these users, allowing
each a small slice of the computer’s processor.
The UNIX Shell
The shell is the UNIX system’s command interpreter. It is a program that reads
the lines typed in at the terminal and performs various operations. A shell performs two
basic functions that is it acts as a command interpreter and as a programming language.
As a command interpreter it is similar to DOS. As a programming interface it allows the
user to process commands stored in shell scripts, this function is similar to batch files in
DOS.
The UNIX File System
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
To organize data on to the disk, the UNIX operating system provides a File
System. The File System allows grouping of similar files together, since if thousands of
files are stored together it would be difficult to locate a single file.
The Unix File System has a Hierarchical structure; therefore the files can be
stored under directories. The directories are created to store files containing data of
similar nature. The root directory will contain the bin, dev, var, etc, usr, home, and tmp
directories. The following picture shows a sample file system:

Page 3
Unix, C & C++

INCLUDEPICTURE "http://www.cs.wlu.edu/labs/imgs/files.gif" \* MERGEFORMATINET

Figure 1.1: File System

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

1.2.4 Text Processing

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.

The user can edit a file by typing

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.

write user [tty]

The other user’s terminal beeps and displays a message.

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

-s shows an account of the number of current items.

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

“Good morning every one” message from administrator

Ctrl +d
1.2.6 The UNIX Environment

UNIX operating system’s structure consists of Kernel, Shell and tools and
applications

HW
Kernel

Shell

Figure 1.1 Structure of UNIX System

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:

 Managing the system resources.


 Allocating time for different users and processes.
 Deciding process priorities and performing them.

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:

 Background processing - Simultaneously two processes can be run, one in the


foreground and another in the background, which is called as multitasking.
 Input/Output Redirection - Programs can be instructed to take input from a file
other than the standard input devices and redirect output other than the standard
output device.
 Shell Scripts contain a sequence of commands to be performed with a single
filename.

1.2.7 Introduction to Shell Programming

The shell is a command programming language that provides an interface to the


UNIX operating system. Its features include control-flow primitives, parameter passing,
variables and string substitution. Constructs such as while, if then else, case and for are
available. Two-way communication is possible between the shell and commands. String
valued parameters, typically file names or flags may be passed to a command. A return
code is set by commands that may be used to determine control-flow and the standard
output from a command may be used as shell input.

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.

1.2.8 Shell Variables

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

An environment is an area in memory where one can place definitions of shell


variables. So that they can be accessible to programs.

a. The Ps1 variable

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

b. The PATH variable

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.

c. The HOME variable

This variable contains the Home directory where the login shell is initially located
after logging in.

d. The LOGNAME variable

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.

e. The .Profile file

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

A variable is referenced as follows:

Command ${variable name}

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

Reading a value into a Variable

The read command is used to enter value into a variable from the keyboard during
execution of a shell script.

The syntax of read command is:

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.

Local and Global shell Variables


The environment variables are known only to that particular shell in which the
user is working.

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.

1.2.9 Shell Meta characters

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:

$ cat sample* <ret>


The asterisk is referred to as a wild-card. UNIX interprets the wild-card * in the
command line as a specific pattern and automatically substitutes this pattern with file-
names that match the pattern.

Following is the list of wild-cards that are used in UNIX.


*
?
[]

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

1.2.10 Text Processing


Text processing programs such as grep, egrep, sed, awk and vi, are used to
search the patterns instead of fixed strings. These text patterns are known as regular
expressions. The user can form a regular expression by combining normal characters and
special characters, with the rules below. With these regular expressions the user can do
pattern matching on text data. Regular expressions come in three different forms:
1. Anchors : which tie the pattern to a location on the line.
2. Character sets : which match a character at a single position.
3. Modifiers : which specify how many times to repeat the previous expression.
Few meta-characters are used only by awk and egrep. These are :

+ - match one or more of the preceding expression


? - match zero or more of the preceding expression
| - separator. Match either the preceding or following expression.
() - group the regular expressions within and apply the match to the set.
Commonly used regular expressions are :

xy*z - any occurrence of an x, followed by zero or more y’s, followed by a z.


^cat - cat at the beginning of the line
cat$ - cat at the end of the line
\* - any occurrence of an asterisk
[0-9]$ - any line ending with number
[A-Z][A-Z]* - zero or more upper case letters

1.2.11 Program Development Tools

Editing is one of the most frequently used functions of a general purpose


computer. No matter what the user is planning to do, basic editing is sure to be the first
step. Many users prefer to use a screen editor to create or modify their files. The only
restriction of the screen editor is that the user must have a video (screen) terminal.

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 make program

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 name of the files that make up the program system.


 Their interdependencies.
 How to regenerate the program system.
This makefile is typically called makefile or Makefile by convention, although
any file name will do. However, if the user uses a different name, the user has to supply
the name as an argument whenever the make command is executed.
Once this information has been described to make, make takes over and does the
rest. Simply typing the command make causes the program to examine the makefile and
regenerate the system according to the rules laid out in the file created by the user.
The automatic method of program generation saves the user from the bother of
having to keep track of the files the user has changed and also recompiling each one by
the user itself. When one file is changed the associated file is also changed. By specifying
this dependency in the makefile, make will take care of recompiling the necessary files
whenever that particular file is changed.

1.2.12 Debugging Tools

The most generally available debugger is dbx.

Prerequisites for dbx

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.

Where Print currently active procedures.


Stop at line - suspended execution at line.
Stop in proc - suspended execution in subprogram proc.
Cont - Resume execution
Edit - Invoke vi editor

Step Execute 1 line

Page 12
Unix, C & C++

There are more subcommand available for use with dbx, which can be got from
the help
utility.

1.2.13 Program Maintenance Tools

An important program maintenance tool is make command. The “make”


command, allows recompiling portions of a program without having to recompile the full
package.

% make –f make_command_file target<CR>

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.

1.3 Revision Points


Operating System
An operating system is a collection of system programs that together controls the
operation of a computer system. The operating system along with hardware, application
and other system software’s, and users constitute a computer system. It has two
objectives. Firstly, an operating system controls computer’s hardware. The second
objective is to provide an interactive interface to the user and interpret commands so that
it can communicate with hardware.

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.

UNIX file system


The UNIX file system is a hierarchical, tree-structured namespace that is designed to help
users organize and access files. The namespace consists of directories that hold files. The
UNIX file system consists of the following:
 Disk based file systems
 Network file systems
 Pseudo file systems

Page 13
Unix, C & C++

1.4 Intext Questions

1. Explain about Operating System and its function.

2. Write a note on UNIX fundamentals.

3. Write a note on different communication commands.

4. Write a note on Unix Environment.

5. Write a note on shell variables and shell Meta characters.

1.5 Summary

 An operating system (OS) is a collection of software programs that


coordinates the operation of computer hardware and software.

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

 UNIX’s shell interacts with the user and the computer.

1.6 Terminal Exercises

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

1. Sumitabha Dass, “Unix Concepts and Applications”, Second Edition, TMH,


1998
2. B.W.Kernighan, D.M.Ritchie, “The Programming Language”, PHI, 1988.

Page 14
Unix, C & C++

1.8 Assignments

1. Describe the directory structure of the UNIX file system.


2. Distinguish between absolute path names and relative path names.
3. Why UNIX systems become the favored operating systems for implementing
the open systems philosophy?

1.9 Suggested Reading/Reference Books/Set Books

1. http://www.opengroup.org
2. http://www.unix.org
3. http://www.yahoo.com/Computers_and_Internet/Operating_Systems/Unix

1.10 Learning Activities

1. What features of UNIX systems are especially useful from a software


engineering standpoint?
2. UNIX systems provide an environment in which large tasks may be
accomplished by combining existing small programs rather tan developing
new programs. Why is this important?
1.11 Keywords
Operating System UNIX systems
Shell Kernel
Network File System (NFS) Andrew File System (AFS)

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,

int high, low, results[20];

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 int counter;

Static variables can be initialized as normal; the initialization is performed once only,
when the program starts up.

2.2.2 C Character Set Instructions


The C Character set consists of upper and lower case alphabets, digits, special
characters and white space. The alphabets and digits are together called the alphanumeric
characters.

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

4. White space characters:


blank space newline carriage return formfeed
Horizontal tab vertical tab

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

< less than


> greater than
<= less than or equal to
>= greater than or equal to
== equal to
!= not equal to

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

2.2.4 Data types


The C language supports the following basic data types

char a single byte that can hold one character


int an integer
float a single precision floating point number
double a double precision floating point number
The precision refers to the number of significant digits after the decimal point. In
addition, applying qualifiers to the above data types yield additional data types. A
qualifier alters the characteristics of the data type, such as sign or size. The qualifiers that
alter the size are short and long. These qualifiers are applicable to integers, and yield two
more data types

short int integer represented by a lesser number of bits (16)


long int integer represented by a greater number of bits (32)
The sign qualifiers are signed and unsigned.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
signed short int
unsigned short int
signed int
unsigned int
signed long int
unsigned long int

2.2.5 Console based I/O


Character Input / Output is the lowest level of input and output. It provides very
precise control, but is usually too fiddly to be useful. Most computers perform buffering

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;

while((ch = getchar()) != EOF)


i ++;

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.

#include <ctype.h> /* For definition of toupper */


#include <stdio.h> /* For definition of getchar, putchar, EOF */

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

%f A floating point value

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

double power(double val, unsigned pow)


{ double ret_val = 1.0;
unsigned i;
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
for(i = 0; i < pow; i++)
ret_val *= val;

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

result = power(val, pow);

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.

void error_line(int line)


{ fprintf(stderr, "Error in input data: line %d\n", line);
}
The definition uses type void which is optional. It shows that no return value is used.
Otherwise the function is much the same as the previous example, except that there is no
return statement. Some void type functions might use return, but only to force an early
exit from the function, and not to return any value. This is rather like using break to jump
out of a loop.
This function also demonstrates a new feature.

fprintf(stderr, "Error in input data: line %d\n", line);

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

Scope of Function Variables


Only a limited amount of information is available within each function. Variables
declared within the calling function can't be accessed unless they are passed to the called
function as arguments. The only other contact a function might have with the outside

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.

2.2.7 Processor Directives


The C preprocessor is a tool which filters your source code before it is compiled.
The preprocessor allows constants to be named using the #define notation. The
preprocessor provides several other facilities which will be described here. It is
particularly useful for selecting machine dependent pieces of code for different computer
types, allowing a single program to be compiled and run on several different computers.
The C preprocessor isn't restricted to use with C programs, and programmers who
use other languages may also find it useful, however it is tuned to recognize features of
the C language like comments and strings, so its use may be restricted in other
circumstances. The preprocessor is called cpp, however it is called automatically by the
compiler so you will not need to call it while programming in C.
The preprocessor directive #include is an instruction to read in the entire contents
of another file at that point. This is generally used to read in header files for library
functions. Header files contain details of functions and types used within the library.
They must be included before the program can make use of the library functions. Library
header file names are enclosed in angle brackets, < >. These tell the preprocessor to look
for the header file in the standard location for library definitions.
For example

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

2.2.8 Programming Style in C


Unlike some other programming languages (COBOL, FORTRAN), C is free form
language. We can group statements together on one line. The statements
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
a = b;
x = y+1;
z = a+x;
It can be written in one line as
a = b; x = y+1; z = a+x;
The generous use of comments inside the program cannot be overemphasized. Sensibly
inserted comments not only increase the readability but also help to understand the
program logic. This is very important for debugging and testing the program.

Page 24
Unix, C & C++

2.2.9 Control Structure

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

The if statement is used for decision-making. It executes a statement based on the


result of evaluation of an expression. The general form of the simple if statement is

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

where statement 1, statement 2 may consist of a single statement or a block of


statements. If the if expression evaluates to true, the statement 1 or block following the if
is executed; otherwise, the statement 2 or block following the else is executed. The else
statement is optional. It is used only if a statement or a sequence of statements is to be
executed in case the if expression evaluates to false.

Consider the following Program:

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

c. The if-else-if Statement


This is another common programming construct adapted from the initial if
statement. The general form of this is:
if (expression) statement;
else
if (expression) statement;
else

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

d. The switch Statement


The switch statement is a multi-way decision maker that tests the value of an
expression against a list of integer or character constants. When a match is found, the
statements associated with that constant are executed. The general form of the switch
statement is:

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

The general form is:

for (initialization; test-condition; increment/decrement)


{
statement
}
The execution of for statement is as follows:

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

Consider the following segment of a program:

for (x = 0 ; x<=9; x= x+1)


{
printf("%d",x);
}
printf("\n");

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.

/* Program to display 1 to 10 numbers on the screen */

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

b. The while Statement

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;

while (digit <= 9)


{
printf("%d\n",digit);
++digit;
}
}
Output:
0
1
2
3
4
5
6
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY 7
8
9

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

c. The do…while Loop

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:

/* accept only int values */


#include <stdio.h>
main()
{
int I,j;
I = j = 0;
do {
printf("\nEnter : ");
scanf("%d",&I);
printf("No. is %d", I);
j++;
} while (I !=0);
printf("\nThe total numbers entered were %d", --j);
/* j is decremented before printing because count for last integer (0) is not to be
considered */
}

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

2.3 Revision Points

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.4 Intext Questions

1. List out the popular features of C.


2. What are the different types of qualifiers?
3. What are the components of a format specifier in a printf statement?
4. In what ways does a switch statement is differ from if statement?
5. Explain the differences between a break statement and continue statement
with examples.

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.

2.6 Terminal Exercises

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

2.7 Supplementary Materials

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.9 Suggested Reading/Reference Books/Set Books

1. Venugopal and Prasad, “Programming with C”, TMH, 2001.


2. Balagurusamy, “Programming in ANSI C”, TMH, 1992.

2.10 Learning Activities

1. Why UNIX is considered a natural operating environment for C programs?


How can C exploit the features of UNIX?
2. Contrast the salient features of exit control and entry control structures.

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.

3.2.1.1 Declaration of Structure

Before a structure is used, it has to be declared. The syntax for structure is as


follows:

struct <structure name>{


Data_type structure_element 1;
Data_type structure_element 2;
Data_type structure _element 3;
….
….
Data_type structure_element n;

};

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;

3.2.1.2 Accessing and Initialization of Structure

Structure variable uses dot (.) operator to access structure element. Syntax to
access the structure elements is

structure_name . structure_element_name

for example, To set the value to the structure element

collegestu.rollno = 1125;
collegestu.age = 21;

for example, To take the value from the structure element

int rnumber = colledestu.rollno;


int stuage = collegestu.age;

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.

3.2.1.3 Array of Structure

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

sym[i].usage++; /* increment usage of i-th identifier */

Page 39
Unix, C & C++

for( j=0; sym[i].id[j++] != '\0'; ) ...


etc.

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

3.2.1.4 Nested Structure

It is possible to declare a structure inside another structure. This means a structure


can be made a member of another structure. The following program uses a structure
called date as a member of another structure.

#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

Date of Birth(dd mm yy):12 12 1980

Marks in 3 Subject:98
97
95

Student Result
Ashwin has secured 96.000000%

3.2.1.5 Pointers and structure

Consider a block of data containing different data types defined by means of a


structure. For example, a personal file might contain structures, which look something
like:
struct tag {
char lname[20]; /* last name */
char fname[20]; /* first name */
int age; /* age */
};

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:

Enter the first name:Mahatma

Enter the last name:Gandhi

Age:60

The details are:Name:Mahatma Gandhi


Age:60

3.2.2 Unions

A union is similar to a structure, except that it shares storage space between


different members.
union union_name {
type variable-names ;
...
}union_variables ;

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.

Basic file handling Program

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:

FILE * fopen(char *filename, char *mode)

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

1. r - open for reading


2. w - open for writing (truncate file before writing, if it exists already)
3. a - open for writing, appending to file if it exists already

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

Output: (Assuming the file sample.dat exists)


File opened successfully

Page 43
Unix, C & C++

3.2.3.1 Text mode Unformatted I/O functions


It is simple to input or output a single character at a time and C has certain
functions which accept or prints a single character at a time. The getchar() function reads
the next character from the standard input; getc(fp) reads the next character from the
stream fp. Both return the next character and if the next character cannot be read, the non-
character constant EOF is returned. Similarly, the function putchar(c) writes the character
c to standard output; putc(c, fp) writes the character c to the stream fp.
The following program, illustrates how the functions getchar() and putc() can be
used to accept the character from the user and copy those contents into a file respectively.
#include<stdio.h>
main()
{
char c;
int i;
FILE *fp;
fp = fopen(“dat.txt”,”w+”);
printf(“Enter the characters”);
while ((c= (char)getchar( ) )!= ‘0’)
putc( c,fp );
}
Input:
Enter the characters
God helps those who help themselves
0
The following program illustrates how the functions getc() and putchar() can be
used to read information from a file and display it on the screen :
#include<stdio.h>
main()
{
int c;
FILE *fp;
fp= fopen(“dat.txt”,”r+”);
while((c=getc(fp))!=EOF)
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY }
putchar( 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++

3.2.3.2 Line Input and Output (fgets, fputs, etc.)

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

int puts(char *line)

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.

The following example illustrates the use of gets and puts.

#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

char *fgets(char *line, int max, FILE *fp)

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

3.2.3.3 Text mode Formatted I/O functions


Similar to the functions printf() and scanf(), there are equivalent function which
read or write data to files. These are called fprintf and fscanf and take the file pointer as
an additional first argument. Consider the following example,

#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

The following program illustrates reading from a file using fscanf ( )

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

3.2.3.4 Binary mode I/O Functions

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

the Macintosh, CRLF on MS-DOS, or an end-of-record mark on record-oriented


operating systems). On MS-DOS systems, without binary mode, a control-Z character in
a file is treated as an end-of-file indication; neither the control-Z nor any characters
following it will be seen by a program reading the file. In binary mode, on the other hand,
characters are read and written verbatim; new line characters (In MS-DOS, control-Z
characters) are not treated specially.
Binary files are mainly used in image handling programs. For general purposes, it
is strongly recommended to use text files/text mode I/O operations.

3.3 Revision Points

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.4 Intext Questions


1. What is a structure? How does a structure differ from an array?
2. What is structure member? What is the relationship between a structure
member and a structure?
3. How is an array if structures initialized?
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
4. What is a union? How does a union differ from a structure?
5. What is the primary advantage to using a data file?

3.5 Summary
 A pointer in C refers to a variable that holds the address of another variable.

 The main use of structure is to lump together collections of disparate variable


types, so that they can conveniently be treated as a unit.

Page 48
Unix, C & C++

 A union is similar to a structure, except that it shares storage space between


different members.

 Files are very useful in storing information for future analysis and retrieval. C
language defines a number of functions for handling files.

3.6 Terminal Exercises

1. How can structure variables be declared? How do structure variable


declarations differ from structure type declarations?
2. How is a structure member accessed? How can a structure member be
processed?
3. What happens when a pointer to a structure is incremented?
4. Summarizes the different types of files that can be specified by the fopen
function.
5. For what kinds of applications are unformatted data files well suited?

3.7 Supplementary Materials

1. Schildt, “C++: The Complete Reference”, Third Edition, TMH, 2000.


2. Byron Gottfried, “Programming with C”, Second Edition, TMH, 1998.

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

1. Venugopal and Prasad, “Programming with C”, TMH, 2001.


2. Balagurusamy, “Programming in ANSI C”, TMH, 1992.

Page 49
Unix, C & C++

3.10 Learning Activities

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

The major motivating factor in the invention of Object-Oriented Programming


(OOP) approach is to salvage some of the flaws encountered in the procedural approach.
OOP treats data as a critical element in the program development and does not allow it to
flow freely around the system. It ties data more closely to the functions that operate on it
and protects it from accidental modification from outside functions. OOP is used to
decompose a problem into a number of entities called objects and then builds data and
functions around these entities used to decompose a problem into a number of entities
called objects and then builds data and functions around these entities.

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.

Structured programming remains an enormously successful approach for dealing


with complex problems. But, by the late 1980s, some of the deficiencies of structured
programming had become too clear. There was a difficulty in separating the data
structures from functions that manipulated the data. The other disadvantage was that the
programmers found themselves constantly reinventing new solutions to old problems.
The idea behind reusability is to build components that have known properties and then
to be able to plug them into the program as and when it is needed. This is modeled after
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
the hardware world. For instance, when engineers need a new transistor, they do not
invent one, they go to a big bin of transistors and finds one that works the way they need
or perhaps modify it. No similar option existed for a software engineer.

Object-oriented programming attempts to respond to these needs, providing


techniques for managing enormous complexity, achieving reuse of software components
and coupling data with the tasks that manipulate the data. The essence of object-oriented
programming is to treat data and the procedures that act upon the data as a single
“object”, a self-contained entity with an identity and certain characteristics of its own.

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

4.2.1 Object Oriented Programming

4.2.1.1 Features of OOPs

Object-oriented programming is an approach that provides a way of modularizing


programs by creating partitioned memory area for both data and functions that can be
used as templates for creating copies of such modules on demand.
That is, an object is considered to be a partitioned area of computer memory that
stores data and set of operations that can access that data. Since the memory partitions are
independent, the objects can be used in a variety of different programs without
modifications. The features of OOPs are as follows:

 Emphasis is on data rather than procedure.


 Follows bottom-up approach in program design.
 Programs are divided into objects.
 New data and functions can be easily added.
 Data structures are designed such that they characterize the objects.
 Functions that operate on the data of an object are tied together in the data
structure.
 Data is hidden and cannot be accessed by external functions.
 Objects may communicate with each other through functions.

4.2.1.2 Basic Concepts of OOPs

Object-Oriented programming concepts are as follows:

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

In OOP, objects are members of classes. A Class serves as a plan or template. It


specifies what data and what functions will be included in objects of that class. Defining
the class does not create any objects. A class is a collection of similar objects.

Data Abstraction and 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. The data is not
accessible to the outside world and only those functions, which are wrapped in the class,
can access it. These functions provide the interface between the object’s data and the
program. This insulation of the data from direct access by the program is called data
hiding.

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.

A message for an object is a request for execution of a procedure and therefore


will invoke a function (procedure) in the receiving object that generates the desired result.
Message passing involves specifying the name of the object, name of the function
(message) and the information to be sent.

4.2.1.3 Principles of OOP


OOP offers several benefits to both the program designer and the user. It solves
many problems associated with the development and quality of software products. The
new technology promises greater productivity, better quality of software and lesser
maintenance cost. The principle advantages are:

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

4.2.1.4 Problems in Software development

Development in software technology continues to be dynamic. New tools and


techniques are announced in quick succession. This has forced the software industry and

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:

 How to represent real-life entities of problem in system design?


 How to design systems with open interface?
 How to ensure reusability and extensibility of modules?
 How to develop modules that are tolerant to any changes in future?
 How to manage time schedules?
 How to improve the quality of software?

4.2.1.5 Applications of OOP

OOP has become one of the programming buzzwords today. It appears to be a


great deal of excitement and interest among software engineers in using OOP. The most
popular application of object-oriented programming has been in the area of user interface
design such as Windows. There are hundreds of windowing systems developed using
OOP techniques.

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.

4.2.2 Introduction to C++

C++ is an object-oriented programming language. Initial name was ‘C’ with


classes’. C++ was developed by Bjarne Stroustrup at AT & T Bell Laboratories in
Murray Hill, New Jersey, USA, in the early eighties. The idea of C++ comes from the C
increment operator ++, thereby suggesting that C++ is augmented (incremented) version
of C++.

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.

The object-oriented features in C++ allow programmers to build large programs


with clarity, extensibility and ease of maintenance, incorporating the spirit and efficiency
of C. The addition of new features has transformed C from a language that currently
facilitated top-down, structured design, to one that provides bottom-up, object-oriented
design.

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.

Type Name Used to Store


char Characters
short Small whole numbers
int Normal sized whole numbers
long Large whole numbers
float Small real numbers
double Large real numbers
long double Extra-large real numbers

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;

Assigning a value to a variable


A newly declared variable is not set to any value. Unless a value is explicitly
assigned to it, it takes a random value. A variable is assigned a value by using an “=”
symbol. The value assigned to a variable is retained until the variable is assigned a new
value or the program terminates.
ANNAMALAI
ANNAMALAI UNIVERSITY
Example UNIVERSITY
a=5;
b=6.5;

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

4.2.3 Introduction to I/O


Any program requires certain data to process and finally gives a result based on
the data fed to it. The data given to the program is called input and the final result from
the program is called output.

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

The symbol ‘>>’ is called an extraction operator.

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.

Simple C++ program

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.

In C++ program any number or character needs to be stored in a variable. From


the algorithm it is clear that three variables are required to store the numbers (the 2
numbers that have to be summed up and the answer). Since all the variables are used for
storing numbers, their data type can be int. Thus the first statement in C++ program
should be

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:

cout<< “The sum is :” << c;

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

In both the programs above, note the use of “#include<iostream.h>”. This


statement is called preprocessor directive. This causes the preprocessor to add the

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.

Compiling and executing a program


Mere typing of a program will not produce any output. The typed program called
source code has to be compiled. The compilation is the process by which the syntax of
the program is checked and then converted to object file. The compilation process is
followed by a linking process during which the library functions are linked automatically
with the object file to produce an executable file. The executable file when executed
produces the desired output. The entire process of compiling, linking and executing the
program can be represented as follows:

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
C++ Source file

COMPILER

Object file

LINKER Library functions

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

Greater than or equal to >= Left to Right


Equal to == Left to Right
Not equal to != Left to Right
Bitwise AND & Left to Right
Bitwise Exclusive OR (XOR) ^ Left to Right
Bitwise inclusive OR | Left to Right
Logical AND && Left to Right
Logical OR || Left to Right
Conditional ?: Right to Left
Assignment = Right to Left
*=, /=, %= Right to Left
+=, -=, &= Right to Left
^=, |= Right to Left
<<=,>>= Right to Left
Comma , Right to Left
Arithmetic operators
Operators like ‘+’, ‘-’, ‘*’, ‘/’ are well known and they perform usual addition,
subtraction, multiplication and division respectively. There are some operators that need
more attention at this stage.
The Unary minus (‘-’) operator
The subtraction operator can sometimes be used in the unary form on one operand
and it performs the function of arithmetic negation. In effect it multiplies its single
operand by -1. So,
-a
changes the sign of the number ‘a’.

The Modulus (‘%’) operator

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,

30 < 40 is true (or one)


and
40 < 30 is false (or zero)

Logical Operators

In addition to the relational operators, C contains two logical operators(also called


Logical connectives). They are

&& - logical and operator


|| - logical or operator
Logical operators act upon operands that are themselves logical expressions. The
net effect is to combine the individual logical expressions into more complex conditions
that are either true or false. The result of logical and operation will be true only if both
the operands are true whereas, the result of logical or operation will be true if either one
of the operand is true or both the operands are true. For example:
Let the value of i be 2 and c be 3.Then

(i>0) && (c<2) will be false while (i>0) || (c<2) will be true.

Assignment Operators

Assignment operators are used to assign a value, result of an expression or the


value of another variable to a variable. The general form is

Variable = Value or Variable = Expression or Variable = Variable


Assignment operators can also be combined with arithmetic operators. The
shorthand form of this combination is as follows.

Variable binaryoperator= expression

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
This is equivalent to saying

Variable = Variable binaryoperator expression

Consider an example

X += 5;

This is the same as

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)

Conditional Operators (Ternary operator)

A ternary operator pair "?:" is available in C++ to construct conditional


expression of the form

exp1 ? exp2 : exp3;

where exp1, exp2 and exp3 are expressions.

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:

x = (a>b) ? a*10 : b /5;


This is the same as saying

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

Operator Use Operation


op1 >>
>> shift bits of op1 right times
op2
op1 <<
<< shift bits of op1 left times
op2
& op1 & bitwise and

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

op1 op2 Result


0 0 0
0 1 0
1 0 0
1 1 1

Suppose the values 12 and 13 are to be anded:


12 & 13
The result of this operation is 12. This is because, the binary representation of
12 is 1100, and the binary representation of 13 is 1101. The "and" function sets the
resulting bit to 1 if both operand bits are 1, otherwise, the resulting bit is 0. So, if the
two operands are lined up the “and” function is performed the two high-order bits of
each operand are 1. Thus the resulting bit in the result is also 1. The low-order bits

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
evaluate to 0 because either one or both bits in the operands are 0.

1101
& 1100
------
1100

The | operator performs the inclusive or operation and ^ performs the


exclusive or operation. Inclusive or means that if either of the two bits are 1 then the
result is 1. The following table shows the results of inclusive or operations:

Page 69
Unix, C & C++

op1 op2 Result


0 0 0
0 1 1
1 0 1
1 1 1

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.

op1 op2 Result


0 0 0
0 1 1
1 0 1
1 1 0

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.

Increment and Decrement Operators

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:

++m pre increment


m++ post increment
--m  pre decrement
m--  post decrement

These operators come in handy while writing the loop statements.


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Note: The evaluation order becomes important while handling these
increment/decrement operators. For example:
int x=8,y=3,z;
z = x++ * ++y;
Here z will be evaluated as 32. This is because the variable x is post incremented.
So operation is done after the expression is evaluated. So while evaluating the expression
x is still 8. But y is pre-incremented, that is, the operation is done before evaluating. So y
will be evaluated to 4. So the final expression is evaluated as 8 * 4 = 32. After evaluation
is done x is operated by post-increment operator. So x will now become 9.

Page 70
Unix, C & C++

4.2.5 Basic Control Structures

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


++pass_count;
In the above example, the variable pass_count is incremented by one only if the
value of the integer variable marks is less than 65. If more than a single instruction has to
be executed in case the expression is true, then the instructions are enclosed within curly
brackets {}.

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.

The following program uses an if statement to validate the user’s input to be in


the range 1-10.

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

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.

The general form of if-else statement is:

if (expression) statement1 else statement2

Depending on whether the result of an expression is true or false, statement1 or


statement2 is evaluated respectively.

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:

Enter value for x:


-4
x is Negative

The switch case Statement


The switch case statement is a better way of writing a program when a series of

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

cout<<numb1<<”+”<< numb2<<”=”<< total;


else if( menu == 2 )
cout<<numb1<< “-“ << numb2<< “=”<< total ;
}
Output:
Enter two numbers: 37 23
Enter the choice
1=Addition
2=Subtraction
2
37 - 23 = 14

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.

/* This is an example of a "while" loop */


#include <iostream.h>
void main()
{
int count;
count = 0;

Page 75
Unix, C & C++

while (count < 6)


{
cout<< “The value of count is :” << count<<endl;
count = count + 1;
}
}
Output:
The value of count is: 0
The value of count is: 1
The value of count is: 2
The value of count is: 3
The value of count is: 4
The value of count is: 5

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.

Several things must be pointed out regarding the while loop.

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

The do-while Loop

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.

Consider the following example to understand do-while construct.

/* This is an example of a do-while loop */


#include<iostream.h>
void main()
{
int i;
i = 0;
do
{
cout<<"The value of i is now : "<< i<<endl;
i = i + 1;
} while (i < 5);
}
Output:
The value of i is now: 0
The value of i is now: 1
The value of i is now: 2
The value of i is now: 3
The value of i is now: 4

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

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

for (initialization; condition; increment) statement


It works in the following way:

1. Initialization is executed where the counter variable is assigned an initial value.


This is executed only once.
2. Condition is checked, if it is true the loop continues, otherwise the loop terminates
and statement is skipped.
3. Statement is executed. As usual, it can be either a single instruction or a block of
instructions enclosed within curly brackets { }.
4. Finally, whatever is specified in the increment expression is executed and the loop
gets back to step 2.

The following example illustrates the use of for loop.

/* This is an example of a for loop */


#include<iostream.h>
void main()
{
int index;
for(index = 0 ; index < 6 ; index = index + 1)
cout<<"The value of the index is: "<< index<<endl;
}

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

fixed number of iterations.


The for loop is also convenient because it moves all of the control information for
a loop into one place, between the parentheses, rather than at both ends of the code. It is
upto the user to decide the type of loop to be used in the program.

The Break and Continue Statements


Sometimes, it may be necessary to interrupt the normal flow in the loop and come
out prematurely. The branching out of loop is carried out by break and continue
statements.

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.

/* This file demonstrates the use of break and continue */


#include<iostream.h>
void main()
{
int xx;
for(xx = 5 ; xx < 15 ; xx = xx + 1)
{
if (xx == 8) break;
cout<< “In the break loop, xx is now:” << xx<<endl;
}
for(xx = 5 ; xx < 15 ; xx = xx + 1)
{
if (xx == 8)
continue;
cout<< “In the continue loop, xx is now:”<< xx<<endl;
}
}
ANNAMALAI
ANNAMALAI UNIVERSITY
Output:
UNIVERSITY
In the break loop, xx is now: 5
In the break loop, xx is now: 6
In the break loop, xx is now: 7
In the continue loop, xx is now: 5
In the continue loop, xx is now: 6
In the continue loop, xx is now: 7
In the continue loop, xx is now: 9
In the continue loop, xx is now: 10

Page 79
Unix, C & C++

In the continue loop, xx is now: 11


In the continue loop, xx is now: 12
In the continue loop, xx is now: 13
In the continue loop, xx is now: 14
Notice that in the first for loop, there is an if statement that calls a break if xx
equals 8.The break will jump out of the loop and begin executing statements following
the loop, effectively terminating the loop. This is a valuable statement whenever it is
required to jump out of a loop depending on the value of some results calculated in the
loop. In this case, when xx reaches the value of 8, the loop is terminated and the last
value printed will be the previous value, namely 7. The break always jumps out of the
loop just past the terminating brace.
The next for loop, contains a continue statement which does not cause
termination of the loop but jumps out of the present iteration. When the value of xx
reaches 8 in this case, the program will jump to the end of the loop and continue
executing the loop, effectively eliminating the cout statement during the pass through the
loop when xx is eight. The continue statement always jumps to the end of the loop just
prior to the terminating brace. At that time the loop is terminated or continues based on
the result of the loop test.

The goto Statement

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

if (i==j) goto flag3;


}
cout<< “ One”;
}
}

Page 80
Unix, C & C++

flag3: cout<<“I am out of the loop!”;


}

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.

4.2.6 Defining Classes and Objects

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:

class Test  keyword “class “and class name


{  opening brace
 other programming lines to go here
};  closing brace and 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

The array manager contains three objects (managers), namely, manager[0],


manager[1] and manager[2], of type employee class. Similarly, the foreman array
contains 5 objects(foreman) and worker array contains 75 objects (workers).

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

void employee:: getdata(void)


{
cout << “Enter name :”;
cin >> name ;
cout << “Enter age: “;
cin >> age;
}
void employee::putdata(void)

Page 84
Unix, C & C++

{
cout << “Name:” << name;
cout << “\n Age:” << age;
cout << “\n \n”;
}
main()
{
int i;

employee manager[3]; // Array of managers


for ( i=0; i<3; i++)
{
cout << “\n Details of manager” << i+1 <<” \n”;
manager[i].getdata();
}
cout << “\n”;
for (i=0;i<3;i++)
{
cout << “\n Manager” << i +1 << “\n”;
manager[i].putdata();
}
}

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

Passing Objects as Functions Arguments

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

 Only the address of the object is transferred to the function (pass-by-


reference)
Example:
 Implemented in Copy Constructor
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
4.2.7 Functions and its Types

Functions play an important role in c++ program development. Dividing a


program into functions is one of the major principles of top-down, structured
programming. Another advantage of using functions is that it is possible to reduce the
size of a program by calling and using them at different places in the program. C++ has
added many new features to functions to make them reliable and flexible. Different types
of functions are as follows:

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

4.2.8 Function Overloading

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.

To make obvious the concept of constructor program is as follows:

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

Difference between Constructor and member function


Constructor Member function
Constructor has the same name as The name of the function can be different.
that of the class.
Return type is not allowed Functions have return type.
Constructor is called automatically Functions can be invoked only through objects.
when an object is created.
4.2.10 Constructor Overloading

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.

Difference between Constructor and 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.

4.2.12 Dynamic initialization of objects

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

cout << “Enter amount and period” << “\n”;


cin >> p >> y;

FD3 =Fixed_deposit(p,y);

cout << “\n Deposit 1”;


FD1.display();

cout << “\n Deposit 2”;


FD2.display();
cout << “\n Deposit 3”;
FD3.display();
}
Output:
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Enter amount,period,interest rate(in percent)
5000 5 15
Enter amount,period,interest rate(in decimal form)
5000 5 0.15
Enter amount and period
5000 5
Deposit 1
Principal Amount =5000
Return Value=10056.8
Deposit 2

Page 96
Unix, C & C++

Principal Amount =5000


Return Value=5037.61

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.

4.2.13 Copy Constructor

Copy constructor is a special type of constructor in C++. The functionality of


copy constructor is similar to copying variables.

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;

This type of notation is sometimes called as functional notation. Anyhow to


avoid confusion the equal sign can be used in between.

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.

4.2.15 Operator Overloading

C++ has an important concept of Operator Overloading. Operator Overloading is


a special case of function overloading, which allows assigning additional meanings to
most of the standard C++ operators. When overloading operators, it is a good practice to
ensure that the overloaded operator has a similar behaviour to the original operator. For
example, it would make more sense to use the + operator for concatenation of strings than
the = operator. Overloading operators does not change the precedence and associativity
of the operator. New operators cannot be introduced using operator overloading.

An operator is overloaded using the keyword operator. The general syntax for
overloading an operator is as follows:

return_type operator operatorsymbol(argument)


{
statement;
}

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.

operatorsymbol refers to the operator that is to be overloaded.

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

Unary Operator Overloading

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.

Binary Operator Overloading

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.

Inside the overloaded operator function another object of class Bi called b2 is


created. The instance variable x of the object b2, that is, b2.x is assigned the sum of v.x
and b1.x (same as z.x). Similarly the instance variable y of the object b2, that is, b2.y is
assigned the sum of v.y and b1.y (same as z.y). The object b2 is finally returned from the
function and hence the value of instance variables of this object are assigned to the
corresponding instance variable of the object u.

General Rules for Overloading Operators


There are certain restrictions and limitations to be kept in mind while overloading
operators. The rules are:
 Only existing operators can be overloaded. New operators cannot be created.
 It is recommended not to change the basic meaning of an operator. That is, the
plus (+) operator should not be redefined to subtract one value from another.
 Overloaded operators follow syntax rules of the original operators that cannot be
overridden.
 Friend functions cannot be used to overload certain operators like =, (), [] and ->.
 Unary operators, overloaded by means of a member function take no explicit
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
arguments. But those overloaded by a friend function take one reference
argument.
 Binary operator overloaded through a member function takes one explicit
argument and those that are overloaded through a friend function take two
arguments.
 Binary operators such as +, -, * and / must explicitly return a value.
 When using binary operators overloaded through a member function, the left hand
operand must be an object of the relevant class.
Operator Overloading Restriction

Page 103
Unix, C & C++

There are some restrictions that apply to operator overloading.


 Operator functions cannot have default arguments.
 The operators that cannot be overloaded are:
 .
 ::
 .
 *
 ?:
 sizeof
 One cannot alter the precedence of an operator.
 One cannot change the number of operands that an operator takes.

4.2.16 Type Conversions

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.

Argument type conversion


During the function overload resolution, the compiler identifies and ranks the
conversions that can apply to each argument in a function call to convert it to the type of
the corresponding parameter in each viable function. There are three possible outcomes
of this ranking:

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.

3. No match. The argument cannot be made to match a parameter of the declared


functions, because no type conversions exist between the argument and the
corresponding function parameter.

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

A promotion conversion is one of the following:

Page 104
Unix, C & C++

 An argument of type char, unsigned char, or short is promoted to type int. An


argument of the type unassigned short is promoted to type int if the machine size
of an int is larger than that of shorter integer otherwise, it is promoted to type
unsigned int.
 An argument of type float is promoted to type double.
 An argument of an enumeration type is promoted to the first of the following type
that can represent all the values of the enumeration constants: int, unsigned int or
unsigned long.
 An argument of type bool is promoted to type int.

Standard Conversion

There are five kinds of conversions grouped in the category of standard


conversions:
1. The integral conversions: the conversions from any integral type or enumeration
type to any other integral type.
2. The floating point conversions: the conversions from any floating point type to
any other floating point type.
3. The floating integral conversions: the conversions from any floating point to any
integral type or vice versa.
4. The pointer conversions: the conversion of a pointer of any type to the type void.
5. The bool conversions: the conversions from any integral type, floating point type,
enumeration type, pointer type to the type bool.

User Defined Conversion (Casting operators &Conversion functions)

When the value of one object is assigned to another of the same type, such as

dist3 = dist1 + dist2;

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;

Casting provides explicit conversion:

intvar = static_cast<int>(floatvar);

For conversion of user-defined types, the programmers must define the


conversion routines. Data conversion may seem unnecessarily complex or even
dangerous.

However, the flexibility provided by allowing conversions outweighs the dangers.

Page 105
Unix, C & C++

Conversions between Objects and Basic Types


The following example performs the data conversion between the objects of class
distance and float. The conversion is meant to convert Distance into meter and vice versa.

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

void showdist() const //display distance


{
cout << feet << "\'-" << inches << '\"' ;
}
operator float() const //conversion operator
{
float fracfeet = inches/12;
fracfeet += float(feet);
return fracfeet/MTF;

Page 106
Unix, C & C++

}
};
void main()
{
float mtrs;
Distance dist1 = 2.35F;
cout << "\ndist1 = "; dist1.showdist();
dist1 = 1.00;

cout << "\ndist1 = "; dist1.showdist();


Distance dist2(5, 10.25);
mtrs = float(dist2);
cout << "\ndist2 = " << mtrs << " meters\n";
mtrs = dist1;
cout << " \n dist1 = " << mtrs << "meters" ;
}

Output:
dist1 = 7'-8.51949"
dist1 = 3'-3.37"
dist2 = 1.78435 meters
dist1 = 1meters

4.3 Revision Points


Object-oriented programming
Object-oriented programming attempts to respond to these needs, providing techniques
for managing enormous complexity, achieving reuse of software components, and
coupling data with the tasks that manipulate that data. The essence of object-oriented
programming is to treat data and the procedures that act upon the data as a single
"object". An Object is a self-contained entity with an identity and certain characteristics
of its own.

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

Operator Overloading is a special case of function overloading, which allows assigning


additional meanings to most of the standard C++ operators.

4.4 Intext Questions

1. What is OOPs? What is the significance of OOPs?


2. Explain the features of OOPs.
3. Define the following terms:
 Variable.
 Keyword.
 Data type.
 Constant.
4. What is inheritance? Why you need inheritance?
5. When will you make a function inline? Why?
6. When do you need to use constant function?
7. Explain the merits and demerits of inline function.
8. Describe the importance of constructor.
9. Explain copy constructor with an example.
10. Explain type conversion with an example.
11. Which operator cannot be overloaded?

4.5 Summary

 OOP is used to decompose a problem into a number of entities called objects.

 A class is a way of creating user-defined data types.

 A class declaration consists of data member and member functions.

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.

 Polymorphism means the ability to take more than one form.

 Objects communicate with one another by sending and receiving information


in the same way as people pass message to one another.

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.

 Variables are quantities whose values can be changed.

 Constants are quantities whose values cannot be changed.

 Data type decides the type of value, a variable can hold.

 Keywords are special words that have a specific meaning in a computer


language.

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

 A comment is just some text enclosed in a pair of comment delimiters.

 A function is made a constant function by using the keyword const.

 A function is made a static function by using the keyword static.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
 Function Overloading refers to the process of defining more than one
function with the same name inside the same class.

 A constructor is a special function, which is having the same name as that of


the class.

 The Destructor can be automatically called when an object is released from


the memory.

 Advantage of dynamic initialization is that one can provide various


initialization formats, using overloaded constructors.

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.

 Operator Overloading is a special case of function overloading, which allows


assigning additional meanings to most of the standard C++ operators.

 An operator is overloaded using the keyword operator.

 The operators that cannot be overloaded are: . ,::, .*,?: and sizeof.

 Type conversion means converting a value in one data type to another.

4.6 Terminal Exercises


1. Explain static function with example.
2. What is the need for overloading an operator?
3. How do we invoke a constructor and destructor function?
4. Constructors do not return any values (True/False).
5. What do you mean by function overloading? When do we use this concept?
6. What is friend function?
7. Define operator overloading.

4.7 Supplementary Materials

1. Schildt, “C++: The Complete Reference”, Third Edition, TMH, 2000.


2. E.Balagurusamy, “C++”, Second Edition, TMH, 2001.

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.9 Suggested Reading/Reference Books/Set Books

1. B.W.Kernighan, D.M.Ritchie, “The Programming Language”, PHI, 1988


2. Venugopal, Rajkumar, Ravishankar, “Mastering C++”, TMH, 2001.

4.10 Learning Activities


1. Collect information on Object Oriented Programming concepts from the
internet.
2. Collect information on Type conversion.

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.

Suppose a class A inherits the properties of a class B, it means “A inherits from


B”. Objects of class A thus have access to attributes and methods of class B without the
need to redefine them.
If class A inherits from class B, then B is called superclass of A. A is called
subclass of B. Objects of a subclass can be used where objects of the corresponding
superclass are expected. This is due to the fact that objects of the subclass share the same
behaviour as objects of the superclass. In addition to the members inherited from the
superclass, the subclass can also include additional members. Superclasses are also called
parent classes. Subclasses may also be called child classes or just derived classes.
The subclass can again be inherited, making this class the superclass of the new
subclass. This leads to a hierarchy of superclass/subclass relationships. The general
format for inheriting a class is:
class new_class: access specifier existing_class
{
members;
};
In this case,

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
‘,’.

class new_class: access specifier existing_class1, access specifier existing_class2

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

int Sphere:: getDiameter()


{
return (r+r);
}
float Sphere:: getVolume()
{
return (4/3)*3.14*r*r*r;
}
class ball: public Sphere
{
ANNAMALAI
ANNAMALAI UNIVERSITY
public: UNIVERSITY
void ballcolor();
};
void ball::ballcolor()
{
cout<< " Ball color is red";
}
main()
{
ball b;

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.

5.2.1.1 Kinds of Inheritance

C++ provides three forms of inheritance:


 private inheritance (the default)
 protected inheritance
 public inheritance.

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,

Protected Members become Private Members


Public Members become Private Members

Page 117
Unix, C & C++

b. Protected Inheritance

General form

class Derived: protected Base_Class


{
access specifier:
members;
};

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,

Protected Members become Protected Members


Public Members become Protected Members

c. Public Inheritance

General form

class Derived: public Base_Class


{
access specifier:
members;
};

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,

Protected Members become Protected Members


Public Members become Public Members

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.

5.2.1.3 Types of Inheritance

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.

This is diagrammatically represented as:

class
A

ANNAMALAI
ANNAMALAI B UNIVERSITY
class
UNIVERSITY
Single Inheritance

In this case class A is the super class of class B.

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

In this case, two classes B and C inherit the members of class A.

Hybrid Inheritance

A combination of any two or more types of inheritance is called 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;
}
};

class Math : public Add, public Subtract


{
public:

ANNAMALAI
ANNAMALAI UNIVERSITY
{
Math()
UNIVERSITY
cout<< “ Constructor Inside Math class”<<endl;
}
};
main()
{
Math m;
m.sum();
m.diff();
}

Page 122
Unix, C & C++

Output:

Constructor Inside Add class


Enter two numbers
3
4
Constructor Inside Subtract class

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.

5.2.2 Virtual Base Class

A potential problem for multiple inheritance occurs when a chain of inheritance


derives from a single class via two or more paths, thus causing duplication of inherited
data and functions.

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

cout<<”Enter the input : “;


cin>>x;
cout<<*pointer;

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
ptrgetdata(100,75.50);
ptrshow();
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++

item *ptr = new item;

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:

ptrshow();
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++

cin >> x >> y;


p->getdata(x,y);
p++;
}
for(i=0; i<size;i++)
{
cout << "Item : " << (i+1) << "\n";
d->show();
d++;
}
}

Output:

Input code and Price for Item 1 : 1001 5000


Input code and Price for Item 2 : 1002 10000
Item : 1
Code : 1001
Price : 5000
Item : 2
Code : 1002
Price : 10000

‘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

Pointers to Base and Derived Classes


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
A pointer to a base class can be assigned the address of one of the base’s derived
class objects. If the derived class overrides members of the base, the compiler associates
pointer reference accesses with the base class components of the object. This means that
if a derived class member overrides a base class member, the pointer ignores the override.

#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

5.2.4 Virtual Functions


The same function name is used in both the base and derived classes, the function
in base class is declared as virtual using the keyword virtual preceding its normal
declaration. When a function is made virtual, c++ determines which function to use at run
time based on the type of objects pointed to by the base pointer, rather than the type of
the pointer.

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

As in traditional programming languages, the compiler calls fixed functions based


on the code. The linker replaces the identifiers with a physical address. Essentially, all
function calls are resolved at compilation itself. Connecting to the functions in the normal
way at compilation is called early or 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();
}

Program will result in an error

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.

5.2.5 File Class and Hierarchy

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. A stream is a general name given to the flow of data in an input/output
process. In fact cin and cout used so far are themselves stream objects. These stream
objects are pre-defined in the header file iostream.h. Both cin and cout are used for
standard input and output respectively. The extraction operator ‘>>’ is a member of the
istream class and the insertion operator ‘<<’ is a member of the ostream class. Both of
these classes are derived from ios 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

Stream Class Hierarchy

Page 138
Unix, C & C++

5.2.5.1 Opening and Closing of files

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:

void open (const char * filename, openmode);

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:

ios::in Open file for reading


ios::out Open file for writing
ios::ate Erase file before reading or writing
ios::app Every output is appended at the end of file
ios::binary Binary mode

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:

void close ();


Once this member function is called, the stream object can be used to open
another file, and the file is available again to be opened by other process.

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.

Writing a text to a file

The following program illustrates opening a file and writing a set of lines to the
specified file.

//storing strings of text on a text file


#include <fstream.h>
void main()
{
ofstream outfile;
outfile.open (“outfile.txt”);
outfile << “This is my first file”<<endl;
outfile.close();
}

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.

Reading a text from a file


The following program illustrates how to open a file, read its contents and display
it on the screen. The program accepts a file name from the user. When the user supplies a
file name, the program checks if such a file exists and the program exits if the file does
not exist. The function fail() is used for this purpose and returns true if the file is not
opened.
//Reading the contents of a text file and printing it out
#include <fstream.h>
#include <iostream.h>
#include <iomanip.h>
#include <stdlib.h>

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

cerr << "No such file exists \n";


exit(1);
}
while (!infile.eof())
{
infile>>ch;
cout<<ch;
}
infile.close();

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

// reading a text file


#include <iostream.h>
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
#include <fstream.h>

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

Reading and Writing objects to a 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.

Their prototypes are:

write ( char * buffer, streamsize size );


read ( char * buffer, streamsize size );
where, buffer is the address of a memory block where read data are stored or where the
data to be written are taken from.

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

cout<< “Name :”<<name<<endl;


cout<< “Age :”<<age;
}
}; //end of class definition
void main()
{
emp_info z; //object z of the base class emp_info
fstream f;
z.input_data();
f.open (“emp.txt”,ios::out);
f.write ((char*) &z, sizeof(z));
f.close();
} // end of program
Output:
Enter the name:
Ashish
Enter the age:
20
Note:
This information will be written into a file called emp.doc

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.

//reading an object from a file


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
#include <fstream.h>
class emp_info
{
private:
char name[30];
int age;
public:
void input_data()
{
cout<< "Enter the name"<<endl;
cin>>name;

Page 144
Unix, C & C++

cout<< "Enter the age"<<endl;


cin>>age;
}
void show_data()
{
cout<< "Name :"<<name<<endl;
cout<< "Age :"<<age;
}
}; //end of class definition

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.

5.2.5.2 Random Access File

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

tellg() and tellp()


These two member functions accept no parameters and return an integer value
representing the current position of get stream pointer (in case of tellg) or put stream
pointer (in case of tellp).
seekg() and seekp()
This pair of functions serves respectively to change the position of stream
pointer’s get and put. The syntax is as follows:
seekg(offset, origin)
seekp(offset,origin)
Using this prototype, an offset from a concrete point determined by parameter
direction can be specified. These functions move the associated file’s pointer to offset
number of bytes from the specified origin, which must be one of the following three
values:
ios::beg beginning of file
ios::cur current location
ios::end end of the file
The values of both stream pointers get and put are counted in different ways for
text files than for binary files, since in text mode files, some modifications to the
appearance of some special characters can occur.
The following program uses the functions seekg() and tellg() to count the number
of bytes.
#include <iostream.h>
#include <fstream.h>
main () {
long m;
ifstream file (“outfile.txt”, ios::in);
file.seekg (0, ios::end);
m = file.tellg();
file.close();
cout << "size of " << “outfile.txt”;
cout << " is " << (m) << " bytes.\n";
}
Output:ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
size of outfile.txt is 10 bytes.

Imagine the file outfile.txt contains the following content


Hi 12345

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

file.seekg (0, ios::end);


will move the pointer to the extreme end of the file and the tellg() function at that stage
will return the current position of the pointer. This value will be a count of the actual
number of characters stored in the file.
The following program demonstrates the use of seekp() function in writing a set
of characters at a specified location of the file.

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

Advantages of C++ stream classes

 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 offer a rich set of error handling facilities.

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

5.2.6 Command line arguments

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.

It looks like this:


int main(int argc, char* argv[])
The integer argc, is the Argument Count (hence argc). It is the number of
arguments passed into the program from the command line, including the path and name
of the program.
The array of character pointers is the listing of all the arguments. argv[0] is entire
path to the program including its name. After that, every element numbers less than
argc are command line arguments. One can use each argv element just like a string or
use argv as a two dimensional array.

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

5.2.7 Basic UNIX Commands

Unix defines a number of commands. Some of the basic commands are:

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

This command tells which user is currently using the system.

Example

$ who
student tty01 Aug 10 10:24

ls command

ls is the program to list files in a directory.

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

This command changes the current directory to /bin

Page 149
Unix, C & C++

mkdir command

This command is used for creating a new directory.

Example
$ mkdir Abc

pwd command

This command returns the present working directory of the user

Example
$ pwd
/usr/student

cp command

This command is used for making a copy of a file

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

This command deletes the file s.


rmdir command
This command is used for removing an empty directory.

Page 150
Unix, C & C++

Example
$ rmdir abc

This command removes the directory abc.


5.2.8 Vi Editor

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

The three most common ways of starting a vi session are:


$ vi filename
$ vi +n filename
$ vi +/pattern filename
The user can open file for editing, optionally at line n or at the first matching
pattern. If no file is specified, vi opens with an empty buffer.

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

b. Movement of the Cursor

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

c. Some More Cursor Movements


The users try to use more cursor movement commands in order to work faster in
vi.
Keys Functions
w Moves forward by a word. Assumes that punctuations are next words.
W Moves forward by a word and this identifies punctuations as a part of the word.
e Takes the cursor to the last character of the word.
E Takes the cursor to the last character of the word and ignores any punctuation.
b Moves backward by a word.
B Moves backward by a word and ignores any punctuation.
^ Takes the cursor to the beginning of the line.
$ Takes the cursor to the end of the line.
L Takes the cursor to the last line of the file.
G Works like the GOTO command. For e.g to go to the second line in the file the user
can say 2G.
Some more examples of the above movements are:
2w (will move the cursor by two words)
4$ (end of the fourth line)
5b (move five words back)

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.

e. Usage of some Editing


The various ways to insert, delete copy and move the text in the file are discussed
in the following paragraphs.

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

h. The undo Command

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

n. Move to the Desired Position

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

A range of lines can be moved to the desired position.

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 $

o. Delete desired number of lines

It is possible to delete multiple lines in a single command using the escape


command.

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.

Executing a Shell Script

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.

Syntax for the sh command is:

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

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

This construct is used to do a set of commands based on a condition being true. If


the condition is not true then another set of commands can be provided.

The syntax of if statement is:

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.

echo "Enter 2 strings"


read str1
read str2
if test $str1 = $str2
then

Page 158
Unix, C & C++

echo "The strings are equal"


else
echo "The strings are not equal"
fi

Output:
Enter 2 strings
hello
hello
The strings are equal

if…elif

Unix also provides the if….elif construct for checking multiple conditions.

The syntax for the if..elif statement is:

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

The case....esac construct


This construct helps in execution of shell script based on the users choice.
The syntax for case construct is:

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

The for Construct

This is used to perform same set of operations repeatedly on a list of values.


The syntax for for statement is:

for <variable> in value1 value2 value3…


do

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

The following program prints 5 stars 5 times.

for i in 1 2 3 4 5
do
echo "*****"
done

Output:
*****
*****
*****
*****
*****

The while Loop


The statements within the while loop are executed repeatedly as long as the
condition remains true
The syntax for the while loop is:

while control command


do
commandlist
done

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 until Loop

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

The test command

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

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 shift Command

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

5.3 Revision Points

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

1. What does inheritance mean in C++?

Page 164
Unix, C & C++

2. Describe the syntax of multiple inheritance. When is the inheritance used?


3. What is virtual Base class?
4. When the class is made virtual?
5. Explain any five basic UNIX commands.
6. Explain this pointer with an example.
7. Explain pure virtual function with an example.
8. Explain command line argument with an example.
9. Write a note on reading and writing text to a file
10. Write a note on stream class hierarchy

5.5 Summary

 Inheritance is the mechanism that allows a class A to inherit properties of


another class B.
 The class from which a new class inherits is called the Super Class and the
newly created class is called Derived Class.
 A new class can inherit the members of a base class in public, protected or
private modes.
 Single inheritance is the mechanism by which a class inherits the members of
only one class.
 Multiple inheritance is the mechanism by which a class inherits the members
of more than one class.

 Pointer is a variable that can hold the address of another variable.

 Operators used in Pointers are & and *.

& means “Address Of”.


* means “Value at”.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
 A pointer can point to an object created by a class. The arrow operator (->)is
used to access the member of that class. This is called pointer to objects.

 “this” Pointer contains the address of the current object through which the
function is being invoked.

 Dynamic Binding/Late Binding is a process in which function calls are


resolved at runtime.

Page 165
Unix, C & C++

 Static Binding/Early Binding is a process in which the identifiers are


associated with the physical address during the process of compilation and
linkage.
 A Virtual Function is a function, which does not exist but nevertheless
appears real to some parts of the program.
 A Virtual Functions is declared as virtual in base class with the keyword
virtual and redefined in the derived class.
 An Abstract Class is a class which has at least one pure virtual function.

 An Abstract class cannot be instantiated.

 A Pure Virtual Function is a function declared in a base class that has no


definition relative to the base class.

 The declaration of pure virtual function has an assignment-to-zero notation.


 A stream is a sequence of characters and is connected to a device or a file.
 To send/receive data to/from an external file the file must be connected to a
stream.
 C++ supports both input and output with files through the following classes:
 ofstream: File class for writing operations (derived from ostream)
 ifstream: File class for reading operations (derived from istream)
 fstream: File class for both reading and writing operations (derived from
iostream)
 Object can be written into a file using the functions read() and write().
 A random access file helps in accessing a particular record.
 Date command displays the current date and time.
 who command tells which user is currently using the system.
 ls is the program to list files in a directory.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
 cd command is used to change from current directory to another directory.
 vi is an editor which has a command mode and a typing mode.
 A shell is a program that acts as an interface between the kernel and the user.

5.6 Terminal Exercises

1. Inheritance helps in making a general class into a more specific class?


(True/False).

Page 166
Unix, C & C++

2. A base class is never used to create objects? (True/ False).

3. What is the open() command?

4. Write a note on shell programming.

5. Write a note on different loops supported by UNIX.

5.7 Supplementary Materials

1. Schildt, “C++: The Complete Reference”, Third Edition, TMH, 2000.


2. Sumitabha Dass, “Unix Concepts and Applications”, Second Edition, TMH,
1998
3. E.Balagurusamy, “C++”, Second Edition, TMH, 2001.

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

6. Write a shell program to print the greater of two numbers.

5.9 Suggested Reading/Reference Books/Set Books

1. B.W.Kernighan, D.M.Ritchie, “The Programming Language”, PHI, 1988.


2. http://www.unix.org

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

5.10 Learning Activities

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

You might also like