0% found this document useful (0 votes)
12 views244 pages

CPP I-Ii BSC

Uploaded by

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

CPP I-Ii BSC

Uploaded by

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

Introduction to C++

Brief history:
During 1970’s, C language got popularity as general purpose
language. It means many applications are developed in
engineering, business and other fields using C language.The
limitations with C language are complex declarations, pointers
usage, which is difficult to understand. And the language has no
special features to handle length and complexity of a program. At
the same time there was some other language called Simula-67.
Simula was suitable for handling large projects. And C has lot of
features to implement general purpose programs. So, designers
combined features of both the languages and formed a new
language called ‘C WITH CLASSES’. Bjarne Stroustrup worked
with this C WITH CLASSES as a part of his Ph.D work and added
some features to the language. In 1983 the language is renamed
as C++ (An increment of C). C++ supports the all the features of C
and OOP features like classes, objects, polymorphism,
inheritance, abstraction.
Introduction:
Learning a language and programming language has the same
analogy. While learning any language, any one generally starts
with Alphabet. Later they try to write words. At the end writing of
sentences and paragraphs become easy.
In the similar way, we start learning C++ with Character set. The
character set in C++ is listed below.
1. Digits 0-9
2. Letters
i. Lower case letters a-z
ii. Upper case letters A-Z
3. Special characters

The various special symbols used in a C++ program are


mentioned in Table1 and the symbols may have different meaning
in different cases in a program.

1
+ plus sign ` single quote % percent sign
- minus sign " double quote ? question mark
* asterisk { left curly bracket = equal sign
/ forward slash } right curly bracket ! Exclamation mark
\ backward slash [ square bracket (left) - Hyphen
¦ broken bar ] square bracket (right) _ underscore
: colon ( left parenthesis # Hash sign
, comma ) right parenthesis ^ Caret, or hat
; semi colon < less than sign & ampersand
. period > greater than sign ~ tilde
Table 1: Special symbols used in C++ program
1.1 Applications
The Following are the various applications of C++.
1. GUI Based Applications
C++ is used by many GUI based Applications like Adobe, Image ready,
Phothoshop
2. Database Software
C++ is Used in Popular DBMS like MySQL.
3. Compilers
C++ is also used by various compilers such as Apple C++,MINGW
4. Operating System
C++ is internally used in many Operating Systems.
5. Web Browsers
C++ is a preferred programming language for many Browsers like Mozilla
Firefox.
6. Advanced Computations and Graphics
C++ is used in developing 3D animation applications like Maya 3D
software
7. Games
C++ is used in 3D games for controlling the Hardware, for improved
performance
8. Enterprise Software
Many banking, flight simulators and radar processing applications
developed in C++
9. Medical and Engineering Applications
Medical equipments like MRI and Engineering equipments like CAD/CAM
systems are making use of C++.

2
1.2 Tokens in a C++ program
If one or more characters from the character set are arranged in a
meaningful way such that a compiler can understand the
meaning then that set of characters are called token. A token in a
program is same like a word in a language. In other words, the
individual unit in a program that can’t be divided into meaningful
components is denoted as token.
The tokens in C++ programming are divided as follows:

Figure 1:C++ Tokens


Keywords:
In a program, some of the statements start with keywords. The
keywords are like commands to the compiler. The meaning of
each keyword is mentioned in compiler. So the compiler acts as
per the meaning mentioned inside it when such keyword is
encountered.
The keywords are predefined words and their meaning is kept in
compiler. Any programmer must know the meaning of the
keywords to use them in correct context.
The programming language C++ is superset of C. All the C
Keywords works in C++ with the same meaning. In addition to C
keywords, C++ has its own keywords to extend the capability of
the language.
The list of keywords is given below:

Keywords for basic data types


int float char void

Modifiers to basic data types


signed unsigned const double long short

3
Keywords for repeated execution of statements on condition
for do while

Keywords for selecting the statements for execution based on


condition
if else switch case default

Keywords for Shifting the Control on Condition

break continue return goto

Keywords to determine Storage Category


auto extern register static

Keywords for User Defined Types


struct union typedef enum class

keyword for avoiding optimization by compiler


volatile

Keywords for Access Control


private protected public

Keywords for Memory Management


new delete

Keywords for Exception Handling


try catch throw

Keyword for defining small functions for faster execution

inline

4
Keyword used in implementing genericity
template

Keyword used for friendly accessto private data


friend

Keyword used to refer current object


this

Keyword used for operator overloading


operator

Keyword used in Dynamic binding

virtual

Keyword used to write assembly language code in C++


program(not supported on all platforms) asm

5
Variables:
The memory of the computer can be assumed as sequence of
boxes. The programmer treats each box as a byte (8 bits). And
logically the boxes are numbered and the numbers are called
addresses of memory locations.
Every variable has a memory location. In this context the memory
location may be of one or more bytes. In a memory location value
of the variable is stored. The variable can be of any type. A
variable can hold single value at a time. The program can change
value of variable.

Figure 2: Logical memory representation


Suppose, if some variable needs only one byte, it occupies one
byte, it may be 2001 or any other location. And the location is
referenced with some variable name. Any location is allotted to
some variable only when it is not occupied by other data or
instruction. In the same way, if another variable needs two bytes,
that variable may occupy any two bytes which are in sequence.
Let the variable may occupy 2002 and 2003. And two bytes are
referenced by only one variable name.
Variable declaration:

When declaring variables, the programmer has to mention the


data type using related keyword. And variable names
areseparated with comma. At the end the declaration is terminated
with semicolon.

6
Examples:

In line 1: Roll Number of a student is declared as integer, the


keyword used is int. the name of the variable is rollNum.
In line 2: Similar to rollNum, marks1, marks2 and marks3 are
declared as integer variables with the keyword int.
In line 3: Similarly total variable is declared. It is for storing total
marks.
In line 4: average is a variable name, keyword used is float, it is
for storing the average marks of 3 subjects’ marks: marks1,
marks2, marks3.
In line 5: grade is character variable, keyword used is char; it is
for storing the grade obtained by student.
Constants:
The constants in C++ are the fixed values which cannot be
changed during execution of program. C++ supports wide variety
of constants.

Figure 3: Constants in C++


Integer Constants:
In C++, Integer constants are the sequence of digits that does not
have any space and comma. Integer constants are represented in
3 ways:

7
Decimal Integers Octal Integers Hexadecimal Integers

Decimal integers are Octal integers are Hexadecimal Integers


formed with 10 formed with 8 digits (0- are formed with 16
digits (0-9) 7). The octal integers symbols. (0-9 , A-F /a-
are preceded by 0. f). These numbers are
preceded by 0X or 0x.

Examples for numbers in three (Decimal, Octal, And Hexadecimal)


Number systems are listed below:

DECIMAL NUMBER OCTAL NUMBER HEXA DECIMAL NUMBER


100 0144 0X64
2000 03720 0X7D0
13587 032423 0X3513
25874 062422 0X6512
32000 076400 0X7D00
Table 2: Decimal Numbers and Equivalent octal, Hexadecimal Numbers
Why these many representations needed?
In construction of circuits, the binary numbers (2 signals) are
used. So the computer is familiar with binary system. The users
are familiar with Decimal system. There are easy conversion
techniques between binary, octal and hexadecimal. A sequence of
4 bits is used to represent one symbol in hexadecimal system (2 4 =
16). Similarly A sequence of 3 bits are used to represent one
symbol in octal number system (23 = 8). And the users can easily
write and read octal and hexadecimal numbers.

Figure 4 : Types of integer constants


In 16 bit compiler the range of values for integer constants
8
short int long
Memory
2 bytes 2 bytes 4 bytes
size
-2 147 483 648 to
signed -32768 to 32767 -32768 to 32767
2 147 483 647
unsigned 0 to 65535 0 to 65535 0 to 4 294 967 295
Table 3 : Range of values for integer constants.
Note: In 16 bit compiler, the short int and int is same. So the size
and range for short int and int is same. In 32 bit compiler the int
and long int is same. So the size and range for int and long int is
same (4 bytes).In 32 bit compiler short int occupies 2 bytes.

Floating point constants:


To represent different real world entities we also need fractional
values. The fractional values are represented with floating point
constants. The keywords used here are float and double.

Figure 5: Types of floating point constants

Range of values for floating point constants


float double long double
Memorysize 4 bytes 8 bytes 10 bytes
range -3.4e-38 to -1.7e-308 to -3.4e-4932 to
+3.4e+38 +1.7e+38 +1.1e4932
Table 4: Range of values for float point constants.

Example for floating point constant:


9
Figure 6: parts in Floating point constant
In a floating point constant, all the above mentioned parts may or
may not be present.
Character Constants:
Any character from the character set which is placed in single
quote marks is treated as character constant. The special
character like escape sequence characters also considered as
character constants when placed in single quote marks.
Examples:

'a' 'x' '\n' '?' '9'


String Constants:
Any sequences of characters that are mentioned in double
quotation marks are treated as String constants. Even when a
single character is kept in double quotation marks, it is
considered as String constant.
Examples:
"This is a string constant"
"x"

10
Enumeration Constants:
Assigning numeric values to strings is called enumeration. Here
the strings are considered as constants. enum keyword is used to
define the enumeration constants. Defining enumeration
constants improve the readability and understandability in the
program as users are familiar with names than numbers.
For example, In a phone contacts list, the users identify persons
with their names than numbers. In the same way programmers
use enum constants in the program and make the program easy
to understand.
enum Week_Day { Sun , Mon , Tue ,
Wed , Thu , Fri
, Sat};
By default, first constant is assigned with 0 and next will be
assigned with 1 and so on. The programmer can also give his/her
own values to strings.
Working with constants in a C++ Program
1) Literal constant:
A literal constant is directly assigned to a variable. Consider the
following example
int x=5;

Where x is an integer variable and 5 is a constant. And 5 is


referred as literal

2) Symbolic constant:
The symbolic constant can be created in the following ways
1. #define
2. the const keyword
The #define preprocessor directive can be used for defining
constants.
Example: # define PRICE 152
A programmer can also define a constant using const keyword
Example: const int price=152;

11
Operators:
Operator is a symbol that performs an operation. In compiler each
operator has its own meaning. When a programmer uses any
operator with correct syntax and valid operands the operation will
be carried out and results will be returned to programmer. C++
supports wide variety of operators such as
 Arithmetic operators
 Relational operators
 Logical operators
 Bit wise operators
 Special purpose operators
Special symbols:
In a C++ program, different special symbols such as #, &, ?, :, %
etc. are used. The special symbols are also considered as tokens
in the program.
Identifiers
Identifiers are names of program elements such as variables,
functions and arrays, structures and classes etc. They are the user-
defined names.
Rules for forming identifiers:
 Identifier is a sequence of letters and digits, with a letter as a
first character.
 Lower case letters are preferred.
 However, the upper case letters are also permitted.
 The ( _) underscore symbol can be used in an identifier.
 In general, underscore is used to link two words in long
identifiers.
 In ANSI C++ there is no restriction on length of identifier
 C++ is a case sensitive language. It means the compiler treats
lower and upper case letters differently.
 For example, the identifiers Account, account and ACCOUNT
are different in compilers perspective.

12
1.3 Data Types in C++
For any program, user provides input data and the program works
on that data to generate the required output. For example, when a
programmer wants to determine the grade point average of a
student, initially the programmer writes the program code and
submits the code to a computer for execution. During the program
execution the computer asks for the input data such as marks
obtained by the student for providing results to the programmer.
Whatever the data provided by the user or programmer to the
computer is called input data and whatever the results provided
by the computer to the user is called output data.

Figure 7 : Basic idea of program execution


When writing a program code, the programmer must allocate
memory for both input and output data. To instruct the compiler
for allocating the memory to data (input /output) the programmer
writes the instructions. Those instructions are called Data
declaration instructions. In data declaration instructions, the
programmer must mention the type of data (Data type) he/she
wants to use in program and the name of the memory location for
the data.By mentioning the data type the compiler knows whether
the data are numeric or character, for numeric, whether fractional
part is present or not, also the range of data and amount of
memory needed.C++ supports wide variety of data types to write
different types of programs. The data types provided by C++
compiler are listed below:

Figure 8 : Data types available in C++


13
Built-in data types:
The terms, built-in data types, fundamental data types, primitive
data types, primary data types all together refers the same. All are
also denoted as Basic data types. The meanings of basic types are
already defined in compiler. These data types are explained
below:
Character data type:
In this data type, char keyword is used. char occupies 1 byte (8
bits) of memory. Using 8 bits, 28 =256 symbols can be
represented. Many of C++ compilers use ASCII (American
Standard Code for Information Interchange) code.
The type conversion between int and char is possible. For every
character, a numeric value is available in ASCII coding. For every
character the corresponding binary code of numeric value is
stored in memory. Those numeric values are also used in writing
programs. char keyword when used with signed keyword the
range is -128 to 127, and when used with unsigned keyword the
range is 0 to 255.
In ASCII Code, the letters (A-Z) are represented with the numbers 65-
90, a-z are represented with 97-122 and 0-9 digits represented with
48 to 57.

Keywords Memory needed in bytes Range of values


char, signed char 1 -128 to 127
unsigned char 1 0 to 255
Table 5 : character data type

14
Integer data type:
All numeric values which do not have fractional part come into
this category. Keywords used in this category are : int, short,
long, signed, unsigned,
Keywords Bytes Range of values
int  2 bytes =16 bits.
short  Total possible values are
short int (216=65536)
signed  When distributed to both sides of
2
signed int integer number line the range
signed short becomes:
-32 768 to 32 767
signed short int
 (-215 to 215-1)
 2 bytes =16 bits.
 Total possible values are
unsigned
(216=65536)
unsigned int
2  For unsigned only positive integers
unsigned short
are taken so the range becomes:
unsigned short int 0 to 65 535
 (0 to 216-1)
long  4 bytes =32 bits.
long int  Total possible values are (232=4 294
signed long 967 296)
 When distributed to both sides of
4
integer number line the range
signed long int becomes:
 -2 147 483 648 to 2 147 483 647(-
231 to 231-1)
 4 bytes =32 bits.
unsigned long  Total possible values are (232=4 294
967 296)
4  For unsigned only positive integers
unsigned long int are taken so the ranges becomes 0 to
232-1:
 0 to 4 294 967 295
Table 6 : Integer Data types (16 bit compiler)

15
Floating point Data type:
All the Numeric values that have fractional part come into this
category. The keywords float, double is used to declare floating
point values.
Examples for floating point numbers are : -34.75, 12.45, 33.67,
-789-87.

Keywords Memory Range of values Allotment of bits


needed in for sign,
bytes Exponent and
mantissa
float 4 -3.4e-38 to 3.4e+38 1bit for sign, 8 bits
for exponent, 23
bits for mantissa
double 8 -1.7e-308 to 1bit for sign, 11
1.7e+308 bits for exponent,
52 bits for
mantissa
void data type:
void means empty or blank. In C++ every function must have
return type. The return type for a function refers that the kind of
value returned by the function. Some times in some functions
there may be no value to return. In such case the return type is
mentioned as void. When the return type is mentioned as void the
compiler understands that there is nothing to return. The return
value is empty.

Example 1:
int find_sum(int x, int y);
In the above example, find_sum is name of the function. x,y
are integer variables and those variables are the inputs for
finding sum. Later when sum function finds the result, it is
sent back. The result data type is int. Therefore the return
type is mentioned as int at the beginning of the function
declaration.
Example 2:

16
In the above example, the function named print_Message() doesn’t
take any value and doesn’t return any value. In both cases the
void keyword is used to denote the function takes nothing (empty)
and returns nothing (empty)
When declaring any variable, the programmer specifies the data
type of variable. Similarly when declaring pointer variables also
the programmer specifies the data type. Here the data type refers
the type of variable whose address is to be stored into the pointer
variable.
For example:
int *p;
In the above example, p is a pointer variable and it holds the
address of any other integer variable.
When the programmer knows the type of variable whose address
is being stored in the pointer variable prior to the declaration of
the pointer then it is fine. In some cases the programmer knows
that he/she needs a pointer variable but doesn’t know address of
which kind of variable is to be stored. In such cases the void data
type is useful. The pointer variable is declared with void initially
and later the conversion to related type is done.
void *p;

Derived data types:


The terms functions, arrays, pointers, and references are defined
based on built in data types.
 Every function returns a value. The type of return value
must be declared in function declaration.
 Arrays refer group of elements (variables) of same data
type. The data type for array must be mentioned.
 Pointer refers to the address of memory location. The
pointer variable holds the address of the memory location
of some variable. All pointers are unsigned integers. But

17
the pointers are declared with the data types of the
variables to which those pointers are pointing.
 Reference variables are the variables that act as an alias
names for other variables. The reference variables are also
declared with the existing data types only.
Hence, all the types, functions, arrays, pointers, and references
are denoted as derived types.
User defined data types:
As the name, user defined indicates, the keywords struct, union,
class, enum, and typedef allows the programmers or users to
define their own data types to represent real world objects.
1.4 Operators in C++
C++ supports wide variety of operators. Each operator is a symbol
or keyword that is used to perform an operation. The meaning of
each operator is mentioned in compiler. The user or programmer
uses the same meaning for writing the programs.
In an expression a+b, + is called operator. a and b are called
operands.
Unary operator:
If an operator takes only one operand, such operator is called
unary operator.
Examples:

Operator Meaning purpose Example


! Logical negation To negate the !(2<3) results false
(NOT) result
~ Bit-wise 1’s Inverts 0s to 1s ~(1101) results
complement and 1s to 0s (0010)
+ Unary plus To indicate the +8
positive value
- Unary minus To indicate the -8
negative value
++ Pre increment or adds 1 to the x=1; x++ (or) ++x
post Increment operand results x=2
-- Pre decrement or subtracts 1 from x=1; x-- (or) --x

18
post decrement the operand results x=0
& Address returns the &x returns
address of address of
variable memory location
where x is stored
* Indirection refers the value at *x, return value at
the address x, x is a pointer

sizeof Returns size of to know the size of sizeof(int), returns


operand in bytes variable or object the number of
bytes occupied by
int
new Dynamically Allocates and int *p;p= new
allocates memory returns starting int[3];
address
ofallocated
memory.
delete Dynamically de- releases the delete p;
allocates memory dynamically
allocated memory

Table 7 List of Unary operators


Binary operator:
If an operator takes two operands, such operator is called binary
operator.

Operator Meaning Purpose Example


* Multiply Multiplication a=2. b=4;
a*b; results 8
/ Divide returns quotient a=4, b=2;
after division a/b; results 2
a=5, b=2: a/b results
2;.
(takes only integer
part)

19
% Modulus returns remainder a=4, b=2;
after division a/b; results 0
a=5, b=2: a/b results
1;.
(remainder is the
output)
+ Binary adds to numbers a=4, b=2;
plus a+b; returns 6
- Binary subtract one a=4, b=2;
minus number from other a-b; returns 2
<< Shift left moves the binary a=0010 1001;
digits to left and a<<2; returns
fills right side gap 10100100
with zeros
>> Shift right moves the binary a=0010 1001;
digits to right and a>>2; returns
fills left side gap 0000 1010
with zeros
< Less than Compares two a=4, b=2;
numbers and a<b; returns false
returns true if op1
is less than op2.
Otherwise false
<= Less than Compares two a=4, b=2;
or equal numbers and a<=b; returns false
returns true if op1
is less than or
equals to op2.
Otherwise false
> Greater Compares two a=4, b=2;
than numbers and a>b; returns true
returns true if op1
is greater than
op2. Otherwise
false

20
>= Greater Compares two a=4, b=2;
than or numbers and a>=b; returns true
equal returns true if op1
is greater than or
equals to op2.
Otherwise false
== Equality Compares two a=4, b=2;
numbers and a==b; returns false
returns true if op1
is equal to op2.
Otherwise false
!= Not equal Compares two a=4, b=2;
to numbers and a!=b; returns true
returns true if op1
is not equal to
op2. Otherwise
false
& Bit wise works between two a = 1100
AND binary numbers b = 0101
and result is 1 if a&b=0100
both inputs are 1
other wise zero
^ Bit wise Works between a = 1100
XOR two binary b = 0101
numbers and a^b=1001
result is 1 if any of
input is 1 and
other is 0.
¦ Bit wise works between two a = 1100
OR binary numbers b = 0101
and result is 0 if a|b=1101
both inputs are 0
other wise 1
&& Logical Evaluate the result a=2, b=4,c=3;
AND when two ((a<b) && (a<c)) is
conditions are
true ((a>b) &&(a<c)) is
joined. The result
is true, if the false ((a<b)&&(a>c)) is
result of both false (((a>b)&&(a>c)) is
conditions are true false

21
¦¦ Logical OR Evaluate the result a=2, b=4,c=3;
when two ((a<b) ¦¦ (a<c)) is true
conditions are ((a>b) ¦¦ (a<c)) is true
joined. The result ((a<b) ¦¦ (a>c)) is true
is false, if the ((a>b) ¦¦ (a>c)) is false
result of both
conditions are
false
= Simple assigns right hand a=3;
assignment side value to left
hand side variable
*= Assign multiplies the left a=3;
product hand side value a*=2; results 6
with right hand
side value and
stores the result in
left hand side
variable
/= Assign divides the left a=3;
quotient hand side value a/=2; results 1
with right hand
side value and
stores the quotient
in left hand side
variable
%= Assign divides the left a=11;
modulus hand side value a%=3; results 2
with right hand
side value and
stores the
remainder in left
hand side variable
+= Assign adds the left hand a=3;
sum side value with a+=2; results 5
right hand side
value and stores
the result in left
hand side variable

22
-= Assign subtracts the left a=3;
difference hand side value a-=2; results 1
with right hand
side value and
stores the result in
left hand side
variable
, Evaluate separates two x=(y=3, y+4); x holds 7
expression.

Table 8 : List of Binary Operators.


Ternary operator:
If an operator takes three operands, such operator is called
ternary operator.
Example :

Operator Meaning General form Example


?: Works like (Conditon ? big = (a>b ? a : b)
simple if – True_Exp :
else False_Exp)

Table 9: Ternary operator


Precedence and Associativity of Operators
The terms precedence, priority, and rank refers the same. In C++
every operator has rank. When an expression contains more than
one operator, the rank is used to decide which operation has to be
carried out first. When an expression is having two or more
operators with the same rank then in which direction the
operators have to be selected is the issue. This direction in which
the compiler selects the operators when the operators have same
rank is called associativity.
The precedence and associativity of operators in C++ are given
below:

Rank Associativity operators


1 Left to right () [] -> :: .

23
Sizeof
2 Right to left ! ~ + - ++ -- & * new
delete
3 Left to right * / %
4 Left to right + -
5 Left to right << >>
6 Left to right < <= > >=
7 Left to right == !=
8 Left to right & ^ ¦
9 Left to right && ¦¦
10 Right to left ?:
11 Right to left = *= /= %= += -=
12 Left to right ,

1.5 Expressions in C++


A Program consists group of instructions in sequence. An
expression is a kind of instruction in program. In general, a
program includes the instructions like data declaration,
input/output, arithmetic/logical and control instructions.
Arithmetic instructions/expressions are algebraic expressions
that are written according to C++ syntax. Simply an arithmetic
Expression is a combination of variables, constants and operators
written according to the grammar rules of C++ language.
Example:

Algebraic expression C++ expression


y=x2+2 y=(x*x)+2
a=lb a=l*b
ax2+bx+c a*(x*x)+b*x+c
Table 10: Expressions in C++
Logical instructions/Expressions are formed with relational
and/or logical operators and operands. In C++ every expression
evaluates to a value. Arithmetic expressions returns numeric
values. Where as logical expression return either true or false.
Example: Let a=5, b=8

24
Logical Expression result
a>b false
a<b True
a==b False
a!=b True
Type Conversion.
Type conversion is also called as Typecasting. It refers conversion
of type. Typecasting is essential when the values of variables are
to be converted from one type to another type. C++ allows implicit
as well as explicit conversion.
Implicit Type Conversion
The type conversion is carried out when the expression contains
different types of data items. When the compiler carries such type
conversion itself by using in built data types then it is called
implicit type conversion. The variable of lower type (small range)
type when converted to higher type (large range) is known as
promotion. When the variable of higher type is converted to lower
type, it is called demotion.
The below table describes various implicit type conversion rules
that a compiler follows.

Argument 1 Argument 2 Argument 3


char int Int
int float Float
int long Long
double float double
int double double
long double double
int unsigned unsigned

Example:
#include<iostream.h>
void main()
{
int a,b;
float c;

25
a=3;
b=2;
c=a/b;
cout<<"c="<<c;
}
Output
c=1

Explanation: quotient for division between a and b is 1.5, but the


output is 1. This is because of implicit conversion.
Explicit typecasting
Sometimes errors may be encountered in the program with
implicit typecasting as shown in below program. The desired type
can be achieved by typecasting a value of particular type. The
following is the syntax of typecasting in C++.
(data-type name) expression;
Example :
#include<iostream.h>
void main()
{
int a,b;
float c;
a=3;
b=2;
c= (float) a/b;
cout<<"c="<<c;
}

Output
c=1.5

Explanation: Here the result of the expression is taken in float by


explicit conversion. Hence c=1.5 is printed.

26
1.6 Control Structures

A program is a sequence of statements given to a computer to


solve a particular task. In general when solving simple tasks that
involves only calculation, the single sequence is enough in
accomplishing the task. For example, when user wishes to
perform some arithmetic operation, the sequence is as follows:
 Declare the data items (variables)
 Get the input values
 Perform the calculation
 Show the results
In above case, the program executes in sequence and finally the
task will be performed.
When solving real world problems, all the problems can’t be
solved only with single sequence. It means some problems involve
various conditions; some other problems involve repeated
execution of some set of instructions. In some cases, the control of
the program needs to be shifted to out of the block.
Based on the requirements of solving various problems, designers
introduced various controls in the sequence of execution. Such
control statements can be divided as follows:
 Conditional Control Statements.
 Loop Control Statements
 Jump Control Statements
Conditional Control Statements
If the condition is true, some set of statements are executed,
otherwise the other set of statements are executed. Conditional
control statements can also be referred as Decision control or
conditional branching statements. if and else are the two
keywords used in implementing conditional control. The
conditional control statements can be implemented in different
ways:

27
 Using if
 Using if and else
 Nesting of if-else
 if-else-if in a sequence
Using if
When a user wants to execute one or more statements only when
given condition is true, then if statement is used. Flow of
execution with if statement is shown below.

Figure 11: Flow control with if statement


General form of if statement
if (condition)
{
Statements;
}

Explanation:
Statements get executed only when the condition is true. Braces
are not necessary if only one statement is related to the condition.
if(condition) is not terminated with semicolon.

28
Example:
Suppose a merchant wants to give 10% concession only when the
bill amount is greater than or equal to 1000. If the bill amount is
less than 1000, then there is no concession. In this kind of
situations, if statement is useful. The below code demonstrates
use of if statement.

1 /* Program to demonstrate if statement */


2 #include<iostream.h>
3 #include<conio.h>
4 int main()
5 {
6 float bill_amt;
7 clrscr();
8 cout<<"enter bill amount ";
9 cin>>bill_amt;
10 if(bill_amt>=1000)
11 {
12 bill_amt=bill_amt-(0.1*bill_amt);
13 }
14 cout<<"bill amount = "<<bill_amt;
15 return 0;
16 }
Run 1:

Run 2:

Explanation:In line no. 6, bill amount is declared.In line no. 9,


the value of bill amount is entered through keyboard. In line no.
10 , the bill amount is compared with 1000, if bill amount is
above 1000 or equal to 1000, the concession 10% is deducted
from bill amount. In line no. 12 finding and deducting the
concession is done. In line no. 14 bill amount is printed. Here the
concession is applicable only when bill amount is above 1000 or
equal to 1000. In line 10, if is a keyword, followed by a condition.

29
The if statement is not terminated with semi colon.The statements
after if will be executed only if the condition is true. Otherwise no
effect. The program is run twice and the output is shown above.
In Run1, the amount is less than 1000 so no concession applied.
But in other case the amount is 1200. After concession the
amount has become 1080.
Using if and else
In a problem, when there are two options, and only one option has
to be selected, based on condition, in such cases if and else is
used. if, else are two keywords. if is always followed by a
condition and for every else there will be an if statement. When
the condition mentioned with if is false, the statements after
else are executed. The flow of execution in if-else statement is
shown below:

Figure 12: flow control with if-else statement


General form of if-else statement
if (condition)
{
Statements;
}
else

{
Statements;
}

30
Explanation:

Statements in if block get executed only when the condition is


true and statements in else block get executed only when
condition is false. if and else statements are not terminated with
semicolon.
Example
Suppose a merchant wants to give 10% concession when the bill
amount is greater than or equal to 1000.If the bill amount is less
than 1000, then there is a concession of 5% on bill amount. For
this kind of situations the if-else statement is useful. The below
code demonstrates use of if statement.
1 /* Program to demonstrate if-else statement */
2 #include<iostream.h>
3 #include<conio.h>
4 int main()
5 {
6 float bill_amt;
7 clrscr();
8 cout<<"enter bill amount ";
9 cin>>bill_amt;
10 if(bill_amt>=1000)
11 {
12 bill_amt=bill_amt-(0.1*bill_amt);
13 }
14 else
15 {
16 bill_amt=bill_amt-(0.05*bill_amt);
17 }
18 cout<<"bill amount = "<<bill_amt;
19 return 0;
20 }
Run 1:

31
Run 2:

Explanation:In line no.6 bill_amt is declared. In line no. 9


bill_amt is entered. In line no. 10 bill_amt is compared with 1000,
if the condition is true then concession is taken as 10% and
bill_amt is computed in line 12. Other wise the concession is 5%
and bill_amt is computed in line 16. At the end in line no. 18 the
bill_amt is displayed.
Nesting of if-else
In some problems, the conditions may include some other
conditions. In such cases simple if or if-else statements are not
enough to solve the problems. So the programmers nest the if
statement or if-else statement with in other if statement or if-else
statements. According to the problem, the nesting occurs.
Below diagram shows one of the different ways of nesting if-else
statements. In general, based on the problem, the nesting occurs
in different ways.

Figure 13: Nested if – else statement

32
General form of nesting of if-else statement:
if(condition1)
{
if (condition2)
{
Statements21;
}
else
{
Statements22;
}
}
else
{
if (condition3)
{
Statements31;
}
else
{
Statements32;
}
}
Explanation:
Statements21 get executed only when condition1 and condition2
are true. Statements22 get executed only when condition1 is true
and condition2 is false.
Statements31 get executed only when condition1 is false and
condition3 is true.
Statements32 get executed only when condition1 and condition3
are false.
There is no standard method for nesting of if-else statements.
Based on the problem statement nesting occurs
Example: Nested if-else statement is best explained with the
problem of determining the biggest in 3 numbers.The code for
determining biggest in 3 numbers is given below.
33
/* A program to determine biggest in 3 numbers using nested if-else*/
#include<iostream.h>
#include<conio.h>4
int main()
{
int num1,num2,num3, big;
clrscr();
cout<<"enter 3 numbers";
cin>>num1>>num2>>num3;
if(num1>num2)
{
if(num1>num3)
{
big=num1;
}
else
{
big=num3;
}
}
else
{
if(num2>num3)
{
big=num2;
}
else
{
big=num3;
}
}
cout<<"\n big="<<big; return 0;
}

Run

Explanation: In line no.9, 3 numbers are entered. In line no. 10


condition1 is mentioned. num1 and num2 are compared.
If condition1 is true, condition 2 is tested in line no 12. If
condition1 is false, condition 3 is tested in line 23. Finally the
output is displayed with line 32.

34
if-else-if in a sequence
When a solution to a problem needs sequence of conditions, if-
else-if is used in a sequence. In the sequence of conditions,
when a condition evaluates to true the remaining conditions will
not be executed.
The below diagram shows flow control, when if-else-if
statements are used in a sequence.

Figure 14if-else-if statements in a sequence


General form for if-else-if statement:
if (condition1)
{
statements
}
else if (condition2)
{
statements
}
else if (condition3)
{
statements

35
}
.
.
.
else
{
statements
}
Explanation:
Statements get executed in if blocks only when the corresponding
conditions are true. Statements in else block get executed when
all other conditions are false.
Example: When a problem involves a sequence of conditions, if-
else-if statements are used. The below program demonstrates if-
else-if statements. In this program, the grade obtained by a
student is displayed when the student marks are entered. To
determine the grade, a series of the conditioned are involved.
1 /*program to demonstrate if-else-if
statement sequence*/
2 #include<iostream.h>
3 #include<conio.h>
4 int
main() 5 {
6 int marks;
7 clrscr();
8 cout<<"enter the marks";
9 cin>>marks;
10 if(marks>=80)
11 cout<<"A Grade";
12 else if(marks>=60)
13 cout<<"B Grade";
14 else if(marks>=40)
15 cout<<"C Grade";
16 else
17 cout<<"D Grade";
18 return
0; 19 }

36
Run

Explanation :In line no. 9, student marks are entered. Line no.
10,12,14 compared marks with certain required marks to
determine the grade. Based on student marks, among A,B,C,D
grades, only one grade is printed for corresponding marks.

37
Program to find roots of quadratic equation
1/* a program to find roots of quardratic
equation */
2 #include<iostream.h>
3 #include<conio.h>
4 #include<math.h>
5 main()
6 {
7 float a,b,c,d,r1,r2,real,img;
8 clrscr();
9 cout<<"\n enter a,b,c
values:"; 10 cin>>a>>b>>c;
11 d=(b*b)-4*a*c;
12 if(d>0)
13 {
14 cout<<"\n roots are real and
unequal"; 15 r1=(-b+sqrt(d))/(2*a);
16 r2=(-b-sqrt(d))/(2*a);
17 cout<<"\n root1=
"<<r1<<"root2="<<r2; 18 }
19 else if(d==0)
20 {
21 cout<<"\n roots are real and
equal"; 22r1=-b/(2*a);
23 cout<<"\n root1= root2=
"<<r1; 24 }
25 else
26 {
27 d=abs(d);
28 cout<<"\n roots are imaginary";
29 real=-b/(2*a);
30 img=sqrt(d)/(2*a);
31 cout<<"\n root1= "<<real<<"+i"<<img;
32 cout<<"\n root1= "<<real<<"-
i"<<img; 33 }
34 return 0;
35 }

38
Output:

Explanation:In line number 10, a,b,c values are entered (for the
equation form ax2+bx+c). In line no 11, d = b2 - 4ac is found where
d is called "discriminant". In line 12, d value is compared with 0
and if d>0 the roots are real and unequal. Line 19 checks whether
d is zero, the real roots which are equal are printed in line 23. and
from line 25 -32 the code is written to print imaginary roots.

switch – case statement:


It is similar to sequence of if-else-if statements. When there are
several options to select one among them switch-case statement is
used. The readability and understandability of a program may be
effected when too many if-else-if statements are used. To avoid
such situation the programmers can use switch case statement.
While working with switch-case statement, in general four
keywords are used. switch, case, default and break. The usage of
keywords is as follows:
 switch is followed by an expression, the expression
evaluates to an integer. Even if the expression is character
expression, the ASCII value of the character is considered.
 Based on value of the expression mentioned in the
switch, the related statements are executed. It means the
statements are selected where the switch expression is
matched with the case label.
 Possible cases are mentioned. Each case is mentioned
with the keyword case followed by label. Each label is
integer expression and terminated with colon. The
statements followed by case are executed when the case
label matches with the switch expression. After the
statements under case a break statement is used to
terminate process. Otherwise the statements under other
cases will be executed.
 If no case label matches with switch expression, the
statements under default will be executed. The default
section can be mentioned anywhere in the switch block.

39
But in general the default statement is mentioned at the
end of switch block. When it is mentioned at the end the
programmers need not mention break statement for the
default section.
The flow control in switch-case statement is given below:

Figure 15Flow control in switch-case statement


General form for switch-case statement:
switch(variable)
{
case constant1: statement1
break;
case constant2: statement2
break;
case constant3: statement3
break;
.
.
.
default: statements
break;
}

40
Explanation:
Switch statement is similar to if else if statement. Statement 1
gets executed when the variable is equal to constant1 and so on.
Control comes to default portion when all the constants, which
have been mentioned do not match with the variable. Here break
and default are optional. When there is no break for a case it
continues till it encounters break or the end of the switch.
Example:To select one among multiple options, switch case
statement is useful. The below program demonstrates switch-case
statement.
1 /*program to demonstrate switch-case statement */
2 #include<iostream.h>
3 #include<conio.h>
4 int
main() 5 {
6 int marks;
7 clrscr();
8 cout<<"enter the marks";
9 cin>>marks;
10 marks=marks/10*10;
11 switch(marks)
12 {
13 case 100:
14 case 90:
15 case 80:
16 cout<<"\n A Grade";
17 break;
18 case 70:
19 case 60:
20 cout<<"\n B Grade";
21 break;
22 case 50:
23 case 40:
24 cout<<"\n C Grade";
25 break;
26 default:
27 cout<<"\n D
Grade"; 28 }

41
29 return 0;
30 }

Run :

Explanation : In line no. 9 marks are entered. In line no. 10


marks are normalized to an integer. In line 11 switch followed by
an expression is given. The expression is integer. Now the possible
cases are mentioned with case labels. When the marks match
with case label the statement under that label is executed. if
marks are 86, the normalized marks are taken as 80. For 80 the
grade is A.
Loop control statements
In some cases, while giving solution to a problem using program,
the programmer needs to execute one or more instructions many
times. For this instead of writing the same set of instructions
repeatedly, the designers introduced a technique with which the
programmer mentions the instruction or set of instructions only
once. But the instruction(s) execute for several times based on the
condition mentioned.
The term loop refers repetition. In programming, loop refers set of
instructions that are mentioned to execute repeatedly until the
specified condition for repetition becomes false.
C++ supports 3 types of loops
 while loop
 do while loop
 for loop
while loop
while is a keyword. while followed by condition includes a block
of statements. It means that while the condition is true the
statements mentioned under while have to be executed. And when

42
the condition becomes false the control reaches to next statement
after while.

In while loop, the condition is tested first and the statement(s) are
executed only when the condition is true. As condition is tested at
the top, it called top tested loop or entry controlled loop. In this
the minimum number of iterations for statements execution may
be zero. It means the loop statements will not be executed if the
condition is false in the first iteration.
The below diagram shows the flow of control in while loop.

Figure 16: Flow control in while loop


General form for while loop:
while(condition)
{
statements
}

43
Explanation:
Statements get executed as long as the condition is true. It checks
condition first and executes the statements later.

Example:
1 /*program to demonstrate while loop*/
2 #include<iostream.h>
3 #include<conio.h>
4 int main()
5 {
6 int count=0; //loop counter
7 clrscr();
8 while (count<=5)//condition
checking 9{
10 cout<<"Hello C++"<<endl;
//statement to be repeated.
11 count++;// updating counter value
12 }
13 cout<<"Bye";//statement after while loop
14 return 0;
15 }
Run:

Explanation:
In line number 6, loop counter is initiated.In line number 8, loop
condition is mentioned. In line numbers 9-12 body of the loop is
mentioned. When the loop condition becomes true line 10 and 11
are executed otherwise the control reaches to line 13.
do while loop
do is a keyword. It refers to execute the following statements. At
the end of the do loop, while condition is mentioned. If the
condition is true, the statements after do are executed again.

44
Otherwise the loop is terminated and the control goes to the next
statement of the do loop.
The difference between while loop and do while loop is the position
of loop condition. In while loop the condition for repetition is
mentioned at the top of the loop where as in do while loop the
condition is mentioned at the bottom of the loop. So do while is
called exit controlled loop or bottom tested loop. In do while loop
the statements mentioned in loop are executed at least once
irrespective of the loop condition. So the minimum number of
iterations for executing the loop statements is 1.
The below diagram shows the flow of control in do while loop.

Figure 17 Flow control in do-while loop


General form for do-while loop
do
{
statements
} while(condition);

45
Explanation:
Statements get executed as long as the condition is true except for
the first time. It executes the statements first and checks the
condition later.
Example :
The below diagram shows the flow of control in do while loop.
1 /*program to demonstrate do while loop*/
2 #include<iostream.h>
3 #include<conio.h>
4 int main()
5 {
6 int count=0; //loop counter
7 clrscr();
8 do
9 {
10 cout<<"Hello C++"<<endl;
//statement to be repeated.
11 count++;// updating counter value
12 }while(cout<=5); //loopcondition
13 cout<<"Bye";//statement after do while loop
14 return 0;
15 }
Run:

Explanation
In line number 6, loop counter is initiated. In line number 8, loop
begins. In line numbers 9-12 body of the loop is mentioned. when
the loop condition becomes true, line 10 and 11 are
executedotherwise the control reaches to line 13. In first iteration,
the loop executes irrespective of condition.

46
Difference between while and do while loops
while loop:
 while loop gets executed as long as the condition is true
 Condition is evaluated first and then statements.
 Minimum number of execution in this case is zero.
do while loop:
 do while loop gets executed as long as the condition is
true, but not in case of first time execution
 Statements get executed first and then condition is
checked
 Minimum number of execution in this case is one
For loop
Programmers use while and do while loops for executing group
of statements repeatedly based on the users choice. for loop is
also a loop but it is used for executing the statements repeatedly
when the number of repetitions is specifically known. This is the
general tendency. But the users can use any loop to repeat the
execution of statements.
In a for loop, three statements are mentioned:

1. Initialization
2. Condition
3. Update

 Initialization statement is executed only once when the


loop execution begins.
 Condition statement is executed until the condition
becomes false
 For every iteration the loop counter is updated in update
statement.
The below diagram shows the flow of control in for loop.

47
Figure 18 flow control in for loop
General form of for loop
for(initialization ; condition; updation)
{
Statements
}
Explanation:
Statements get executed as long as the condition is true.
Initialization is done only once and update of loop counter is done
for every iteration.
Example:
1 /*program to demonstrate for loop*/
2 #include<iostream.h>
3 #include<conio.h>
4 int
main() 5 {
6 clrscr();
7 for(int count=0; count<=5;count++)
// initialization, condition, update
8 {
9 cout<<"Hello C++"<<endl;
//statement to be repeated.
10 }

48
11 cout<<"Bye";//statement after for loop
12 return
0; 13 }
Run:

Explanation
In line number 7, for is mentioned. The statement in line number
9 will be repeated until the condition becomes false. When the
number of repetitions is well known, for loop is best for writing
the program.
Nested Loop.
Using a loop within another loop is called nested loop. In general
programmers use nested for loops. Even while and do while loops
can be nested. The nested loops are generally used to construct
two dimensional or multi dimensional data. When two
dimensional data is to be manipulated, two loops are nested. The
outer loop counts the rows and inner loop counts columns.
General for of nesting two for loops
for (initializing ; test condition ; increment /
decrement)
{
statement;
for (initializing ; test condition ; increment /
decrement)
{

body of inner loop;


}
Statement;
}

49
Example:
1 /*program to demonstrate nested loop*/
2 #include<iostream.h>
3 #include<conio.h>
4 int main()
5 {
6 clrscr();
7 int row, col;
8 for(row=1; row<=4;row+
+) 9 {
10 for(col=1;col<=4;col++)
11 cout<<"*"<<" ";
12 cout<<endl;
13 }
14 return
0; 15 }
Run:

Explanation:
Outer loop is mentioned in line number 8, it counts the rows and
inner loop is mentioned in line number 10, it counts the columns.
For every row there are four columns. And 4 rows are taken with
outer loop. Finally 4 X 4 = 16 asterisks are printed.
break statement
break statement terminates the loop and moves the control to
next statement of the loop in which break statement is added.
break in any loop is not mentioned directly. break is always
mentioned after condition. When the condition is true, break will
be executed and the corresponding loop terminates.
Break statement is also used switch case statement. Among
multiple cases when particular case is executed conditionally, the
other cases should not be executed. In that context the break
statement is useful. If break statement is mentioned for each
case, after particular case the break terminates the execution of
other cases.
50
Below diagram shows the flow control with the break statement.

Figure 19Flow control with break statement


Example:
1 /*program to demonstrate break statement*/
2 #include<iostream.h>
3 #include<conio.h>
4 int
main() 5 {
6 clrscr();
7 int i=5;
8 while(i<=50)
9 {
10 cout<<"i="<<i<<endl;
11 if(i%4==0)//condition for break
12 break;
13 i+=5; //updating i
value 14 }
15 return 0;
16 }

51
Run:

Explanation: In line 7, i value is taken as 5. In line 8 while loop


condition is mentioned to run the loop upto i value becomes 50.
But the output shown is only 20. It means, break at line 12
terminated while loop. Here the condition is when i value is
divisible by 4 the break executes. So when i value is reached to
20, the loop is terminated.
Continue statement
continue statement moves the control to the beginning of the loop
in which it is mentioned. continue statement in any loop is not
mentioned directly. It is mentioned after a conditon. When the
condition is true, continue will be executed and the corresponding
loop will be executed from the beginning by leaving the statements
after continue statement in the loop.
The below diagram shows the flow control with the continue
statement.

Figure 20flow controlwith continue statement

52
Example:
1 /*program to demonstrate continue statement*/
2 #include<iostream.h>
3 #include<conio.h>
4 int main()
5 {
6 clrscr();
7 int i=0;
8 while(i<=50)
9 {
10 i+=5; //updating i value
11 if(i%4==0)//condition for continue
12 continue;
13 cout<<"i="<<i<<endl;
14 }
15 return 0;
16 }
RUN:

Explanation: The program is written to print multiples of 5. And


the number which is divisible by 4 is exempted from printing. In
line number 7, i value is taken as 0. In line 10, i value is updated.
In line 11, Condition for checking whether the number is divisible
by 4 or not is mentioned. In line 12, the continue statement
moved the control to beginning of the loop. Because of that reason
20 is exempted from printing.
goto statement.
goto is a keyword. goto control statement moves the control either
forward or backward in the program. It means goto moves the
53
control to specified label. goto can be mentioned with condition or
without condition.
Two ways of using goto statement is shown below:
a) Jumping forward:
statement1
goto label;
statement 2
label:
statement 3
Explanation:
statement2 gets omitted because after statement1,goto moves the
control to the labeled statement i.e. statement 3
b) Jumping back:

statement 1
label:
statement 2
goto label;
statement 3
After statement1, statement 2 gets executed for infinite times,
because goto moves the control to statement 2 repeatedly.
Example:
1 /*program to demonstrate goto statement*/
2 #include<iostream.h>
3 #include<conio.h>
4 int main()
5 {
6 clrscr();
7 abc:
8 cout<<"enter a number: "<<;
9 cin>>n;
10 if(n<0)
11 goto abc;
12 else
13 cout<<"square root of "<<n<<" is"<<sqrt(n);
14 return0;
15 }

54
Run:

Explanation: In line number 7, label for goto is mentioned. And in


line 11, goto statement is mentioned. if the number is negative,
then it asks for entering other number. Otherwise it finds and
displays the square root of given number.
Reason to Avoid goto Statement
Goto statement can move the control back and forward from the
current location. This kind of shifting leads to unexpected errors.
And such errors are sometimes very difficult to debug.
A program to print even number between 0 and 20.
1 /* a program to print even numbers
between 1 to 20 */
2 #include<iostream.h>
3 #include<conio.h>
4 int main()
5 {
6 clrscr();
7 int i=0;
8 while(i<=20)
9 {
10 if(i%2==0)
11 cout<<i<<"";
12 i++;
13 }
14 return 0;
15 }

OUTPUT

Explanation :
In line number 9, while loop is written to run for 21 times. Line
number 10 checked whether the number is even or odd. Line 11,
printed the value if it is even. Line 12 updates the loop counter.
55
A program to find reverse of a given number.
/* a program to print reverse of given number */
#include<iostream.h>
#include<conio.h>
int main()
5{
clrscr();
int num,rev,rem;
cout<<"enter a number :";
cin>>num;
rev=0;
while(num!=0) 12{
rem=num%10;
rev=rev*10+rem;
num=num/10;
16}
cout<<"reverse number is :"<<rev;
return 0; 19 }
Output

Explanation : In line number 9, a number is entered. Let the


number is num. and the value is 342. Line number 13 to 15 will
show the output as follows
Iteration 1:
num rev rem
342 0 342%10=2
rev=rev*10+rem
=0*10+2=2
num=num/10
=342/10
34
Iteration 2:
num rev rem
34 2 34%10=4
rev=rev*10+rem

56
=2*10+4=24
num=num/10
=34/10
3
Iteration
3:

num rev rem


3 24 3%10=3
rev=rev*10+rem
=24*10+3=243
num=num/10
=3/10
0
Loop discontiues

A program to check whether the given is palindrome or not


1 /* a program to check whether given number
is polyndrome*/
2 #include<iostream.h>
3 #include<conio.h>
4 int main()
5 {
6 clrscr();
7 int num,rev,rem,aux;
8 cout<<"enter a number :";
9 cin>>num;
10 aux=num;
11 rev=0;
12 while(num!=0)
13 {
14 rem=num%10;
15 rev=rev*10+rem;
16 num=num/10;
17 }
18 cout<<"reverse number is :"<<rev;
19 if(aux==rev)
20 cout<<"\n Given number "<<aux<<" is "
<<"polyndrome";
21 else
22 cout<<"\n Given number "<<aux
57
<<" is "<<"not polyndrome";
23return 0;
24}
OUTPUT:

Explanation : The above program is similar to reverse of a


number program. But only the difference is if given number and
reversed number is same, then it displays palindrome. Otherwise
not palindrome is displayed.
Program to check whether given number is perfect or not.
1. /* a program to check whether given number is
perfect or not*/
2. #include<iostream.h>
3. #include<conio.h>
4. int main()
5. {
6. clrscr();
7. int num,i,sum;
8. cout<<"enter a number :";
9. cin>>num;
10. i=1;
11. sum=0;
12. while(i<num)
13. {
14. if(num%i==0)
15. sum=sum+i;
16. i++;
17. }
18. if(sum==num)
19. cout<<"\n Given number "<<num<<" is "
<<"perfect";
20. else
21. cout<<"\n Given number "<<num<<" is "
<<"not perfect";
22. return 0;
23. }

58
Output

Explanation : i begins with 1 and increases upto num(excludes


num).for each value of i , num is divided by i and if the remainder
is zero then i value is added to sum. At the end sum and num are
compared. if both are equal then num is treated perfect number.
A program to check whether the given number is prime or not.
1 /* a program to check whether given number is prime
or not*/
2 /* prime number is a number that has only 2
factors i.e.1 and itself*/
3 #include<iostream.h>
4 #include<conio.h>
5 int main()
6 {
7 clrscr();
8 int num,i,count;
9 cout<<"enter a number :";
10 cin>>num;
11 i=1;
12 count=0;
13 while(i<=num)
14 {
15 if(num%i==0)
16 count=count+1;
17 i++;
18 }
19 if(count==2)
20 cout<<"\n Given number "<<num<<" is "<<"prime";
21 else
22 cout<<"\n Given number "<<num<<" is "
<<"not prime";
23 return 0;
24 }

59
Output

Explanation : i begins with 1 and increases upto num. For each


value of i, num is divided by i and if the remainder is zero then
count is increased. At the end count is checked. if the count is
two, then the given number is prime otherwise it is not prime.
A program to find factorial of a given number
1 /* a program to find factorial of a given number*/
2 #include<iostream.h>
3 #include<conio.h>
4 int
main() 5 {
6 clrscr();
7 long num,fact,i;
8 cout<<"enter a number :";
9 cin>>num;
10 fact=1;
11 for(i=1;i<=num;i++)
12 fact=fact*i;
13 cout<<"factorial of "<<num<<"is"<<fact;
14 return
0; 15 }
Output

Explanation :value i begins with 1 and increases upto num. the


value fact is also taken as 1. Each time fact is multiplied with i
value. At the end the fact is the output.
Example

60
i f f*i
1 1 1
2 1 2
3 2 6
4 6 24
5 24 120
A program to check whether given number is Armstrong
or not

1 /* a program to check whethergiven number


is armstrong or not*/
2 /* In a number if the sum of cubes of digitsis
equal to that number then the number is
called armstrong number*/
3 #include<iostream.h>
4 #include<conio.h>
5 int
main() 6 {
7 clrscr();
8 int num,sum,rem,aux;
9 cout<<"enter a number :";
10 cin>>num;
11 aux=num;
12 sum=0;
13 while(num!=0)
14 {
15 rem=num%10;
16 sum=sum+(rem*rem*rem);
17 num=num/10;
18 }
19 if(aux==sum)
20 cout<<"\n Given number "<<aux
<<" is "<<"armstrong";
21 else
22 cout<<"\n Given number "<<aux
<<" is "<<"not armstrong";
23 return
0; 24 }

61
output

Explanation:
In line number 15, a digit from the number is taken and line
number 16, the cube of that number is found and added to sum.
In the same way in every iteration one digit is taken and the cube
is found. Cubes of the digits is added to sum. At the end the sum
and given number is compared. if both are same then the output
is displayed as Armstrong number otherwise not Armstrong
number is printed.
A program to find sum of the digits in a number
1. #include<iostream.h>
2. void
main() 3. {
4. int n, n1, sum = 0;
5. cout << "Enter a number : ";
6. cin >>
n;
7. n1=n;
8. while (n !=
0) 9. {
10. sum = sum + n %
10; 11. n = n / 10;
12. }
13. cout << "sum of the digits
in" 14. << n1 << " is " << sum;
15. }

A program to print prime numbers between num1 and num2.


/* a program to print prime number between num1 and num2*/
#include<iostream.h>
#include<conio.h>
int main()

62
5. {
6. clrscr();
7. int num1,num2,i,count;
8. cout<<"enter num1 :";
9. cin>>num1;
10. cout<<"enter num2";
11. cin>>num2;
12. while(num1<=num2)
13. {
14. i=1;
15. count=0;
16. while(i<=num1)
17. {
18. if(num1%i==0)
19. count=count+1;
20. i++;
21. }
22. if(count==2)
23. cout<<num1<<" ";
24. num1++;
25. }
26. return 0;
27. }

Output

Explanation : Prime number checking logic is used in nested


loop. Line number 14 to 23 are checking for prime or not. The
logic is nested in another while loop between 12 and 25.

A program to print Armstrong numbers between num1


and num2.

/* a program to print armstrong number between


num1 and num2*/
#include<iostream.h>

63
4 #include<conio.h>
5 int
main() 6 {
7 clrscr();
8 int num1,num2,sum,rem,aux;
9 cout<<"enternum1 :";
10 cin>>num1;
11 cout<<"enter num2:";
12 cin>>num2;
13 while(num1<=num2)
14 {
15 aux=num1;
16 sum=0;
17 while(aux!=0)
18 {
19 rem=aux%10;
20 sum=sum+(rem*rem*rem);
21 aux=aux/10;
22 }
23 if(num1==sum)
24 cout<<num1<<"";
25 num1++;
26 }
27 return 0;
28 }

Output:

Explanation: Armstrong number checking logic is used in nested


loop. Line number 17 to 24 are checking for Armstrong or not.
The logic is nested in another while loop between 13 and 26.
A program to find sum of the digits in a given number.
1. #include<iostream.h>
2. void
main() 3. {
4. int n, n1, sum = 0;

64
5. cout << "Enter a number : ";
6. cin >>
n;
7. n1=n;
8. while (n !=
0) 9. {
10. sum = sum + n %
10; 11. n = n / 10;
12. }
13. cout << "sum of the digits
in" 14. << n1 << " is " << sum;
15.
Output: }

A program to find smallest & largest numbers in a list.


1. #include<iostream.h>
2. void main
() 3. {
4. int list[10], n, i, smallest, largest;
5. cout << "\n Enter the number elements of
the array : ";
6. cin >> n;
7. cout << "\n Enter the elements of the array :
"; 8. for (i = 0; i < n; i++)
9. cin >> list[i];
10. largest = list[0];
11. for (i = 0; i < n; i++)
12. {
13. if (largest < list[i])
14. largest = list[i];
15. }
16. smallest = list[0];
17. for (i = 0; i < n; i+
+)
18. {
19. if (smallest > list[i])
20. smallest = list[i];
21. }

65
<< largest<<endl;
23. cout << " Smallest element : "
<< smallest<<endl;
24. }

Output

1.7 Arrays
An Array is linear, homogeneous data structure whose elements
are stored in adjacent memory locations. Arrays are called
subscripted variables or indexed variables. The array elements are
accessed using index or subscript.
Types of Arrays:
 One-dimensional Array or linear array: it requires only
one index to access an element.
 Two-Dimensional Array: It requires two indices to access
an element.
 Multidimensional Array: It requires two or more indices to
access an element.
Indices of array are integer numbers.
In C/C++/Java index starts from 0, i.e the smallest index of array
is 0.
In C/C++/Java index are written in brackets [ ].
Representation of One-dimensional array in memory:
Suppose name of linear array is arr and it has 5 elements. Then
its elements are represented as:

66
arr[0] arr[1] arr[2] arr[3] arr[4].
Representation of two dimensional array in memory:
Suppose name of two-dimensional array is P and it has 4 rows
and 4 columns. Then its elements are represented as:

P[0][0] P[0][1] P[0][2] P[0][3]


P[1][0] P[1][1] P[1][2] P[1][3]
P[2][0] P[2][1] P[2][2] P[2][3]
P[3][0] P[3][1] P[3][2] P[3][3]

Elements of two-dimensional arrays are stored in two ways:


1. Column major order: Elements are stored column by column,
i.e. all elements of first column are stored, and then all elements
of second column stored and so on.
P [0][0] P [1][0] P [2][0] P [3][0] P [0][1] P [1][1] P [2][1] P [3][1]
P [0][2] P [1][2] P [2][2] P [3][2] P [0][3] P [1][3] P [2][3] P [3][3]
2. Row major order: Elements are stored row by row, i.e. all
elements of first row are stored, and then all elements of second
row stored and so on.
P [0][0]P [0][1]P [0][2]P [0][3] P [1][0]P [1][1]P [1][2]P [1][3]
P [2][0]P [2][1]P [2][2]P [2][3] P [3][0]P [3][1]P [3][2]P [3][3]

Representation of n dimensional array in memory:


1 D array is considered as single row
2 D array is considered as an array of arrays. It means it is
considered as a layer.
3 D array is considered as an array of 2D arrays. It means it is
considered as a cube/Cuboid.

67
Array Storage Structure:
Storage structure represents arrangement of data elements in the
memory of the computer. Array is stored contiguous memory
locations. The number of storage cells allocated to each element
depends on the data type of the array. Typically a character
occupies one byte, short integer 2 bytes, and long integer 4 bytes.

In the below example, MARK[] array of 4 elements’ storage


structure is shown. The array MARK is of short int type.

Figure 21: Array Storage Structure


In the above example, the element MARKS[0] is stored in the
address 1000, MARK[1] is stored in the address 1002 and so on.
The numbers 1000, 1002,1003,1004,1006 are called storage
addresses of array elements. The address of first element in the
array is called base address. In this example the base address of
array MARK is 1000. With the base address we can easily
compute address of any other element in the array.
To compute the address of jth element the following formula is
used:
Address (X[J]) = BASE ADDRESS + SIZE* J
Where SIZE is number of bytes occupied by an element in the
array, J is the index of the array. BASE ADDRESS is the address
of first element.

68
Using, the above formula we can directly access any of the
elements of an array. For this reason, the element of an array can
be accessed rapidly. A drawback of the contiguous storage
structure is that memory allocated is not released until program
execution is finished.
One dimensional array:
One dimensional array contains the elements in the form of a row
or a column. Here there is only subscript.
Generalform of declaring single dimensionalarray :
Type array_name[size];
Type is any datatype like int, float, or char or any other user
defined type. array_name must be valid identifier. size is a
variable of type int. Size denotes the number of elements an array
can hold.
Example: int age[5];
This array age can hold 5 integer elements.

Figure 22: One dimensional array in memory.


The first element of an array is age[0] not age[1]. This array has 5
elements and fifth is age[4] not age[5].
Array Initialization
Assigning values to array elements at the time of declaration is
called Array initialization.
For example:

int score[5] = {2, 3, 8, -3, 9};


In the above array score mentioning size 5 is not mandatory.
int score[] = {2, 3, 8, -3, 9};
The below program reads 5 integer values from the user and
prints the first and last elements.
69
1 #include<iostream.h>
2 #include<conio.h>
3 int main()
4 {
5 int n[5];
6 clrscr();
7 cout<<"Enter 5 numbers: ";
8 for (int i = 0; i < 5; ++i)
{ 9 cin>>n[i];
10 }
11 cout<<"First number: "<<n[0]<<endl;
// first elementis n[0]
12 cout<<"Last number: "<<n[4];
// last element of an array n[4]
13 return
0; 14 }
RUN

Explanation: In line 5, array n is declared with 5 elements. In line


9, elements to the array are entered. Line 11 displays first element
in the array that is n[0], and line 12 displays last element in the
array that is n[4].
Two dimensional array
An array of arrays is known as two-dimensional array. Two
dimensional arrays have 2 subscripts. In two dimensional array
the first subscript in declaration indicates number of rows and
second subscript indicates number of columns. In program
statements, when two dimensional array is used the first
subscript refers row number and second subscript refers column
number.
The general form of declaring double dimensional array:
Data _type name_of_array[No_of_rows][No_of_columns];

70
Data_type is any datatype like int, float, or char or any other user
defined type. name_of_array is a valid identifier. No_of_rows refers
maximum number of rows allowed in the array. Similarly
No_of_columns refers maximum number of columns allowed in
the array
example: int P[5][4];
Here, P is a two dimensional array. This array can hold 20
elements. It has 5 rows and each row has 4 columns.

ARRAY P WITH 5 ROWS AND 4 COLUMNS


COLUMN-1 COLUMN-2 COLUMN-3 COLUMN-4
ROW 1 P[0][0] P[0][1] P[0][2] P[0][3]
ROW 2 P[1][0] P[1][1] P[1][2] P[1][3]
ROW 3 P[2][0] P[2][1] P[2][2] P[3][3]
ROW 4 P[3][0] P[3][1] P[3][2] P[4][3]
ROW 5 P[4][0] P[4][1] P[4][2] P[5][3]

Figure 22 Double dimensional array representation


Two-dimensional array Initialization
We can initialize a two-dimensional array in more than one way
1. int test[2][3] = {2, 4, -5, 9, 0, 9};
2. int test[2][3] = { {2, 4, 5}, {9, 0 9} };
The below program displays the elements of 2 dimensional array.
1 #include<iostream.h>
2 #include<conio.h>
3 int main() {
4 clrscr();
5 int test[3][2] = {{2,-5}, {4,0}, {9, 1} };
//2D Array initialization
6 //Displaying elements of the array.
7 cout<<"\n the elemetns in the test array are:\
n"; 8 for(int i = 0; i < 3; ++i) {
9 for(int j = 0; j < 2; ++j) {
10 cout<< "test["<< i << "][" << j << "] = "
<< test[i][j]<<endl;

71
11 }
12 }
13 return 0;
14 }
Run

Explanation:In line number 5, 2D array is declared and


initialized. Line 8 works for each row and line 9 works for each
column. It is a nested loop. For each row, the given number of
columns will be considered and the elements are displayed.
Three dimensional array:
It consists of 3 dimensions.This kind of arrays are rarely used.
The below array contains 2x3x4=24 elements.
int score[2][3][4] =
{2,4,6,8,10,12,14,16,18,20,22,24,1,3,5,7,9,11,13,15,17,19,21,23};
Another way to initialize this array with same elements is as
follows
int score[2][3][4] = {

{ {2, 4, 6, 8}, {10, 12, 14, 16}, {18, 20, 22, 24} },
{ {1, 3, 5,7}, { 9,11,13,15}, {17, 19, 21, 23} }
};
Arrays as function arguments
Similar to the ordinary variables, Array elements can be sent to a
function as arguments. It is also possible to send entire array as
an argument to a function. When an array is sent to a function as
an argument, mentioning the name of an array is enough in the
function call. But mentioning the square brackets are not needed
beside the array name. In the function header again array
declaration is done. It looks like call by value parameter passing

72
technique but it is call by address technique. Even though the
operators & and * are not used explicitly, the array name itself is
a pointer. With that technique the parameter is the pointer and it
works like call by address technique. If the array parameter is
changed in the called function, as argument works like call by
reference parameter, the change will be found in the caller
function.
Example : display(marks);//marks is name of the array
The code demonstrates use of array argument to a function
1. #include <iostream.h>
2. void display(int score[5]);
3. int main() {
4. int score[5] = {88, 76, 90, 61, 69};
5. display(score);
6. return
0; 7. }
8. void display(int m[5]) {
9. cout<<"Displaying score: "<<endl;
10. for (int i = 0; i <5; ++i)
{
11. cout<<"Student "<<i+1<<": "<<m[i]<<endl;
12. }
Run:13. }

Explanation: The argument score used in the above code


represents the memory address of first element of array score.
The formal argument int m[5] in function declaration is pointer
to score;. Even though the function is manipulated with array
name m[5], the original array is manipulated. The C++
programming language handles passing array to a function in this
way to save memory and time.

73
Multidimensional Array as argument to a Function
Multidimensional array can be sent to a function in similar way as
one-dimensional array. Here also only the array name is
mentioned in the function call. When the function is invoked,the
control moves to function definition and in the function header,
the formal parameter is declared with required dimensions.
Remaining accessing is same in caller and callee functions.
Example : Passing Multi dimensional Array to a Function
1 #include <iostream.h>
2 #include<conio.h>
3 void show(int n[3][2]);
4 int main()
5 {
clrscr();
6 int num[3][2] = {
7 {3, 4},
8 {9, 5},
9 {7, 1}
10 };
11 show(num);
12 return 0;
13 }
14 void show(int n[3][2]) {
15 cout<<"Displaying Values: "<<endl;
16 for(int i = 0;i < 3; ++ i) {
17 for(int j = 0; j < 2; ++j) {
18 cout<<n[i][j]<<" ";
19 }
20 cout<<endl;
21 }
22 }
RUN

Explanation: In line numbers 6-10 the array num is initialized


with 3 rows and 2 columns. Using nested for loop, in the function

74
show from line 16 to 21, the array elements are displayed. In this
program the 2D array is sent to the function named show() and
the array elements are displayed in the function.
Operations on arrays
Several operations can be performed on an array. An each array
element can be used as an ordinary variable. And array elements
are stored in adjacent memory locations. Some of the operations
that can be performed on arrays are listed below:
 Inserting an element to an array
 Deleting an element from an array
 Finding min and max elements in the array
 Sorting array elements
 Searching for an element in the array
 Merge two arrays
Inserting an element to an array
When the array size is ‘n’ and there are less number of elements
in the array than the size of the array then inserting an element
into an array is possible. Other wise overflow occurs. It means we
cannot insert elements more than the size of the array. One
difficulty in this process is shifting of elements. If the user wants
to insert the element at the end it is easy. But inserting an
element into the array in any other position other than end
position needs shifting of existing elements for creating space for
new element.

Figure 23: Inserting element into an array at the end.

75
.Figure 24:Inserting element into an array
Deleting an element from an array
When an element is deleted from an array, the size of the array is
reduced by 1. If last element is deleted there is no need of shifting
the elements in the array. But when an element is deleted in a
position other than last position, the elements next to the deleted
element are shifted towards deleted element position

Figure 25 Deleting last element in an array

Figure 26:Deleting element from an array


Finding min and max elements in the array
When the elements in the array are arranged in ascending or
descending order, picking min and max elements is very simple.

76
But when the elements are not in order, then the user needs to
navigate the entire array to determine min and max elements.
Sorting array elements
The array elements can be arranged in increasing or decreasing
order. This technique is called as sorting. In programming there
are different techniques for sorting the elements in the array.
Various techniques are suitable for different data inputs. However
optimum sorting technique work efficiently for all types of input
sets of any size.
One of the approaches used for sorting is bubble sort. It is easy to
understand. But when it is implemented it is found that the time
taken to sort the elements is very high. That is the reason why
this technique is not widely used.Bubble sort compares each pair
of adjacent elements in the array and interchange their positions
if they are not in the correct order. The process is continued until
the list is sorted. Bubble sort is based on comparison of two
adjacent elements; it is also denoted as comparison sort
Example:
Consider an array of integers "7 3 6 4 9",
Here we compare the each pair of elements and swap the values if
they are not in correct order.

ITERATION 1
7 3 6 4 9 compare 7 and 3 (7>3)
Elements 7,3 are swapped
3 7 6 4 9
and now 7,6 are compared (7>6)

3 6 7 4 9 elements 7,6 are swapped


now 7,4 are compared (7>4)

3 6 4 7 9 elements 7,4 are swapped


now 7,9are compared (7<9)
7,9 are in correct order for ascending order so no swap
occurs

ITERATION 2
3 6 4 7 9 3,6 are compared, (3<6) no swap
3 6 4 7 9 6,4 are compared and swapped since 6>4

77
3 4 6 7 9 6,7 are compared but not swapped since 6<7
3 4 6 7 9 7,9 are compared but not swapped since 7<9

ITERATION 3
3 4 6 7 9 3,4 are compared, (3<4) no swap
3 4 6 7 9 4,6 are compared (4<6) no swap
3 4 6 7 9 6,7 are compared (6<7) no swap
3 4 6 7 9 7,9are compared (7<9) no swap
Now the algorithm will be stopped.

Figure 26: example for Bubble sort technique

Searching for an element in an array


Searching refers to locating an element in an array. The basic
search method is linear search. In this search process the search
element is compared with each element in the list. But to reduce
the search time we follow another search method called binary
search. Here we need not to search for an element by comparing
each element in the list. But it works on only sorted list. We
discuss both the techniques in this section.
Linear Search (Sequential Search)
In this search process, the search element is compared with first
element in the given list. If there is a match, the search
terminates. Otherwise the search continues by comparing with
second element in the list. The process will be continued till the
end of the list. As name indicates the search continues in linear
order till the end.
Linear search is implemented using following steps.

 Step 1: Consider a list of values in which the search


operation is to be conducted.
 Step 2: input the search element
 Step 3: Compare the search element with list values in
sequence
 Step 4: If the search element matches with element in
the list, the search process terminates

78
 Step 5: otherwise search process continues till the end
of the list.
 Step 6: element found or not message will be
displayed accordingly

Figure 27: Linear search


Binary Search
Binary search is a search technique applied only on ordered list.
In this technique the search element is compared with the
element located in the middle of the list. If there is a match then
the search completes. Otherwise, the list is divided into two parts.
First part index range will be [0 to mid-1]] and second part index
range will be [mid+1 to n-1] where n is the size of the list and mid
is index of middle element. The search will be continued in first
part if the search element is less than the middle element. Here
mid-1 is last index of first part.Otherwise the search will be
continued in the second part of the list. In the second part mid+1
is start index.When the search process is continued the search
element may be found or last index becomes greater than the
start index. This condition concludes the element is not found in
the list.
Binary search is implemented using following steps.

 Step 1: Consider a list of values in which the search


operation is to be conducted
 Step 2: input the search element
 Step 3: Compare the search element with middle
element

79
 Step 4: If the search element matches with middle
element in the list, the search process terminates, element
found message will be displayed
 Step 5: otherwise search process continues in either first
part or second part of the list.
 Step6: The range of index for first part of list is [0 to mid-
1], here mid is the index of middle element.
 Step 7: The range of index for second part of list is
[mid+1 to n-1], here n is the size of the list
 Step 8: if search element is less than the middle
element, the search is carried out in first part of the
list
 Step 9: if search element is greater than the middle
element, the search is carried out in second part of the
list
 Step 10 : the search process mentioned in steps [3-9]
will be continued until the element is found or last index
becomes less than start index after some iterations.
Example:

Figure 27: Binary search

80
Merging two arrays.
Merging of two arrays is possible when one of the arrays is able to
hold elements of two arrays. If sufficient memory is not allocated
then merging is not possible.

10 11 13 14

Array1

15 20 25 30

Array2
When array2 is merged with array1 then the result will be as
follows.

10 11 13 14 15 20 25 30

81
Array1
Program to sort list of elements.

#include<iostream.h>
void main ()
{
int list[10], n, i, smallest, largest;
cout << "\nEnter the number elements of the array: ";

cin >> n;
cout << "\n Enter the elements of the array : ";

for (i = 0; i < n; i++)


cin >> list[i];
largest = list[0];

for (i = 0; i < n; i++)


{
if (largest < list[i])
largest = list[i];
}

smallest = list[0];
for (i = 0; i < n; i+
+)
{
if (smallest > list[i])
smallest = list[i];
}

cout << " Largest element : " << largest<<endl;


cout << " Smallest element : " << smallest<<endl;
}

82
1.8 Strings in C++
C++ compiler allows using 2 types of strings:
 C-Strings (Sequence of characters that are terminated
with \0 (null character)).
 The String class objects that are introduced with
Standard C++.
The C-Style Character String
C-strings are the strings which are used in C language and those
strings are continued with C++. The C- strings are the sequence of
characters that ends with a null character '\0'. Here null
character is used as delimiter. The pre-defined functions for these
strings are mentioned in <string.h> header file.
When C- strings are declared, we must declare the size one more
than the required number of characters. Since the last character
must be null character, and with is not the part of the string.
char str[4] = {'C', '+', '+', '\0'};
It can also be declared as follows:
char str[] = {'C', '+', '+', '\0'};
char str[] = “C++”;
The memory representation for the above initialized strings will be
as follows:

INDEX 0 2 3 4
VARIABLE C + + \0
ADDRESS 0X23451 0X23452 0X23453 0X23454

When working with strings the programmer need not to keep the
null character explicitly. The compiler automatically places the
null character at the end of the string. Only when it is initialized
character by character, the null character is needed.
Several predefined functions are supported by C++ compiler. The
functions are declared in string.h header file. Few of those
functions are :

83
Function Purpose
strcpy(str1, str2); Copies string str2 into string str1.

84
Concatenates string str2 onto the end of
strcat(str1, str2);
string str1.
strlen(str1); Returns the length of string str1.
Returns 0 if str1 and str2 are the same;
strcmp(str1, str2); negative value if str1<str2; positive value
if str1>str2.
strlwr(str1) converts the letters in str1 into lower case
strupr(str1) Converts the letters in str1 into upper case.
strrev(str1) Reverses the string str1.

Following example demonstratesfew of the above-mentioned


functions –
1. #include <iostream.h>
2. #include <string.h>
3. int main () {
4. char str1[10] = "Hello";
5. char str2[10] = "World";
6. char str3[10];
7. intlen ;
8. // copy str1 into str3
9. strcpy( str3, str1);
10. cout << "strcpy( str3, str1) : "
<< str3 << endl;
11. // concatenates str1 and str2
12. strcat( str1, str2);
13. cout << "strcat( str1, str2): "
<< str1 << endl;
14. // total lenghth of str1 after
//concatenation
15. len = strlen(str1);
16. cout << "strlen(str1) : " << len << endl;
17. return 0;
18. }

Output:
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10

85
Explanation: In line 4 and 5 two strings str1 and str2 are
initialized. In line 6, str3 is declared. In line 9, str1 is copied into
str3, in line 13 str2 is appended to str1. In line 15, length of str1
is found.
The String Class in C++
The standard C++ library provides a string class. it supports the
string operations in more flexible manner. A snapshot of the code
is given below:
string str1 = "Hello";
string str2 = "World";
string str3;
int len ;
// copy str1 into str3
str3 = str1;//copy operation is done with assignment operator
cout << "str3 : " << str3 << endl;

// concatenates str1 and str2


str3 = str1 + str2;// concatenation is done with + operator
cout << "str1 + str2 : " << str3 << endl;

// total length of str3 after concatenation


len = str3.size(); // length is found with size member function
cout << "str3.size() :" << len << endl;
1.9 Pointers in C++

The computer memory can be treated as sequence of bytes. Each


byte is logically numbered. Such numbers are called addresses.
Every byte is numbered with an unsigned integer. These integers
cannot be used in general arithmetic. But the integer values are
helpful in referring the memory locations.The address refers the
memory location so the address is also called as pointer. As we
already know variable name is a name of memory location. And
variables hold the values. In C++ there is special kind of variables
called pointer variables. Pointers are the addresses and pointer
variable contains memory location’s address allotted to another
variable. Pointer variables are the variables that hold the address
of other variables.

86
The general form of a pointer variable declaration is:
data-type *var-name;
Here, datatype is the pointer's base type;
Following are the valid pointer declaration:
int *ip;// ip holds an address of integer variable
double *dp;// dp holds address of double variable
float *fp;// fp holds address of float variable
char *ch;// ch holds address of character variable
All pointers are long type and represented as hexa-decimal
numbers. But the type of pointer we mention is the type of
variable to which it points.
Using Pointers in C++:
There are few important operations,
 We define a pointer variables
 Assign the address of a variable to a pointer
 Finally access the value at the address stored in pointer
variable.
Following example makes use of these operations:
1. #include<iostream.h>
2. #include<conio.h>
3. int main ()
4. {
5. clrscr();
6. intvar = 20;// var is a variable of type int.
7. Int *ip;// ip holds address of integer variable

8. ip = &var;// address of var is stored in ip


9. cout << "Value of var variable: ";
10. cout << var << endl;

11. cout << "Address stored in ip variable: ";


12. cout << ip << endl;//address of var is printed

13. cout << "Value of *ip variable: ";


14. cout << *ip << endl;
87
//value at ip means value in var is printed

15. return 0;
16. }
RUN

Explanation: In line 6, a variable is declared with the name var.


and assigned a value 20. In line 7, a pointer variable is declared
with the name ip. In line 8, address of var is stored in ip. In line
10 , value of var is printed that is 20. In Line 12, ip values is
printed. ip holds the address of var. so address is printed. In line
14 , *ip is displayed. *means value at. So value at ip (*ip) means
value at that address is 20.

Figure 28: Pointer variable


Advantages and disadvantages of pointers
Advantages:
 Pointers are efficient in handling arrays and other data
structures.
 They can be used to return multiple values from a function via
function arguments.
 The use of pointer arrays to character strings results in saving
of data storage space in memory.
 Allocating memory and releasing memory for variables is done
at run time with the help of pointers. This avoids wastage of
storage space.
 Stacks, Queues, trees, graphs and many other data structures
are managed with pointers.
 The length of the programs often reduced with pointers.
88
 The execution speed of the program is increased with usage of
pointers.
Disadvantages
 Pointer if used incorrectly leads to severe bugs
 Pointers allow the user to navigate to the adjacent memory
locations without boundary checking. When reading data
values, if the navigation is occurred out of boundary, then the
values read are garbage and the program works with garbage
values.
NULL Pointer
 The term NULL is used to represent no value in the pointer. It
means that the pointer is not having any address.
 NULL indicates the constant value 0. The meaning of NULL is
mentioned in various header files like <iostream.h>,
<stdlib.h>, <stddef.h>

Consider the following program:


1. #include <iostream.h>
2. int main ()
3. {
4. int*ptr = NULL;
5. cout << "The value of ptr is " << ptr ;
6. return 0;
7. }

Run

Explanation: In line 4, ptr is declared. ptr is a pointer variable and


it is assigned NULL, It refers no address(0).
Pointer arithmetic
Pointer arithmetic is one of the powerful features of C++. If the
variable p is a pointer to a type, ‘p+1’ gives the address of next
variable of same type. This mechanism is extensively used in
accessing array elements using pointers.
If p1, p2 are the pointers the following statements are valid.
P1+1;

89
P2+3;
P1-2;
P1++
P1--
 Suppose p=1000 and p is pointer to integer, which occupies 4
bytes. The p++ gives 1004.
 If p=1012 and q=1008 then p-q=1 and p-2=1004
But the following are the invalid
statements p1+p2;
p1-p2;
p1/p2;
Wild Pointer
Uninitialized pointers are known as wild pointers, because they
point to some arbitrary memory location and may cause crash.

1. int
main() 2. {
3. int *p; /* wild pointer */
4. *p = 12; /* Some unknown memory location is
being corrupted.*/
5. }
Dangling Pointer
 Dangling pointers arise during object destruction
 When an object is deleted or de-allocated, without modifying
the corresponding pointers, then such pointer becomes
dangling pointer.
Example :

Statement Meaning

int *p1;

90
p1=new int;

*p1=8;

int *p2;

p2=p1;

delete p1;

Figure : 29:Dangling pointer.


Generic Pointer
 void pointer in C++ is known as generic pointer.
 Literal meaning of generic pointer is a pointer which can point
to anytype of data.
 These are much useful in templates.
Example:
void *ptr;
Here ptr is generic pointer.
91
The below code demonstrates generic pointer.

1. #include<iostream.h>
2. int main(){
3. char c='A';
4. int i=4;
5. void *p;// g
6. 6. eneric pointer
char *q=&c;
7. int *r=&i;
8. p=q;//stored character pointer
9. cout<<"\nDisplaying char value with generic pointer p
*p="<<*(char *) p;
10. p=r;// stored integer pointer
11. cout<<"\nDisplaying int value with generic pointer p
*p="<<*(int *) p;
12. return 0;
13.}
Run

Explanation: In line 3, character variable ‘c’ is declared and


assigned value ‘A’. similarly in line 4, integer variable ‘i’ is
assigned a value 4. In line 5, generic pointer ‘p’ is declared. Later
the character pointer ‘q’ and integer pointer r’’ are taken. Now, the
generic pointer *p worked with both character and integer
pointers in lines 9 and 11.
Pointers and Arrays
 Array name itself gives the base address of the array. Similarly
a pointer can store address of array.It means both pointers
and arrays work similarly with slight difference. Pointers save
memory when implemented as arrays.
 When collection of data items has to be stored we need arrays.
But with arrays, we need to specify the size prior. In case of
pointers it is not needed. Also the array created with pointer
can be deleted when its purpose is fulfilled.
 The arrays created with pointers are called dynamic arrays.
The dynamic arrays can be created and destroyed as and when
needed.
92
Consider the following program:

1. #include <iostream.h>
2. const int MAX = 3;
3. int main
() 4. {
5. intvar[MAX] = {10, 100, 200};
6. int*ptr;
7. // address of array var can be stored into ptr with
//assignment.
8. ptr = var;
9. for (int i = 0; i < MAX; i++)
10. {
11. cout << "Address of var[" << i << "] = ";
12. cout << ptr << endl;
13. cout << "Value of var[" << i << "] = ";
14. cout << *ptr << endl;
15. // point to the next location
16. ptr++;
17. }
18. return 0;
19. }
Run:

Explanation : In the above program we have used pointer as


array. var is an array. ptr is a pointer. Using ptr the array
elements are displayed. It means pointers can be used as arrays.
However, pointers and arrays are not completely interchangeable.

1. #include <iostream.h>
2. const int MAX = 3;
3. int main ()
4. {
5. intvar[MAX] = {10, 100, 200};
6. for (int i = 0; i < MAX; i+
+) 7. {
8. *var = i;// This is a correct syntax
9. //var++;// This is incorrect.
10. } 93
11. cout<<"var="<<var;
12. return 0;
13. }
Run

Explanation: use of * with var is valid but it is illegal to modify


var value. So var++ is not correct. The reason for this is that var is
a constant that points to the beginning of an array and cannot be
used as l-value.
Because an array name generates a pointer constant, it can still
be used in pointer-style expressions, as long as it is not modified.
For example, the following is a valid statement. It assigns 500 to
var[2] .
*(var + 2) = 500;
Above statement is valid and will compile successfully because var
is not changed.
Array of pointers
We can declare an array of pointer to any type. Example is given
below:
int *ptr[MAX];
In the above declaration ptr is an array with size MAX, it can hold
only addresses. Simply ptr is an array of pointers. Due to that
reason every element in ptr, holds an address of integer variable.
In the below example var is an array of pointers and it can store
addresses of 3 integers
1. #include <iostream.h>
2. const int MAX = 3;
3. int main ()
4. {
5. int var[MAX] = {10, 100, 200};
6. int *ptr[MAX];
7. for (int i = 0; i < MAX; i+
+) 8. {
9. ptr[i] = &var[i];// assign the address
of integer.
10. } 94
11. for ( i = 0; i < MAX; i++)
12. {
13. cout << "Value of var[" << i << "] = ";
14. cout << *ptr[i] << endl;
15. }
16. return 0;
17. }
Run

Explanation: var is an array. ptr is an array of pointers. Address


of each array element is assigned to one of the elements of ptr.
Later the array elements are displayed with pointers.

95
Functions

Function is a block of code that performs a task or subtask of


other task. In C++, every program consists at least one function
called main(). When a task is lengthy or complex, the task can be
divided into number of subtasks. For each subtask we write a
block of code with some name. Such a code is called function.It is
the idea of modular programming. A problem is divided into
several modules and for each module we write block of code.
When a block of code is needed many times in a program or many
programs, then it is good practice to write such block as a
function. Since the block can be used many times in same
program or in many other programs.

Figure 31Usage of Functions


Need for the functions
In C/C++, a large task can be divided into smaller ones. The
smaller tasks solved by writing functions. The process of dividing
a lengthy program into small sub programs and manipulating
them independently is known as modular programming. This
technique is similar to divide and conquer technique. Dividing a
large program into smaller functions provides advantages to the
programmer. The testing and debugging of a program with

96
functions becomes easier. A call to a function is done as per
requirement. Thus the size of the program can be reduced.
Function
Function is a block of code that solves a task or sub task of other
task. In C++ we have two types of functions. They are predefined /
library/built-in functions and user defined/programmer defined
functions. The library functions can be used in any program by
including respective header files. The header files must be
included using # include preprocessor directive. The programmer
can also define and use his/her own functions for performing
some specific tasks. Such functions are called as user-defined
functions.
The following are the advantages of functions:
1. Support for modular programming
2. Reduce the program size
3. Code duplication is avoided
4. Code reusability is provided
5. Functions can be called repetitively
6. A set of functions can be used to form libraries
Parts of function
A Function consist the following components. Not all functions
consist all of the below mentioned components.
1. Function prototype
2. Definition of a function
3. Function call
4. Actual and formal arguments
5. The return statement
Function prototype
A function prototype is also called as declaration of the function.
The declaration of a function includes the function return type ,
name of the function, and parameter which it accepts. It means
the declaration tells the following to the compiler
(a) Function Name,

97
(b) Type of the value it returns
(c) Argument data types individually in comma separation
The first line of the function definition is also called header. The
header of the function and the function declaration has to be
same except the declaration consists semicolon at the end. If
declaration and header is not same, the compiler flags an error.
The following statements are the examples of function prototypes:
void show(void);
float sum(float, int);
Function Definition
The first line is called function header and is followed by function
body. The block of statements followed by function header is
called as function definition. The header and function prototype
declaration should match each other. The function body is
enclosed with in curly braces. The function can be defined
anywhere. If the function is defined before its caller, then its
prototype declaration is optional
Function Call
The function gets activated only when a call to function is made. A
function is invoked by mentioning its name; we mention the
inputs to the function as parameters of the function. The function
arguments in the function call are mentioned in parenthesis.
Actual and formal Arguments
The parameters that we mention in function call are called actual
parameters. The actual parameters are the input to the function.
To receive the values or references of actual parameters we
declare some other variables in the function definition at the
header line of the function, those variables are called formal
parameters. The parameters that are declared in the function
declaration also called formal parameters.The
parameters/arguments in function declaration, definition, and
call must be in same number and type in sequence.

98
The return Statement
The output of the function can be sent via return statement. The
only limitation of the return statement is that it can return only
one value. In return statement the programmer can return value
directly or a variable/expression the yields a value. The value
returned by the return statement and the return type of the
function must be same otherwise the compiler flags an error. In
general, the return statement is the last statement in the
function. If the return statement is kept in any other part of the
function and when the return statement is encountered, the
function execution is terminated and the control moves to the
called function. The general form of the return statement is given
below.
return (variable name); or
return variable name;
Example:

1 #include<iostream.h>
2 #include<conio.h>
3 float sum(float, int);//function prototype
4 void
main() 5 {
6 clrscr();
7 float x,y=2.4;
8 int z=5;
9 x=sum(y,z);//function call with actual argument in
//parenthesis
10 cout<<"x="<<x;
11 }

12 float sum(float j, int k)// function header


13 {
14 return (j+k);
//function body with return statement
15 }
Run

99
Explanation: In line number 3, the function prototype is given. In
line number 9, function call is made. When the function is called
the control will be shifted to line number 12. The function is
defined between line 12 and line 15. In the program two numbers
are added.
Parameter passing techniques
When the program is divided into number of functions, the main
function provides coordination between the functions.But for
establishing communication among the functions, parameter
passing techniques are used. In many cases, the communication
occurs between main function and other functions. The input to
the functions is arguments. And a programmer can send the
arguments in 3 different methods.
The main objective of passing argument is message passing. The
message passing is also known as communication between two
functions i.e. between caller and callee functions. There are 3
methods by which we can pass values to the function. These
methods are:
1. Call by value (pass by value)
2. Call by address (pass by address)
3. Call by reference (pass by reference)
Pass by value
In this technique, the programmer mentions values to be sent to
the function. The values are mentioned in the function call. The
list of values are separated with comma and kept in parenthesis of
function call. The list of values is copied into the formal
parameters mentioned in the function header. These formal
parameters are used in the function definition. But if the
parameters are changed, the changes are limited to that function
definition only. In the caller function the changes done to formal
parameters are not visible. In this technique, the programmers
pass only the values, or the function is called with values of
parameters, hence this technique is called pass by value or call by
value.
The following program demonstrates the call by value technique.

10
0
1 #include<iostream.h>
2 #include<conio.h>
3 void change(int x,int y);
4 int
main() 5 {
6 int x,y;
7 clrscr();
8 cout<<"Enter
x,y,values:"; 9 cin>>x>>y;
10 cout<<"\nThe values of x,y before function call:";
11 cout<<"\nx="<<x<<"\ty="<<y;
12 change(x,y);
13 cout<<"\nThe values of x,y after function
call:"; 14 cout<<"\nx="<<x<<"\ty="<<y;
15 return 0;
16 }
17
18 void change(int x,int y) {
19 cout<<"\nThe values of x,y"
<<" in function before change:";
20 cout <<"\nx="<<x<<"\ty="<<y;
21 x=x+10;
22 y=y+10;
23 cout<<"\n\nThe values of x,y"
<< "in function after change:";
24 cout <<"\nx="<<x<<"\ty="<<y;
25 }
RUN

10
1
Explanation: In line number 11, x ,y values are displayed as 10
,20. In line number 12, change function is called, In line number
20, x,y values are displayed as 10,20. But, in line numbers 21
and 22 the values of x and y are changed. In line number 24, the
values of x,y are displayed as 20 and 30. (changed values). After
the completion of the function in line number 14, x,y values are
displayed as 10 and 20. Here the values of x,y are not changed in
function main.
Pass by address
In this technique, the programmer sends addresses of variables to
the function. The addresses are mentioned in the function call.
The list of addresses is copied into the formal parameters
mentioned in the function header. These formal parameters are
the pointer variables. The changes applied through formal
parameters are available in the caller function. As the
programmer sends addresses of variables to the function, this
technique is called pass by address
The following example illustrates the concept of pass by address

1 #include<iostream.h>
2 #include<conio.h>
3 void change(int *p,int *q);
4 int
main() 5 {
6 int x,y;
7 clrscr();
8 cout<<"Enter x,y,values:";
9 cin>>x>>y;
10 cout<<"\n\nThe values of x,y "
<<"before function call:";
11 cout<<"\nx="<<x<<"\ty="<<y;
12 change(&x,&y);
13 cout<<"\n\nThe values of x,y after function call:";
14 cout<<"\nx="<<x<<"\ty="<<y;
15 return 0;
16 }

10
2
17 void change(int *p,int *q)
18 {
19 cout<<"\n\nThe values of *p, *q"
<<"in function before change:";
20cout <<"\n*p="<<*p<<"\t*q="<<*q";
21*p=*p+10;
22*q=*q+10;
23cout<<"\n\nThe values of *p, "
<<"*q in function after change:";
24cout <<"\n*p="<<*p<<"\t*q="<<*q;
25}
RUN

Explanation: In line number 11, x ,y values are displayed as 10


,20. In line number 12, change function is called, In line number
20, x,y values are displayed as 10,20. But, in line numbers 21
and 22 the values of x and y are changed. In line number 24, the
values of x,y are displayed as 20 and 30. (changed values). After
the completion of the function in line number 14, x,y values are
displayed as 20 and 10. Here the values of x,y are changed in
function main since the addresses of the variables x, y are sent to
the function so the values in the original location are changed..
Pass by reference
In this technique, the programmer uses reference variables. The
parameters are mentioned in the function call. The list of
references to actual parameters are mentioned as formal
parameters in the function header. These formal parameters are
10
3
the reference variables. The changes applied through reference
variables are available in the caller function. As the programmer
sends references of variables to the function, this technique is
called pass by reference
The below example illustrates concept of pass by reference
1 #include<iostream.h>
2 #include<conio.h>
3 void change(int& x,int& y);
4 int
main() 5 {
6 int x,y;
7 clrscr();
8 cout<<"Enter
x,y,values:"; 9 cin>>x>>y;
10 cout<<"\n\nThe values of x,y"
<<" before function call:";
11 cout<<"\nx="<<x<<"\ty="<<y;
12 change(x,y);
13 cout<<"\n\nThe values of x,y: "
<<" after function call:";
14 cout<<"\nx="<<x<<"\ty="<<y;
15 return 0;
16 }
17 void change(int& x,int& y)
18 {
19 cout<<"\n\nThe values of x,y "
<<"in function before
change:"; 20 cout <<"\nx="<<x<<"\
ty="<<y;
21 x=x+10;
22 y=y+10;
23 cout<<"\n\nThe values of x,y "
<<"in function after
change:"; 24 cout <<"\nx="<<x<<"\
ty="<<y;

10
4
RUN

Explanation: In line number 11, x ,y values are displayed as 10


,20. In line number 12, change function is called,In line number
20, x,y values are displayed as 10,20. But, in line numbers 21
and 22 the values of x and y are changed. In line number 24, the
values of x,y are displayed as 20 and 30. (changed values). After
the completion of the function in line number 14, x,y values are
displayed as 20 and 10. Here the values of x,y are changed in
function main since the formal the formal parameters are alias
name to actual parameters
Default arguments
Usually, a function is called with all the arguments as declared in
function prototype. C++ compiler lets the programmer to assign
default values in the function prototype declaration/function
header. When function is called with less number of parameters
or without parameters, the default values are used for the
operations. The default arguments are useful while making a
function call if we do not want to take effort for passing
arguments that are always same. Here we assign the default
values to parameter in declaration from right to left.

10
5
The below program demonstrates the concept of default
arguments

1 #include<iostream.h>
2 int sum(int a, int b=10, int c=15, int d=20);
3 int
main() 4 {
5 int a=2,b=3,c=4,d=5;
6 cout<<"\nsum="<<sum(a,b,c,d);
7 cout<<"\nsum="<<sum(a,b,c);
8 cout<<"\nsum="<<sum(a,b);
9 cout<<"\nsum="<<sum(a);
10 cout<<"\nsum="<<sum(b,c,d);
11 return
0; 12 }
13 int sum(int j,int k,int l, int m)
14 {
15 return(j+k+l+m);
16 }

Run

Explanation: In line number 2, the variables b,c, and d aare


assigned with the values 10,15 and 20 respectively. In line 6
sum() function is called with 4 parameters. So there is no
problem. All assigned values for a,b,c,d are used from main
function. Inline 7, sum() function is called only with 3 parameters.
But the function expects 4 parameters from its prototype. So from
line 2, value for 4th parameter d is substituted. In the same way
for the function call in line 8, c,d values are substituted from line
2 and for the function call in line 9, b,c,d values are taken from
line 2. In line 10, sum() function used 3 parameters b,c,d but the
variables works for a,b,c respectively and d is considered as
default argument.

10
6
Constants as arguments
Constants sent as arguments should not be changed in the
functions. For this we use a const reference. So we cannot change
the argument.
The following function will produce a compiler error:

void foo(const int &x) // x is a const reference


{
x = 6;// compile error: a const reference cannot be changed!
}
Scope of the variable
A scope is a part of the program, where variables can be used.
There are three locations where we could declare the variable.
 Within a function or a block the declared variables are
called local variables.
 In function definition, at the function header the
parameters are referred as formal parameters.
 The variables which are not declared in any block of
program that is out of all blocks are called global variables.

Local variables are created when the program control enters the
block and the variables are destroyed when the control exits the
block.
Global variables are created when program execution begins, and
they can be accessed through out the program till the end of the
program
Inline Functions
Need for inline functions:
The main reason to use the functions is to avoid duplicate code.
But if the same function is called several times, each time the
control is switched to the function. Due to the passing of control
in between caller and callee functions, execution speed of program

10
7
decreases. Inline functions prevents repetitive calls and increases
program execution speed.
Implementation of inline function:
In case of inline functions, the compiler replaces function call with
the code of the function during compilation. It avoids moving of
control between caller and callee functions. With this technique
the execution speed of the program is improved.
The concept of inline function does not work when the function is
lengthy. Because, here the compiler copies the code at function
call, due to this reason the code in the program increases when
the function is lengthy. It means when the length of the code is
increased obviously the execution speed decreases. So the
purpose of inline function (increasing the execution speed) will not
be full filled.

The general form of inline function is given below:


inline function-name
{
statement1;
statement2; //function body
}
Example:
inline float square(float k)
{
return (k*k);
}
inline functions can’t be used in the following cases:

1. For recursive functions, we can’t apply inline function


concept
2. Inline function concept can’t be applied when the
function contains static variables.
3. Inline functions are not used for the functions that have
iterative and conditional statements
Unlike other functions, main() function can never be used as
inline.

10
8
Function overloading
When same kind of task is to be performed on distinct number of
values or for distinct type of values, a programmer can use the
same function name. Assigning same name to different functions
that are written for solving similar problems is known as function
overloading. In Object Oriented programming it is called
polymorphism. It means having different forms with the same
name. Here only the function name is same but the number of
parameters or type of parameters is different.
Principles of function overloading
 The return type of the function is not considered to distinguish
between two functions. It means the two forms of the functions
must be different either in the type of arguments they take or
number of arguments they accept.
 Use of constants directly in function calls also creates
ambiguity in function calls.
 When a function is overloaded, the name of the function will be
same, so when the function call is made the compiler checks
for the correct matching of parameter list. If no correct match
of parameter list is found the compiler flags an error.
The examples of overloaded functions are given below.

intsqr(int);
float sqr(float);
long sqr(long);
The below program demonstrate the concept of function
overloading.
1 #include<iostream.h>
2 #include<conio.h>
3 int square(int);
4 float square(float);
5 int
main() 6 {
7 clrscr();
8 int a=15;
9 float b=2.5;
10 cout<<"\nsquare="<<square(a)<<endl;

10
9
11 cout<<"square="<<square(b)<<endl;
12 return
0; 13 }
14 int square(int s)
15 {
16 return
(s*s); 17 }
18 float square(float j)
19 {
20 return (j*j);
21 }
Run

Explanation: In line number 3 and 4, square function is declared


with one parameter but the parameter type is different. When
square() function is called in line 10, function at line 14 is called.
Because parameter a is integer. And for the function call in line
11, function at line 18 is called. Here the parameter b is float. In
this program square() is overloaded with an integer and float
parameter separately.
Recursive function

 In general, a function calls other function. The calling function


is called caller, and called function is called callee.
 In function communication, C++ allows the caller and callee is
same. It means a function may call itself. Such function is
called recursive function and technique is called recursion.
 In recursive function definition, we have to mention at least
one stopping case (base case) and one recursive call.
Otherwise it is not valid recursion, it may lead to infinite
recursion or it may not give correct result.
 Every recursive call has to solve a unit of entire task
 In recursion, a function makes a call to itself but for every call
a new copy of function is created in memory

11
0
 The local variables inside the copies of functions are also
different and can only be accessed within that function.
Consider this example to find factorial of a number using
recursion.

1 #include<iostream.h>
2 #include<conio.h>
3 int factorial(int);
4 int
main() 5 {
6 clrscr();
7 int n;
8 cout<<"Enter a number to find factorial: ";
9 cin>>n;
10 cout<<"Factorial of "<<n<<" = "<<factorial(n);
11 return
0; 12 }
13 int factorial(int n)
14 {
15 if (n>1)
16 {
17 return n*factorial(n-1);
18 }
19 else
20 {
21 return 1;
22 }
23 }
Run:

Explanation: In line 3, factorial() function prototype is declared.


In line13 to 23 factorial function is defined. In line 10 factorial
function is called. The parameter n value is sent to function. In
line 13, n is received as formal parameter.Suppose n=3, as n>1
the function returns 3*factorial(2), now factorial(2) will be in
active. It again calls 2*factorial(1). Here the terminating condition
occurs. As n>1 is false. The recursive call will be stopped. At the
end 3*2*1 will be returned.

11
1
Recursion Vs. Iteration
In Programming, the programmer may need to repeat certain code.
For such repetition, there are two techniques. The first one and
most widely used technique is iteration.In C++ we have different
iterative statements namely while, do-while and for. For repetitive
execution of code, there is another technique called recursion. In
recursion, the caller and callee functions are same. For some
problems, implementation becomes simpler with recursion. But in
recursion the same function is called many times, and because of
compile time checking at each function call the program execution
speed will be decreased.
In case of recursion, a function definition has call to itself. The
function is called several times until the terminating condition
becomes true.

 In case of repetition,the code block will be executed until the


condition becomes false. In any iterative statement, the
programmer sets the initial condition, later mention the loop
terminating condition and also inserts an update statement
that leads to the termination of the loop. By the end of the loop
the purpose of that loop in the program will be fulfilled.
 In recursive function,a terminating condition is essentially set
by the programmer, otherwise the function makes call to itself
infinite times. This leads to abnormal termination of the
program.
 If the terminating condition is set properly in recursive
function. The code seems to be easy, small and simple. On the
other hand iterative statements can also perform same kind of
task like recursive functions. But the code may be much
lengthy.
 In recursion, a same function is called in its definition multiple
times until the terminating condition occurs. Because of
compile time checking for every function call and pushing
function onto the stack and popping it from the stack may
take more time. Because of this reason, the recursion is slower
than the iteration.
 As a function replicates itself in case of recursion with different
argument values it takes more memory.

11
2
 In case, if recursive condition is not terminated with proper
stopping case, the function calls itself infinite times and stack
overflow occurs.
 Any problem that can be solved with recursion can be solved
with iteration and vice versa. It means recursion and iteration
are equal in power. The only difference is that some problems
are easily expressed in terms of recursion. But iteration is
faster than recursion.
.
Eg for finding factorial of a number in two ways
Recursive version:
int cal_factorial(int n)
{
/* Base condition if n equals to 1 then return 1 */
if(n==1)
return 1;
else
/* Recursive call */
return (n * cal_factorial(n-1));
}

Iterative version
int factorial (int n) {
int fac = 1;
for (int i = 1; i <= n; i++){
fac = fac * i;
}
return fac;
}

11
3
Object Oriented Programming

Programming Paradigms
The term paradigm refers methodology. Programming paradigm is
a way of writing programs. In the evolution of programming
languages, different programming paradigms are found. No one
paradigm is suitable for writing all varieties of programs. It means
each paradigm has its own strengths and weaknesses.
The programming paradigms can be classified as follows:
 Monolithic programming
 Procedural programming
 Structured programming
 Object oriented programming
Monolithic Programming:
 In the monolithic programming paradigm, the programs are
not divided into sub programs. So the entire program is seen
as a single unit.
 The entire data are kept as Global and every statement can
access the data items. There is no security to the data. It
means when multiple statements change the data, the
programmers mayhave no control on the program.
 In a program, to transfer the control from one statement to
other statement, the jump control statement goto is used. Use
of several goto statements causes lot of confusion to the
programmer or user.
 Assembly languages and high level language like BASIC fall
into this category.
 This kind of programming methodology is suitable for writing
very small programs. In this reusability of the code is not
provided.

11
4
Layout of a program in Monolithic programming.
Procedural programming:
 In this programming methodology, a program can be divided
into multiple sub programs.
 All the sub programs share the global data. so no security is
provided to the data against unauthorized or unexpected
changes.
 The control of the program can be moved from one part to
other part using only the jump statements like goto. This
causes lot of confusion to programmers when writing large
programs.
 Programming languages like FORTRAN, COBOL comes into
this category
 This methodology is suitable for developing medium size
applications

11
5
Layout of a program in Procedural programming
Structured Programming:
 In this programming methodology, the programs are divided
into sub-programs. The sub programs are also called as
functions or procedures or modules.
 In each sub program, local data are present. And the
statements in that sub program can work with that local data.
 The local data are hidden from other part of the program. This
improves the security to data at some level. In previous
methodologies, the data are completely global.
 Here also, the global data are present. The data items that are
used throughout the application are kept in the global section.
 Dividing a task into multiple sub tasks is called
modularization. This modularization allows the user to code
and test each module separately. For this reason the
structured programming is also called as modular
programming.
 The large programs can easily be managed with this approach.
 In structured programming, instead of using jump control
statements like goto, several other flow controls are
introduced. The new flow controls include selection and
repetition.
 The selection flow control indicates selection of one statement
from several statements to be executed.For this the keywords
like if, if – else, switch are introduced.
 In the repetition flow control, a set of instructions can be
executed iteratively until some specified condition becomes
false. For the keywords like while, do-while, for are introduced.

11
6
The complete syntax and meaning is explained in later
chapters in this book.
 The programming languages like Pascal and C are based on
structured programming paradigm.

Layout of a program in Structured programming


Object Oriented Programming:
When solving a large complex task, the programmers need to write
a lengthy program. In modular programming a lengthy program
consists of huge number of functions and variables. When the
length of program is very high and several data items and sub
programs are involved, then automatically the programmer gets
confusion. Sometimes the programmers getinto a loop in
understanding the program and may not come out of that
situation.To avoid such large complex implementation problems,
the programmers tried to have new alternatives. The result is
Object Oriented Programming.
In modular programming, the programmer thinks only about the
process of solving the problem. When the programmer focuses
only on process, control on sub programs and data items may be
lost. To avoid this situation, the programmers introduced new
approach of binding data items and concern operations into a
single unit. Such a unit is denoted as Object.
When accomplishing a task, the programmer concentrates on
data to be used and the operations to be performed on the data.
With this methodology programmer gets complete understanding

11
7
on data and related operations. So even when working with large
complex real world problems the programmer never lose grip on
the process. Here the objects are the key components in solving
any problem. So they denoted this paradigm as Object Oriented
Programming.
Every object in general, possesses data items and related
operations. The data items are secured, only the related
operations are performed on the data. The objects can also
communicate with each other through the operations. The data
items are called member data. The operations are member
functions.
“Object Oriented Programming (OOP) is a programming
methodology, in which the task or problem can be viewed as set of
objects and accomplishment of the task is possible with
communication between the objects”.
For example, if a college or university wishes to maintain their
data and operations with in computer. The OOP identifies the
objects in the environment and defines the communication among
the objects. The objects in the environment include student,
faculty, book, exam, and so on.

11
8
Object

Object oriented paradigm


Features of Object Oriented Programming (OOP):
The Object oriented programming paradigm is most widely used
in solving large complex problems. The core concept of this
methodology is object. So the programmers need to define, create
and manipulate the objects. Establishing communication between
objects is also essential to accomplish the task. The OOP provides
the following features for the problem solving.

 Objects  Encapsulation  Message


 Classes  Inheritance Passing
 Methods  Polymorphism  Reusability
 Abstraction  Dynamic  Delegation
Binding  Genericity
Objects:
An Object is essential concept of OOP. Any Problem can be viewed
as set of objects and their relationships. Every object has its own

11
9
properties and related operations. The properties mentioned as
data members and operations are taken as member functions or
methods. In OOP the objects represent real world entities. Any
entity like person, place, thing, event, and concept that involve in
solving the problem are taken as objects.
The set of objects that have common properties and operations
can be treated as class. In other words a class represents the
structure of the object. A single occurrence of the class is called
object.
An object is an essential concept of OOP, every object possesses its
own data members and member functions that are combined in its
class.
Examples for object and their properties are given below.

Class Examples for Properties or Data Member functions or


Objects of Members Methods or
class Operatons
Student Govind rollNumer getStudentDetails()
Akshara firstName showStudentDetails()
lastName findTotalMarks()
gender
course
Marks1
Marks2
Book Fundaments of ISBN getBookDetails()
Computers Title showBookDetails()
Programming Subject returnBookCost()
with C++ Pages
Cost
Course B.Sc courseId getCourseDetails()
B.Tech courseName showCourseDetails()
duration showEligibleCourses()
totalCredits
Classes
A class is a blue print or template for the object. The class shows
the structure of the object. In other words the class represents the

12
0
object. In a class the properties and operations of an object are
combined.
The basic idea of creating a class is that the data members and
operations on those data members can be tied into single unit.
The data members get security in such a way not to be accessed
by any other statements of the program. Only the member
functions can work on data members.
In general, the data members are declared under private section
and member functions are declared under public section in the
class. The members declared under public can be available for use
in any part of the program. But private members can be used only
in the member functions of that class.
Class is a blue print for an object. It combines data members and
member functions of common entities into single unit.

An example for Student class


Explanation: In line 1, class is the keyword and Student is tag
name. From line 4 to line 9, the properties of Student rollNumber,
firstName, lastName, gender, marks1 and marks2 are declared.
Here int and char are keywords to denote the type of the data that
can be stored with that name. From line 11 to 13 the member
functions are declared. The keyword private in line 3 denotes that
the data members are accessible to only student class member
functions. The keyword public in line 10 denotes the member
functions can be used in any part of the program.

12
1
Methods:
Method is another name for member function. A method defines
the operation to be performed on data members. Without
methods any object has no significance. The methods in a class can
be kept in private or public sections. The private methods are
accessible to only that class. The public methods are accessible to
the entire program. Member data of a class can be accessed with
public member functions from outside the class. In this way, the
direct access to member data in a class is restricted.

Student class with


Data members and member functions
Data Abstraction and Encapsulation:
The term abstraction indicates, mentioning the essential details
without giving the entire details. For example when a person
(driver) wants drive a car, he needs to know the features provided
by the car but he need not to know the complete internal
operations inside the car.
In the same way when a user wishes to use a code in OOP need
not to know the internal details mentioned in the code. Only the
user needs to know the essential details to use the code.
One of the constructs of OOP is class. When a user wish to
perform the operations mentioned in the class need not know the
implementation details of the member functions. Only the needs

12
2
to know how to invoke the member function, what are inputs it
takes and what output it gives.
In a class we combine the member variables and member
functions. The method of combining the member variables and
member functions is denoted as Encapsulation.
Combining the members in a class is done in three different ways.
 If the members are declared under public, the members
can be used anywhere in the program.
 If the members are declared under private, the members
can be used only within that class.
 If the members are declared under protected, the
members can be used in that class and its derived classes.
In this way the members in the class are declared, secured and
used. The data hiding is possible with the encapsulation.
Inheritance:
It is concept in OOP. It allows the user to create a new class from
existingclass. The new class is called derived class/child class/
sub class. Already existing class is called as base class/parent
class/super class.
The idea behind this concept is that when an object needs new
properties than the existing object, instead of defining the object
from the scratch, the programmer can extend the features of
existing object.This feature allows the user to use the available
code and to extend the code for fulfilling the new requirements.
With the property of inheritance the code duplication is avoided.
Existing code can be used instead of rewriting the code. The
hierarchy of the code is easily understood.

12
3
Figure 1 : Inheritance and its example
Polymorphism:
Polymorphism is composed with two terms poly and morphism.
The term poly refers many or more. And morphism is a condition
of having a specified form. As a whole the term Polymorphism in
OOP refers to mentioning of many forms with same name.
In other programming methodologies, a program can use a
variable name or a function name for only one specific purpose.
But in OOP, the polymorphism concept allows the programmer to
assign more than one purpose to a variable or a function based on
the context. So the variable or a function can exhibit different
behaviors in different contexts.
Suppose, When we want to find sum of two numbers, we can use
a function sum() with two parameters, and to find the sum of
three numbers,we can use the same function name sum() for
three numbers. The only difference is that the first one takes two
parameters and second one takes three parameters. The compiler
indentifies and calls the specified function with the number of
parameters mentioned in the function call. The concept of
polymorphism can be implemented in two ways : static binding
and dynamic binding.
Static Binding:
When a function call is found, then the compiler checks for the
declaration and definition of the function. If there is no matching
between function header and function declaration, the compiler

12
4
generates an error. If it finds a match to a function call then there
will be no error. The binding of function call to a function
definition at the time of compilation is denoted as compile time
binding or early binding or static binding.
Dynamic Binding:
In the hierarchy of class definitions, it means, when the concept of
Inheritance is used, the parent class and child class may have a
function with same name and same parameter list. In this case
the call to a function is identified with object of the class. When a
pointer to a base class object is used to call parent class function,
then the pointer must hold the parent class object reference. And
if the pointer is used to call the function of child class, then the
pointer must hold the object reference of the child class object. In
this way single pointer is used to invoke the functions available in
parent and child classes. But the object reference within the
pointer is made the difference. In this way the invocation of the
function is decided at the time of execution. This kind of
association or binding is called Dynamic binding or late binding or
Run-time binding.
Message Passing:
In OOP, Methods of a class are used to convey the message to an
object. Any object in general holds data and methods. Method
refers the action to be performed. The parameters in the method
call are the data to be sent to the object. Here the object is the
receiver. Performing an action or conveying a message to do
something on data of an object is denoted as message passing.

Figure 2 : Message Passing

12
5
Reusability:
The term Reusability indicates that the code written already can
be used over and again without rewriting in the programs.The
reusability can be achieved from the code written in the same
program or from other programs.
Inheritance allows the user to derive the features of existing class
to the new class without defining the same again.
Inheritance, Delegation/Containership and Genericity provide
reusability in different ways while creating new programs.
Delegation:
Suppose an Object is formed with two or more other objects. And
when that object receives a message, it sends the message to the
objects (its delegate objects) with which it is formed. In this way
Delegation is possible in OOP. It provides reusability.
Here the new object is composed with other objects, so this
concept is called composition. In other words an object is
contained in other object. So it is referred as containership.
For example, let’s consider computer as an object. It is composed
of other objects like processor and memory. The user sends a
message to computer, now the computer object sends the
message to its delegate object processor and the processor sends
the message to another object memory.

12
6
Figure 3 : An Example for Delegation
In the above example, Date class object and Course class objects
are the part of Student class object. It means the student object is
composed with Date and Course objects.
Genericity:
This feature of OOP allows the user to define template functions
and template classes. The template refers a pattern to design
something. In Programming, the template function is defined with
the entire logic to solve the task except the data types for the
parameters to the functions are left as common terms. Later when
the function is executed, the corresponding data types will be sent
as arguments to the function. In this method one function can be
used for many verities of data types. Here rewriting of code for
each of data type is avoided and reusability is provided.
For example, when a programmer wants to swap two values, if a
template function is written then it can swap the integers,
characters, floating point values and other. The programmers
need not to write separate function for each data type.

12
7
In the same way, template class can be defined to perform same
operations on different types of data with same class.
Merits and Demerits of Object Oriented Programming
Language
OOP offers several benefits compared to other programming
paradigms. Some of them are listed below:
Merits:
 Using Encapsulation technique, the data members and
member functions are tied into single unit. In this method the
data members get more security from unexpected
modifications in the program.
 Different security levels are provided using the keywords like
private, public and protected keywords.
 Binding of data and operations into single unit improved the
program understandability and enhanced the ability of writing
large complex programs.
 The abstraction feature allows the user to know only the
essential details and hides the internal details. So the users
need not to work more in solving the problems.
 Reusability with the features like Inheritance, Delegation and
Genericity reduce the length of the code and improves the
productivity of programs.
 The code already written can be extended to develop new
programs.

Demerits:
 The programs developed with OOP methodology needs high
processing capabilities.
 To develop a new large system using OOP, the high skilled
personnel are needed.
 The OOP is Optimum for large systems.
 Developing a user friendly system with OOP needs building of
much complex system.

Applications of OOP
The applications of OOP are spread across many areas. Few of
them are listed below:

12
8
Several artificial intelligence applications are developed with OOP
concepts.
 Expert systems, Neural networks, and large complex
databases applications are based OOP.
 User interfaces, Operating Systems, Compilers for many
languages are developed using OOP concepts.
 Several Computer Games, Graphics applications, Online
shopping Applications, Distributed systems, and many
Networks systems are also based on OOP.

12
9
Unit 2
Class

In C++, class is type, the entities that have common properties


and behavior are considered as class. So the programmers bind
the common properties and possible operations on those
properties. The result is denoted as class. It means the
programmer declares variables (properties) and defines operations
(functions) as single unit. That is called class.
 Class gives the blue print for objects.
 For the class declaration memory is not allocated, but memory
is allocated for the variables of class type when they are
created.
 A class can be viewed as data type. Here the programmer
mentions the data and operations on that data.
Defining the Class
class is a keyword in C++. It allows binding data and operations
into single unit. It means class keyword is used to define a data
type. Data members in a class are declared similar to ordinary
variables and the member functions can be declared or defined.
Both the data members and member functions can declared in
any of 3 sections: private, public and protected. Each section has
its own visibility.
class class_name
{
// some data
// some functions
};
Example:

13
0
Keywords: private and public
Keyword private refers the data members or functions declared
under private are only accessible with in the class. Whereas the
members declared under public keyword are public.The public
members can be accessed any where throughout the program.
Another keyword protected refers the members of the class can be
accessed within the class and in their derived classes. The private
keyword restricts the data access. The keyword private we can
achieve security to data. It is also called information hiding. The
private data can be accessed only with public functions of the
class.
C++ Objects
Object is an entity whose type is class. In programming, classes
are formed based on the properties of objects. If set of objects
share common properties and have same operations on those
properties, such properties and operations are combined into
single unit called class. An occurrence of class is an object. Class
represents structure of an object. Every object of a class consists
all the properties of that class and performs operations defined in
that class
Syntax to Define Object in C++
class_name object_name;
For the class Student, objects can be defined as:

13
1
Student obj1,obj2;
Here, two objects(obj1 and obj2) of Student class are defined.
Data members and Member functions
The properties or attributes declared in the class are called data
members. The operations defined in the class are denoted as
member functions. In the above class Student, rollNumber,
firstName, lastName, gender, marks1, marks2 are data members
and getStudentDetails() and showStudentDetails(), findTotalMarks()
are member functions.
Accessing Data Members and Member functions
The class members are accessed with objects. The object refers its
members using the dot(.) operator. The dot operators connect
object and its member while accessing.
For the object ob1 defined above, getStudentDetails() and
showStudentDetails(), findTotalMarks() functions can be accessed
as follows:
obj1. getStudentDetails()
obj1. showStudentDetails()
obj1. findTotalMarks()
With dot operator data members and member functions both can
be accessed from outside of the class. But here the members of
the class must not be private. Anyway the members can be
accessed within the class without use of object or dot operator.
object_name.data_memeber;//access to data member outside of
the class
Here we cannot access the data member of the above class
Student because all data members are private so the members
cannot be accessed outside that class.
The below Program demonstrates working with Objects and Class
in C++ .
1.#include <iostream.h>
2.class temp

13
2
3.{
4. private:
5. int data1;
6.float data2;
7.public:
8.void int_data(int d){
9.data1=d;
10. cout<<"Number: "<<data1;
11. }
12. float float_data(){
13. cout<<"\nEnter data: ";
14. cin>>data2;
15. return data2;
16. }
17. };
18. int main(){
19. temp obj1, obj2;
20. obj1.int_data(12);
21. cout<<"You entered "<<obj2.float_data();
22. return 0;
23. }

Run

Explanation :
In this program, two data members data1 and data2 and two
member function int_data()and float_data() are defined in temp
class. Two objects obj1 and obj2 of that class are declared.
Function int_data() for the obj1 is executed using code
obj1.int_data(12);, which sets 12 to the data1 of object obj1.
Then, function float_data()for the object obj2 is executed which
takes data from user; stores it in data2 of obj2 and returns it to
the calling function.
Note: In this program, data2 for object obj1 and data1 for object
obj2 is not used and contains garbage value.

13
3
Defining Member Function outside the Class
C++ provides two ways of defining member function. It means the
member functions can be defined with in the class declaration or
out side of the class declaration. When function is small, it is
better to define the function inside the class. But when function is
lengthy it is better to define outside of the class. The difference is
that the functions defined with in the class are treated as inline
function. If the functions have control structures and the code in
the function is more complex and lengthy then those are not
treated as inline. So, in order to avoid the complexity in the class
declaration it is better to define the functions outside of the class
declaration.When the function is defined outside, we use scope
resolution operator along with the class name.
Eg :temp ::float float_data(){
cout<<"\nEnter data: ";
cin>>data2;
return data2;
}
Objects as an argument to functions
In C++ programming, objects can be passed to function in similar
way as variables and structures.

13
4
Procedure to Pass Object to Function

Example to Pass Object to Function


// C++ program to add two complex numbers by passing
objects to //function.
1.#include <iostream.h>
2.class Complex
3.{
4. private:
5. int
real; 6.int
imag;
7.public:
8.Complex(): real(0), imag(0) { }
9.void Read()
10. {
11. cout<<"Enter real and imaginary
number respectively:"<<endl;
12. cin>>real>>imag;
13. }
14. void Add(Complex comp1,Complex comp2)
15. {
16. real=comp1.real+comp2.real;
17. imag=comp1.imag+comp2.imag;
18. }

13
5
20. {
21. cout<<"Sum="<<real<<"+"<<imag<<"i";
22. }
23. };
24. int main()
25. {
26. Complex c1,c2,c3;
27. c1.Read();
28. c2.Read();
29. c3.Add(c1,c2);
30. c3.Display();
31. return 0;
32. }
RUN

Explanation:
In line 26, three objects c1,c2 and c3 are declared. In line 27 and
28 values for c1 and c2 are given with Read() function. Line 13-18
Read() function is defined. In line 29, Add() function took c1 and
c2 objects as arguments. In line 14 to 18 Add() function is defined.
The Display() function defined between lines 19-22 displays
resulting object. In this program c1 & c2 are sent as an argument
to add() function.
Returning Object from Function
The syntax and procedure to return object is similar to that of
returning structure from function.

13
6
Example to Return Object from Function
1. #include<iostream.h>
2. class
Complex 3. {
4. private:
5. int real;
6. int imag;
7. public:
8. Complex(): real(0), imag(0){}
9. void Read()
10. {
11. cout<<"Enter real and imaginary
number respectively:"<<endl;
12. cin>>real>>imag;
13. }
14. Complex Add(Complex comp2)
15. {
16. Complex temp;
17. temp.real=real+comp2.real;
18. temp.imag=imag+comp2.imag;
19. return temp;
20. }
21. void Display()

13
7
22. {
23. cout<<"Sum="<<real<<"+"<<imag<<"i";
24. }
25. };
26. int main()
27. {
28. Complex c1,c2,c3;
29. c1.Read();
30. c2.Read();
31. c3=c1.Add(c2);
32. c3.Display();
33. return0;
34. }

Run

Explanation:
in line 14 to 20 add function is defined. In this function complex
object temp is returned. And the returned object is stored in c3 of
main function in line 31.
This Pointer
In C++ , there is a special pointer called this. Any object’s address
is implied with this pointer. It is an implicit pointer to all the
member functions. Whenever an object invokes a member
function from outside of the class, the address of the object is
available in that member function with name this. There are some
other functions named friend functions, these are not the
members of the class. So those functions have no implicit pointer
this.
Example:
1. #include <iostream.h>
2. class
Box 3. {

13
8
4. public:
5. Box()
6. {
7. cout <<"Constructor1 called." << endl;
8. length = 2;
9. breadth = 2;
10. height = 2;
11. }
12. Box(double l, double b, double h)
13. {
14. cout <<"Constructor2 called." << endl;
15. length = l;
16. breadth = b;
17. height = h;
18. }
19. double Volume()
20. {
21. return length * breadth * height;
22. }
23. int compare(Box box)
24. {
25. return this->Volume() > box.Volume();
26. }
27. private:
28. double length;// Length of a box
29. double breadth;// Breadth of a box
30. double height;// Height of a box
31. };

32. int main(void)


33. {
34. Box Box1(3.3, 1.2, 1.5);// Declare box1
35. Box Box2(8.5, 6.0, 2.0);// Declare box2

36. if(Box1.compare(Box2))
37. {
38. cout << "Box2 is smaller than Box1" <<endl;
39. }
40. else
41. {

13
9
42. cout << "Box2 is equal to or larger than Box1"
<<endl;
43. }
44. return 0;
45. }

Run

Explanation: In the above programs, Box objects are compared.


In line number 25, this pointer is used. to indicate the member of
current object this pointer is used.
Local class in C++
The variables declared inside the function are called local
variables. Their scope is limited to that function only. In C++, we
can declare a class inside a function. Such classes are local
classes. The local classes have visibility in that function only. It
means that the class can be useful to that function only. Outside
of the function is not recognized by the compiler.The local classes
are declared and used within a function. In a local class the
member functions must be defined with in the class only. And
static members are not allowed in local classes.

Example:
int func1()
{
class localclass1
{.....};
}
Nested classes
We have nested loops, nested blocks and nested functions.
Similarly C++ allows declaring a class inside other class. This is
called nesting of classes.

14
0
It means a class can be declared inside other class for the local
use. But C++ supports one excellent feature called inheritance. It
allows deriving the properties of one class to other. Because of
this feature the Nested classes are not widely used in C++
Example :
1 #include <iostream.h>
2 class Nest
3 {
4 public:
5 class Display
6 {
7 private:
8 int s;
9 public:
10 void sum( int a, int b)
11 { s =a+b; }
12 void show( )
13 { cout << "\nSum of a and b is:: " << s;}
14 };
15 };
16 void main()
17 {
18 Nest::Display x;
19 x.sum(12, 10);
20 x.show();
21 }
Run
Sum of a and b is: 22
In the above example, the nested class "Display" is given as
"public" member of the class "Nest".
Empty Class
C++ classes are declared without mentioning any attributes and
operations. It means that the internal representation of the class
is not defined. But it is known that such a class may be needed.
Eg:
#include <iostream.h>

14
1
class Sample {
};
int main()
{
std::cout << "sizeof(Sample): " << sizeof(Sample)
<< '\n';
}
For many platforms, this program will print 1 as size of Sample.
static Keyword
static Variables
The variables that are declared with static keyword are static
variables. These variables are initialized once and allocated
storage only once at the beginning of program execution. A static
variable retains its value until the end of program. So the value of
the variable persists in different function calls.

#include<iostream.h>
void fun()
{
static int i = 1;
i++;
cout << "i="<<i<<endl;
}
voidmain()
{
fun();
fun();
fun();
}

i is static, and it retains its value during different function calls. i


is initialized to 1 at the beginning. The output for the program will
be

i=2
i=3
i=4

14
2
Static Member Variables
member variables can be declared with static keyword. unlike
other member variables, static member variables are associated
with class. It means all the member variables are assocated with
objects of the class. Whereas static member variables are not
associated with any one object individually.
static data members are stored in memory separately, and these
members must be initialized. Only one copy of static member
exists for the entire class and it is not related to the number of
objects created. For all objects only one copy of static member will
exist.
The below program distinguish between static data member and
other data member.
#include<iostream.h>
class StaticDemo
{
static int
s; int x;
public:
StaticDemo()
{
x=0;
}
void show()
{
++x;
++s;

cout<<"x= "<<x<<"s="<<s<<endl;
}
};
int StaticDemo :: s=0;

void main()
{
StaticDemo ob1, ob2,ob3;
ob1.show();
ob2.show();
ob3.show();
}

14
3
Output:

Explanation:
In the above program, s is a static member variable, it is created
only once when the program execution begins. And it is destroyed
when the program comes to end. In the program three objects are
created and for each object x available as separate copy. But s is
common to all objects. And value of s is retained through out the
program.
Static member function
Similar to static member variable, only one copy of static member
function is created. All objects have to share the same copy of the
static member. The restriction is that, a static member function
can access only static data members or functions. Accessing the
static member functions is possible with class name and scope
resolution operator. It is also possible to access static member
functions with objects.
The below program demonstrates static member function.
#include<iostream.h>
class StaticDemo2
{
static int s;

public:

static void show()


{
++s;
cout<<"s= "<<s<<endl;
}
};
int StaticDemo2 :: s=0;

void main()
{
StaticDemo2::show();

14
4
StaticDemo2::show();
StaticDemo2::show();
}
output

Explanation:
In the above program, show() is a static member function and s is
a static member variable. When a user wish to have a function or
variable that is common to entire class and it is not specific to an
object the static members are useful.
Friend functions
In C++, private members of the class can be accessed with in the
class only. User can access private members through public
member functions. Another way to access private members of the
class is friend function. Friend functions are special functions,
which can access private members of the class through the object
and dot operator.
Characteristics of friend functions
 Even though the friend function is declared with in the class,
it is not treated as member of the class.
 Friend function is not a member of the class, so it is not
invoked with object and dot operator. But within the friend
function the members are accessed with object and dot
operator.
 Friend function declaration begins with the keyword friend.
 Friend functions can be declared with in the class either in
private or public section. These sections do not change the
meaning of declaration.
 Friend functions take one or more objects as arguments. The
members of objects are accessed in the friend function.

14
5
Declaration:
class class_name
{
..................
friend return_type function_name(argument/s);
..................
}
Example
/* C++ program to demonstrate the working of friend function.*/
1. #include <iostream.h>
2. class
Distance 3. {
4. private:
5. int meter;
6. public:
7. Distance() { meter =0; }
8. friend int func(Distance);//friend
function 9. };
10. int func(Distance d)//function definition
11. {
12. d.meter=5;//accessing private data from
non- member
//function
13. return d.meter;
14. }
15. int main()
16. {
17. Distance D;
18. cout<<"Distace: "<<func(D);
19. return 0;
20. }
Run
Distance: 5
Friend Class
Suppose a function is made friend of a class, that function can
access private members of given object. To make all the member
functions of one class, friends of other class, we declare the class

14
6
as friend class. The friend class makes all its member functions as
friend functions other class. But here friendship is not bi
directional. It means X class is friend of Y means the member
functions of X are friend functions of Y. But it does not mean that
member functions of Y are friends of X
For example:
.....................
class A{
friend class B;// class B is a friend class
..... ..... .....
}
class B{
..... ..... .....
}
If B is declared friend class of A then, all member functions of
class B can access private data and protected data of class A but,
member functions of class A cannot access private and protected
data of class B. Remember, friendship relation in C++ is
granted,not taken.
A C++ program to demonstrate friend Class
#include <iostream.h>
class A {
private:
int a;
public:
A() { a=0; }
friend class B;// Friend Class
};

class B {
private:
int b;
public:
void showA(A& x) {
// Since B is friend of A, it can access
// private members of A
cout << "A::a=" << x.a;

14
7
}
};

int main() {
A a;
B b;
b.showA(a);
return 0;
}
Output:
A::a=0
Constructors
 Constructors, the name itself indicate that they construct the
objects. When an object is created a constructor is called
automatically by the compiler.
 Constructors take the values from the user and initialize the
member of the class. Users have no direct access to the
member of the class directly.Data members are declared
under private in general.
 When an object is created, the corresponding constructor is
called to assign the values to the data member.
class A
{
int x;
public:
A();//Constructor
};
 The constructor is declared and defined with in the class. It is
also possible to define the constructor outside the class
declaration.
 The constructor is special kind of function, the name of the
constructor and class name is always same. It is a rule not
convention.
 Constructor is a member function but it doesn’t have any
return value. So there will be no return type in constructor
declaration.

14
8
class A
{
int i;
public:
A(); //Constructor declared
};

A::A()// Constructor definition


{ i=
1;
}
Types of Constructors
Constructors are of three types:
 Default Constructor
 Parameterized Constructor
 Copy Constructor
Default Constructor
A constructor that has no arguments is called default constructor.
User wish to keep preset values in the members of the function,
there is no need of sending values separately. It is easy to keep
the values directly in the definition of the constructor. It means
the default values are kept in the members of the object through
default constructor.
Syntax :
class_name ()
{ Constructor Definition }
Example :
1 class Cube
2 {
3 int side;
4 public:
5 Cube()
6 {
7 side=10;

14
9
8 }
9 };
10 int main()
11 {
12 Cube c;
13 cout <<
c.side; 14}
Output : 10
Declaring and defining default constructor is essential, when
there are other constructors declared in the class otherwise the
compiler will generate an error.
Parameterized Constructor
When the user wishes to send values explicitly at the time of
object creation, the values are sent as parameters to the
constructor. This constructor is called parameterized constructor.

Example :
1. class Cube
2. {
3. int side;
4. public:
5. Cube(int
x) 6. {
7. side=x;
8. }
9. };

10. int main()


11. {
12. Cube c1(10);
13. Cube c2(20);
14. Cube c3(30);
15. cout << c1.side;
16. cout << c2.side;
17. cout << c3.side;
18. }

15
0
OUTPUT : 10 20 30
By using parameterized constructor in above case, we have
initialized 3 objects with user defined values. We can have any
number of parameters in a constructor.
Copy Constructor
If the user wishes to create an object with the same values of
other object, then he/she sends the object as parameter to
constructor. It means here the contents of one object are copied
into the other object through the constructor. This is the reason
why the constructor is called copy constructor. To avoid changes
on object that is sent as parameter is mentioned as constant
parameter.

Syntax of Copy Constructor


class-name (const class-name
&)
{
....
}
class Cube
{
int side;
public:
Cube(const Cube& ob)//copy constructor
{
side=ob.size;
}
};
Constructor Overloading
There may be one or more data members in a class, among those
members the user may wish to send values to data members
optionally. It means the user may send values to few or more data
members. Sometimes the user may not send values to members.
When user does not give any values through constructor it is
denoted as default constructor. When the user sends the values
15
1
as arguments through constructor then it is called parameterized

15
2
constructor. In case of parameterized constructors, the user may
send different number of arguments based on requirement and
the remaining values are directly mentioned in the definition of
the constructor. So here user gives different parameter lists with
the same function name and the function is the constructor, so it
is called Constructor Overloading.
Example:
1. #include<iostream.h>
2. class
Student 3. {
4. int rollno;
5. int marks;
6. public:
7. Student(int
x) 8. {
9. rollno=x;
10. marks=0;
11. }
12. Student(int x, int m)
13. {
14. rollno=x ;
15. marks=m;
16. }
17. void display()
18. {
19. cout<<"\n rollno="<<rollno;
20. cout<<"\n marks="<<marks;
21. }
22. };

23. int main()


24. {
25. Student A(10);
26. Student B(11,95);
27. A.display();
28. B.display();
29. return 0;
30. }

15
3
Explanation: in line number 7 student constructor with one
parameter and in line number 12 student constructor with two
parameters are defined. This is an example for constructor
overloading.
Destructors
 Any object that is created in a program exists throughout the
program. This may lead to memory shortage problem.
 C++, supports another special function called destructor as a
counter to constructor. It means when an object is created the
constructor is called automatically. And when the object loses
its scope, the destructor is called automatically.
 Similar to constructor, the destructor has same name as class
name. It does not take arguments. It also has no return type.
But it is preceded by tilde ~ sign
class A
{
public:
~A();
};
Destructors will never have any arguments.

Example to see how Constructor and Destructor is called


1. #include<iostream.h>
2. class
A 3. {
4. public:
5. A()
6. {
7. cout << "\n Constructor called";
8. }

9. ~A()
10. {

15
4
11. cout << "\n Destructor called";
12. }
13. };
14. int main()
15. {
16. A obj1;// Constructor Called
17. int x=1;
18. if(x)
19. {
20. A obj2;// Constructor Called
21. }// Destructor Called for obj2
22. return 0;
23. } //Destructor called for obj1

Run

Explanation: in line number 16, obj1 object is created so the


constructor is called. Similarly in line number 20 obj2 object is
created so the constructor is called again. In line 21 obj2 lost its
scope, so the destructor is called. In line 23, obj1 lost its scope so
again destructor is called.
A Program to print student details.

#include<iostream.h>
class student
{
private:
int sno;
char sname[20];
int marks;
public:
void getData();
void
showData();

15
5
};
void student::getData()
{
cout<<"Enter
sname:"; cin>>sname;
cout<<"Enter sno:";
cin>>sno;
cout<<"Enter
marks:"; cin>>marks;
}
void student::showData()
{
cout<<"\nsname:"<<sname;
cout<<"\nsno:"<<sno;
cout<<"\nmarks:"<<marks;
}
void main()
{
student s;
s.getData();
s.showData();
}

Output:

Program to demonstrate dynamic memory allocation with


constructors and destructors
#include <iostream.h>
class Sample
{
public:

15
6
Sample() {
cout << "Constructor is called" << endl;
cout << "Object created" << endl;

}
~Sample() {
cout << "Destructor is called" << endl;
cout << "Object destroyed" << endl;
}
};

int main()
{
Sample* s = new Sample[2];
//creation of two objects with the name
s delete [] s; // Deletion of objects
return 0;
}

A program to find area of rectangle , square and circle

#include <iostream.h>
class Area
{
private:
int
length;
int breadth;
int side;
float radius;

15
7
Area();
Area(int,int);
Area(int);
Area(float);

int rectArea ()
{
return (length * breadth);
}
int sqrArea ()
{
return (side*side);
}
float circleArea ()
{
return (3.14*radius*radius);
}

};

Area::Area()
{
length = 0;
breadth = 0;
side=0;
radius=0;
}
Area::Area(int x, int y)
{
length = x;
breadth = y;
}

Area::Area(int x)
{
side = x;

}
Area::Area(float x)

15
8
{
radius = x;

int main ()
{
Area rect =new Area(5,6);
cout << "\nThe area of rectangle is :: " <<
rect.rectArea()<< endl;

Area sqr = new Area(3);


cout << "\nThe area of square is :: " <<
sqr.sqrArea()<< endl;

Area circle = new Area(3.2);


cout << "\nThe area of square is :: " <<
circle.circleArea()<< endl;

return 0;
}

Program to demonstrate different types of constructors.


#include <iostream.h>
class Rectangle {
private:
int length;
int breadth;
public:

Rectangle();// simple constructor


Rectangle(int l, int b);//parameterized constructor
Rectangle( const Rectangle &obj);// copy constructor
void showData();

15
9
};

// constructorsdefinitions
Rectangle::Rectangle() {
cout << "Default constructor called" << endl;
length=0;
breadth=0;
}

Rectangle::Rectangle(int l, int b) {
cout << "parameterized constructor called" << endl;
length=l;
breadth=b;
}

Rectangle::Rectangle(const Rectangle &obj) {


cout << "Copy constructor called " << endl;
length = obj.length;
breadth=obj.breadth;
}

void Rectangle::showData() {
cout<<"length="<<length<<endl;
cout<<"breadth="<<breadth<<endl;
}

// Main function for the program


void main() {
Rectangle r1; //default constructor is called.
cout<<"r1 object"<<endl;
r1.showData();

Rectangle r2(3,5);
cout<<"r2 object"<<endl;
r2.showData();

Rectangle r3(r2);
cout<<"r3 object "<<endl;

16
0
r3.showData();
}

16
1
Operator Overloading:

In C++ programming, it allows the programmer to give special


meaning to an operator when they operate on class objects. It is
known as operator overloading.
1. The operations on built-in-data types are defined
in complier. The operator and their meaning is defined
for pre-defined data types. The operator overloading
refers that the operations that are defined on predefined
types with operators can be extended to user defined
data types
2. The assignment operator (=) and address of (&)
operators are need not to be overloaded specially.
Because these two operators are already overloaded in C+
+ library. For example: If obj1 and obj2 are two objects
of same class then, we can use code
obj1=obj2; without overloading = operator. = operator will
copy the contents object of obj2 to obj1. Similarly, we can
use address operator directly without overloading. The &
operator will return the address of object in memory.
3. For every operator precedence and associativity
are defined in compiler. When operators are overloaded,
the programmer should not change the precedence and
associativity.
4. In C++ all operators can’t be overloaded. The
operators that cannot be overloaded in C++ are ::(scope
resolution), .(member selection), .*(member selection
through pointer to function) and ?:(ternary operator).
To overload an operator, the operator function is defined inside a
class as shown:
class class_name
{
……………

16
2
public:
return type operator sign(arguments)
{
…………
}
……………
};
Overloading Unary Operator with member function.
Unary operator takes only one operand. In this case, while
overloading unary operator for an object, we use only one object.
When unary operator is overloaded with member function, no
arguments are sent to member function. The underlying object
used to call the member function itself gives the values for
performing an operation.
Example:
1. #include <iostream.h>
2. class
temp 3. {
4. private:
5. int count;
6. public:
7. temp()
8. {
9. count=5;
10. }
11. void operator ++() //member functionfor
//overloading
12. {
13. count=count+1;
14. }
15. void Display() { cout<<"Count: "<<count; }
16. };
17. int main()
18. {
19. temp t;
20. ++t;/* operator function void operator ++()
is called */
21. t.Display();

16
3
ALPHORES W.D.C, KARIMNAGAR
22. return 0;
23. }
24. }
Run:
Count: 6
Explanation: In the above program t is an object of temp class. t
has only one member variable count. When ++t is executed in line
20, the member function written for overloading ++ is executed
and count value is increased by 1.
Overloading Unary Operator with friend function
It is possible to overload Unary Operator with friend function. In
this case the friend function takes one argument by
reference.Friend function accesses the members of the object with
dot operator. The changes made to the object in the friend
function become permanent as it is sent by reference.
Example:
1. #include <iostream.h>
2. class
temp 3. {
4. private:
5. int count;
6. public:
7. temp(
) 8. {
9. count=5;
10. }
11. friend void operator ++(temp& ob) {
12. ob.count=ob.count+1;
13. }
14. void Display() { cout<<"Count: "<<count; }
15. };
16. int main()
17. {
18. temp t;
19. ++t;/* operator function void operator ++() is
called */
20. t.Display();

16
4
ALPHORES W.D.C, KARIMNAGAR
21. return
0;
22. }
Run:
Count: 6
Explanation: In the above program, t is an object of temp class. t
has only one member variable count. When ++t is executed in line
19, the friend function written for overloading ++ is executed and
count value is increased by 1. The friend function has one
argument of temp class by reference.
Overloading binary operator with member function
Binary Operators accept two operands and perform operation.
Arithmetic operators are most commonly used operators in C++.
In C++ it is possible to overload all the arithmetic operators. When
binary operator is overloaded with member function, it takes only
one argument. The other argument is implicitly available. It
means the underlying object that is used to call the member
function is the first argument and argument sent to the function
is the second argument. The resulting object is returned from the
function. In the below example, we have overridden
the + operator, to add to Time(hh:mm:ss) objects.
Example: overloading '+' Operator to add two time object
1. #include< iostream.h>
2. #include< conio.h>
3. class
time 4. {
5. int h,m,s;
6. public:
7. time()
8. {
9. h=0, m=0; s=0;
10. }
11. void getTime();
12. void show()
13. {
14. cout<< h<< ":"<< m<< ":"<< s;
15. }

16
5
ALPHORES W.D.C, KARIMNAGAR
16. time operator+(time);//overloading '+' operator
17. };
18. time time::operator+(time t1)//operator function
19. {
20. time t;
21. int a,b;
22. a=s+t1.s;
23. t.s=a%60;
24. b=(a/60)+m+t1.m;
25. t.m=b%60;
26. t.h=(b/60)+h+t1.h;
27. t.h=t.h%12;
28. return t;
29. }
30. void time::getTime()
31. {
32. cout<<"\n Enter the hour(0-11) ";
33. cin>>h;
34. cout<<"\n Enter the minute(0-59) ";
35. cin>>m;
36. cout<<"\n Enter the second(0-59) ";
37. cin>>s;
38. }
39. void main()
40. {
41. clrscr();
42. time t1,t2,t3;
43. cout<<"\n Enter the first time ";
44. t1.getTime();
45. cout<<"\n Enter the second time ";
46. t2.getTime();
47. t3=t1+t2;//adding of two time object using '+'
operator
48. cout<<"\n First time ";
49. t1.show();
50. cout<<"\n Second time ";
51. t2.show();
52. cout<<"\n Sum of times ";
53. t3.show();
54. getch();

16
6
ALPHORES W.D.C, KARIMNAGAR
55. }
RUN:

Explanation : Time objects t1,t2,t3 are declared in line 42. Each


time object consists three member variables hours (h), minutes
(m)and seconds(s). When t1+t2 statement is executed in line 47,
the member functionwritten for overloading + operator is
executed. The overloaded function is defined between 18 to 29
lines. The two time objects are added and resulting object is
returned.
Overloading binary operator with friend function
When a binary operator is overloaded with friend function, the
function takes two arguments. Both arguments are of class type.
The arguments are sent by reference. Even the arguments can be
sent by value also. But when arguments sent by reference, the
memory is saved. And to avoid unexpected changes, the
arguments can be sent as constant arguments by modifying with
const keyword.
Example:
1. #include<iostream.h>
2. #include<conio.h>
3. class time

16
7
ALPHORES W.D.C, KARIMNAGAR
4. {
5. int h,m,s;
6. public:
7. time()
8. {
9. h=0, m=0; s=0;
10. }
11. void getTime();
12. void show()
13. {
14. cout<< h<< ":"<< m<< ":"<< s;
15. }
16. friend time operator+(const time& t1, const
time& t2); //friend function
17. };
18. time operator+(const time& t1, const time& t2)
19. {
20. time t;
21. int a,b;
22. a=t1.s+t2.s;
23. t.s=a%60;
24. b=(a/60)+t1.m+t2.m;
25. t.m=b%60;
26. t.h=(b/60)+t1.h+t2.h;
27. t.h=t.h%12;
28. return t;
29. }
30. void time::getTime()
31. {
32. cout<<"\n Enter the hour(0-11) ";
33. cin>>h;
34. cout<<"\n Enter the minute(0-59) ";
35. cin>>m;
36. cout<<"\n Enter the second(0-59) ";
37. cin>>s;
38. }
39. void main()
40. {
41. clrscr();
42. time t1,t2,t3;

16
8
ALPHORES W.D.C, KARIMNAGAR
43. cout<<"\n Enter the first time ";
44. t1.getTime();
45. cout<<"\n Enter the second time ";
46. t2.getTime();
47. t3=t1+t2;//adding of two time object using '+'
operator
48. cout<<"\n First time ";
49. t1.show();
50. cout<<"\n Second time ";
51. t2.show();
52. cout<<"\n Sum of times ";
53. t3.show();
54. getch();
55. }
RUN:

Explanation : Time objects t1,t2,t3 are declared in line 42. Each


time object consists three member variables hours (h), minutes
(m)and seconds(s). when t1+t2 statement is executed in line 47,
the friend function written for overloading + operators is executed.
the overloaded function is definedbetween 18 to 29 lines. The two
time objects are added and resulting object is returned.
Overloading Relational operator
We can also overload Relational operators like < , >,
== , != , >= , <= etc. to compare two user-defined object.

16
9
ALPHORES W.D.C, KARIMNAGAR
Example
1. #include<iostream.h>
2. class time
3. {
4. int hr,min,sec;
5. public:
6. time()
7. {
8. hr=0, min=0; sec=0;
9. }
10. time(int h,int m, int s)
11. {
12. hr=h, min=m; sec=s;
13. }
14. friend int operator==(time &t1, time
&t2);//overloading '==' operator
15. };
16. int operator== (time &t1, time &t2)//operator
function
17. {
18. return ( t1.hr == t2.hr &&
19. t1.min == t2.min &&
20. t1.sec == t2.sec );
21. }
22. void main()
23. {
24. time tm1(3,15,45);
25. time tm2(3,15,46);
26. if(tm1==tm2)
27. {
28. cout<<"True";
29. }
30. else
31. {
32. cout<<"False";
33. }
34.
}
Output
False
17
0
ALPHORES W.D.C, KARIMNAGAR
Overloading insertion and extraction operators
In this case, the object must be returned by reference from
theoverloaded function. For insertion operator ostream and for
extraction operator istream objects are used. The overloaded
functions must be friend functions. The arguments must be sent
by reference
Example: overloading << Operator and >> operator
1. #include<iostream.h>
2. #include<conio.h>
3. class time
4. {
5. int hr,min,sec;
6. public:
7. time()
8. {
9. hr=0, min=0; sec=0;
10. }
11. time(int h,int m, int s)
12. {
13. hr=h, min=m; sec=s;
14. }
15. friend istream& operator >> (istream
&in,time &tm);//overloading '>>' operator
16. friend ostream& operator << (ostream &out,
time &tm);//overloading '<<' operator
17. };
18. ostream& operator<< (ostream &out, time
&tm)//operator function
19. {
20. out << "Time is " << tm.hr << "hour : " <<
tm.min << "min : " << tm.sec << "sec";
21. return out;
22. }
23. istream& operator>> (istream &in, time
&tm)//operator function
24. {
25. in>>tm.hr>>tm.min>>tm.sec;
26. return in;

17
1
ALPHORES W.D.C, KARIMNAGAR
27. }
28. void main()
29. {
30. time tm1();
31. time tm2(3,15,45);
32. cout<<"enter time :";
33. cin>>tm1;
34. cout<<tm1;
35. cout<<tm2;
36. }
Type Conversion
Implicit TypeConversion
C++ is a strong typed language. All initialization and assignments
of identifiers are checked at compile time.
int m ;
float x = 2 . 531;
m = x ;// ok
converts x to an integer before its value is assigned to m.Thus the
fractional part is truncated.
Conversion of one type of value to other type automatically is
known as implicit type conversion.
Explicit Type Conversion
C++ permits explicit type conversion of variables or expressions
using the type cast operator. Some times a programmer needs to
convert a value from one type to another type. A situation where
the compiler will not do it automatically.Type conversions
specified by the programmer are referred to as Explicit type
conversion (Casting) The following two notations are used for
casts.
( type-name )expression
type-name( expression )
Eg:
average = sum /( float ) i ;

17
2
ALPHORES W.D.C, KARIMNAGAR
average = sum /float ( i ) ;
Conversions between Objects and Basic Types
Three types of situations might arise in the data conversion
between in compatible types:
1 Conversion from built-in type to class type.
2 Conversion from class type to built-intype.
3 Conversion from one class type to another class type.
When we want to convert between user-defined datatypes and
basic types, we can't rely on built-in conversion routines, since
the compiler doesn' know anything about user-defined types.
Basic toClassType
To go from a basic type to a user-defined type, we use a
constructor with one argument.These are sometimes called
conversion constructors. A single argument constructor is a
constructor that may be called with only one argument.Such a
constructor may declare a single parameter or it may declare
multiple parameters, with each parameter after the first having a
default value. Here is one single-argument constructor example.
string : : string ( char *a )
{
length =strlen ( a ) ;
P = newchar [ length + 1 ] ;
strcpy ( P , a ) ;
}
This constructor builds a string type object from a char* type
variable a. The variables length and P are the data members of the
class string. Once this constructor has been defined in the string
class, it can be used for conversion from char *type to string type.
string str1,str2 ;
char *name1 = " Computer " ;
char *name2 = " Science" ;
str1 = string ( name1 ) ;

17
3
ALPHORES W.D.C, KARIMNAGAR
str2 = name2 ;
The statement
str1 = string ( name1 ) ;
first convert sname1 from char* type to string type and then
assigns the string type values to the object str1.The statement
str2 = name2 ;
also does the same job by invoking the constructor implicitly.
Class to BasicType
C++ allows us to define a overloaded casting operator function,
usually referred to as a conversion function,
operator typename ( )
{
Function statements
}
This function converts a class type data to typename. For
example, the operator double ( ) converts a class object to type
double, the operator int ( ) converts a class type object to type int,
and so on.
Consider the following conversion function:
Class Rational
{
public :
.......
Operator double( )const ;
};
This function would be automatically invoked in contexts like this:
Rational r ( 1, 2 ) ;//r has the value 1/2
doubled = 0.5*double ( r ) ;//converts r to double
//then does multiplication
17
4
ALPHORES W.D.C, KARIMNAGAR
or
doubled = 0.5*r ;//same as above
A casting operator function should satisfy the following
conditions:
It must be a class member
It must not specify a return type
It must not have any arguments
Conversion Between Objects of Different Classes
The same two methods just shown for conversions between basic
types and user defined types also apply to conversions between
two user defined types. That is, you can use a one-argument
constructor or you can use a conversion operator function. The
choice depends on whether you want to put the conversion
routine in the class declaration of the source object or of the
destination object.
For example ,suppose you say
X objectX ;
Y objectY ;
object = objectY ;
Y is known as the source class and X is known as the destination
class.
When the source object needs to be converted a casting operator
function can be used. When the destination object needs to be
converted a single argument constructor function can beused.
Aggregation
C++ supports the concept of aggregation.It is a process in which
one class defines another class as any entity reference. Reuability
is achieved with this method. It represents HAS-A relationship. An
association between classes is created.

17
5
ALPHORES W.D.C, KARIMNAGAR
An example of aggregation where Employee class has the
reference of Address class as data member is given below. Here, it
can reuse the members of Address class.
1. #include <iostream.h>
2. #include<string.h>
3. class Address {
4. public:
5. char addressLine[20];
6. char city[15];
7. char state[15];
8. Address(char s1[], char s2[], char s3[])
9. {
10. strcpy(addressLine , s1);
11. strcpy(city , s2);
12. strcpy(state, s3);
13. }
14. };
15. class Employee
16. {
17. private:
18. Address* address;//Employee HAS-A Address
19. public:
20. int id;
21. char name[20];
22. Employee(int id, char name[], Address* address)
23. {
24. this->id = id;
25. strcpy(this->name , name);
26. this->address = address;
27. }
28. void display()
29. {
30. cout<<id <<" "<<name<< " "<<
31. address->addressLine<< " "<< address->city<< "
"<<address->state<<endl;
32. }
33. };
34. int main(void) {
35. Address a1= Address("#23,
Ramnagar","Warangal","TS");
36. Employee e1 = Employee(111,"Raman",&a1);
37. e1.display();
38. return 0;
39. }

17
6
ALPHORES W.D.C, KARIMNAGAR

Unit 3
Inheritance

Inheritance is the capability of one class to acquire properties and


characteristics from another class. The class whose properties are
inherited by other class is called the Parent or Base or Super
class.
And, the class which inherits properties of other class is
called Child or Derived or Sub class. Inheritance makes the code
reusable. When we inherit an existing class, all its methods and
fields become available in the new class, hence code is reused.
All members of a class except Private, are inherited
Purpose of Inheritance
 Code Reusability
 Method Overriding (Hence, Runtime Polymorphism.)
 Use of Virtual Keyword
Basic Syntax of Inheritance
The general form of declaring a derived class
Visibility Mode is used to specify, the mode in which the
properties of superclass will be inherited into subclass, public,
privtate or protected.
class derived-class-name : [visibility mode] base-class-name
{
…….
……..
};
Inheritance Visibility Mode
We can inherit a class in 3 ways. It can either be private,
protected or public.

17
7
ALPHORES W.D.C, KARIMNAGAR
1) Public Inheritance
This is the most widely used inheritance mode. In this the
protected member of super class becomes protected members of
sub class and public becomes public.
class Subclass : public Superclass
2) Private Inheritance
In private mode, the protected and public members of super class
become private members of derived class.
class Subclass : Superclass// By default its private inheritance
3) Protected Inheritance
In protected mode, the public and protected members of Super
class become protected members of Sub class.
class subclass : protected Superclass
Table showing all the Visibility Modes

Derived Class Derived Class Derived Class

Base class Public Mode Private Mode Protected Mode

Private Not Inherited Not Inherited Not Inherited

Protected Protected Private Protected

Public Public Private Protected

Types of Inheritance
In C++, we have 5 different types of Inheritance. Namely,
 Single Inheritance
 Multiple Inheritance
 Hierarchical Inheritance
 Multilevel Inheritance
 Hybrid Inheritance (also known as Virtual Inheritance)

17
8
ALPHORES W.D.C, KARIMNAGAR
Single Inheritance
In this type of inheritance one derived class inherits the
properties/characteristics from only one base class. It is the
simplest form of Inheritance.

Single Inheritance
The below program demonstrates single Inheritance
1. #include<iostream.h>
2. #include<conio.h>
3. class Student {
4. public:
5. int sno;
6. char name[20], course[20];

7. void get() {
8. cout << "Enter the student number:";
9. cin>>sno;
10. cout << "Enter the student name:";
11. cin>>name;
12. cout << "Enter the course:";
13. cin>>course;
14. }
15. };

16. class Result : public Student {


17. int marks1, marks2, total;
18. float avg;
19. public:

20. void get1() {

17
9
ALPHORES W.D.C, KARIMNAGAR
21. cout << "Enter marks1:";
22. cin>>marks1;
23. cout << "Enter marks2:";
24. cin>>marks2;
25. }

26. void calculate() {


27. total = marks1+marks2;
28. avg= total/2.0;
29. }

30. void display() {


31. cout<<sno<<"";
32. cout<<name<<"";
33. cout<<marks1<<"";
34. cout<<marks2<<"";
35. cout<< total<<"";
36. cout<<avg<<"";
37. }
38. };

39. void main() {


40. int i, n;
41. char ch;
42. Result s[10];
43. clrscr();
44. cout << "Enter the number of students:";
45. cin>>n;
46. for (i = 0; i < n; i++) {
47. s[i].get();
48. s[i].get1();
49. s[i].calculate();
50. }
51. cout << "\nsnosnamemarks1 marks2 total avg \n";
52. for (i = 0; i < n; i++) {
53. s[i].display();
54. cout<<endl;
55. }
56. getch();
57. }

18
0
ALPHORES W.D.C, KARIMNAGAR

58. Output:

Explanation : In the above program,student is the super class and


Result is the sub class. Properties of student class are derived and
used in the sub class Result.
Multiple Inheritance
In this type of inheritance, a single derived class may inherit the
properties/characteristics from two or more base classes.

Multiple Inheritance
The below program demonstrates Multiple Inheritance:

1. #include<iostream.h>

18
1
ALPHORES W.D.C, KARIMNAGAR
2. #include<conio.h>
3. class Student//Base Class1
4. {
5. int sno;
6. char name[20];
7. public:
8. void getData()
9. {
10. cout << "Enter sno, name";
11. cin >> sno >> name;
12.}
13.void putData()
14.{
15. cout << "sno=" << sno<< endl;
16. cout <<"Name=" << name << endl;
17.}
18.};
19.class Exam //Base class2
20.{
21. protected:
22. int marks1, marks2;
23. public:
24. void getMarks()
25.{
26. cout <<"Enter marks1, marks2";
27. cin >> marks1 >> marks2;
28.}
29.void putMarks()
30.{
31. cout << "marks1=" << marks1 << endl;
32. cout << "marks2=" << marks2 << endl;
33.}
34.};
35.class Result : public Student, public Exam
//Derived Class//
36.{
37. int total;
38. float avg;
39. public :

18
2
ALPHORES W.D.C, KARIMNAGAR
40. void showResult()
41.{
42. total=marks1+marks2;
43. avg=total/2.0;
44. cout << "Total=" << total << endl;
45. cout << "Average=" << avg << endl;
46.}
47.};
48.void main()
49.{
50. Result r; //Object
51. clrscr();
52.r.getData();
53.r.getMarks();
54.r.putData();
55.r.putMarks();
56.r.showResult();
57.getch();
58.}
Output.

Explanation:
In the above example , Student and Exam are two super classes
and Result is the sub class. Properties of the two super classes
are used in the sub class. It demonstrates the multiple
inheritance.
Hierarchical Inheritance
In this type of inheritance, multiple derived classes inherit the
properties/characteristics from a single base class.

18
3
ALPHORES W.D.C, KARIMNAGAR

Hierarchical Inheritance
The below program demonstrates Hierarchical Inheritance:
#include <iostream.h>
#include <conio.h>
class Person 4. {
char name[20],gender[10];
int age;
public:
void getPersonData() 9. {
cout<<"Name: ";
cin>>name;
cout<<"Age: ";
cin>>age;
cout<<"Gender: ";
cin>>gender;
16.}
17.void showPersonData()
18.{
cout<<"Name: "<<name<<endl;
cout<<"Age: "<<age<<endl;
cout<<"Gender: "<<gender<<endl;
22.}
23.};

24. class Student: public Person


25. {
26. char course[20]; int year; public:
27. void getStudentData()
28.
29.

18
4
ALPHORES W.D.C, KARIMNAGAR
30. {
31. Person::getPersonData();
32. cout<<"enter course: ";
33. cin>>course;
34. cout<<"enter which year studying: ";
35. cin>>year;
36. }
37. void showStudentData()
38. {
39. Person::showPersonData();
40. cout<<"course : "<<course<<endl;
41. cout<<"year: "<<year<<" year"<<endl;
42. }
43. };

44. class Employee: public Person


45. {
46. char org[100];
47. int salary;
48. public:
49. void getEmpData()
50. {
51. Person::getPersonData();
52. cout<<"Name of Organization: ";
53. cin>>org;
54. cout<<"Salary: Rs.";
55. cin>>salary;
56. }
57. void showEmpData()
58. {
59. Person::showPersonData();
60. cout<<"Name of Organization: "<<org<<endl;
61. cout<<"Salary: Rs."<<salary<<endl;
62. }
63. };

64. int main()


65. {
66. Student s;
67. Employee e;

18
5
ALPHORES W.D.C, KARIMNAGAR
68. cout<<"Student"<<endl; cout<<"Enter data"<<endl; s
69. cout<<endl<<"Displaying data"<<endl; s.showStudent
70. getch(); return 0;
71. }
72.
73.
74.
75.
76.
77.
78.
79.
80.

Output:

18
6
ALPHORES W.D.C, KARIMNAGAR
Explanation:In above example Studentand Employee are the two
sub classes which are derived from the super class Person
Multilevel Inheritance
In this type of inheritance the derived class inherits from a class,
which in turn inherits from some other class. The Super class for
one class, is sub class for the other.

Multilevel Inheritance
The below program demonstrates multilevel inheritance:
#include<iostream.h>
class Person
{
char name[20];
char gender[20];
public:
void getData()
{
cout<<"Name: ";
cin>>name;
cout<<"Gender: ";
cin>>gender;
}
void showData()
{
cout<<"Name: "<<name<<endl;
cout<<"Gender: "<<gender<<endl;
}
};

class Student: public Person

18
7
ALPHORES W.D.C, KARIMNAGAR
{
char course[20];
int year;
public:
void getStudentData()
{
Person::getData();
cout<<"Name of Course: ";
cin>>course; cout<<"Year:
"; cin>>year;
}
void showStudentData()
{
Person::showData();
cout<<"Name of Course: "<<course<<endl;
cout<<"Year"<<year<<endl;
}
};

class Skills: public Student


{
int number;
public:
void getSkillData()
{
Student::getStudentData();
cout<<"Number of programming languages known: ";
cin>>number;
}
void showSkillData()
{
Student::showStudentData();
cout<<"Number of programming languages known:
"<<number;
}
};

int main()
{Skills s;

18
8
ALPHORES W.D.C, KARIMNAGAR
cout<<"Enter data"<<endl;
s.getSkillData();
cout<<endl<<"Displaying data"<<endl;
s.showSkillData();
return 0;
}
Output:

Explanation:
In the above program Person is the Super class, Student is
derived from the Person, Again Skills class is derived from the
Student class. This program demonstrates the multilevel
inheritance.
Hybrid (Virtual) Inheritance
Hybrid Inheritance is combination of Hierarchical and Mutilevel
Inheritance.

18
9
ALPHORES W.D.C, KARIMNAGAR
Hybrid Inheritance
The below program demonstrates hybrid inheritance:
#include<iostream.h>
class Person
{
char name[20];
char gender[20];
public:
void getData()
{
cout<<"Name: ";
cin>>name;
cout<<"Gender: ";
cin>>gender;
}
void showData()
{
cout<<"Name: "<<name<<endl;
cout<<"Gender: "<<gender<<endl;
}
};

class Student: public Person


{
char course[20];
protected:
int marks;
public:
void getStudentData()
{
Person::getData();
cout<<"Name of Course: ";
cin>>course;
cout<<"marks: ";
cin>>marks;
}
void showStudentData()
{
Person::showData();

19
0
ALPHORES W.D.C, KARIMNAGAR
cout<<"Name of Course: "<<course<<endl;
cout<<"Marks: "<<marks<<endl;
}
};

class Skills
{
protected:
int number;
public:
void getSkillData()
{
cout<<"Number of programming language known: ";
cin>>number;
}
void showSkillData()
{
cout<<"Number of programming language known:
"<<number;
}
};

class Result : public Student, public Skills


{
public:
void getDataForResult()
{
Student::getStudentData();
Skills::getSkillData();
}
void showResult()
{
Student::showStudentData();
Skills::showSkillData();
if(marks>=50 || number>=3)
cout<<"\nstudent is selected for interview";
else
cout<<"\nstudent is not selected for interview";
}
};

19
1
ALPHORES W.D.C, KARIMNAGAR

int main()
{

Resultr;
cout<<"Enter data"<<endl;
r.getDataForResult();
cout<<endl<<"Displaying data"<<endl;
r.showResult();
return 0;
}

Output:

Explanation:
In the above program, Student is derived from super class Person.
Skills is another class. Result is a class derived from Skills and
Student class. Here Multilevel and Multiple inheritance is merged
so it is called Hybrid Inheritance.
Order of Constructor Call
Base class constructors are always called in the derived class
constructors. Whenever we create derived class object, first the
base class default constructor is executed and then the derived
class's constructor finishes execution.

19
2
ALPHORES W.D.C, KARIMNAGAR
 Whether derived class's default constructor is called or
parameterised constructor is called, base class's default
constructor is always called inside them.

 To call base class's parameterized constructor inside derived


class's parameterized constructor, we must mention it
explicitly while declaring derived class's parameterized
constructor.
Base class Default Constructor in Derived class Constructors
1. #include<iostream.h> #include<conio.h> class Base
2. {
3. int x; public:
4. Base() { cout << "\nBase default constructor"; }
5. };
6.
7.
8.

9.class Derived : public Base


10. {
int y;
public:
Derived() { cout << "\nDerived default constructor"; }
Derived(int i) { cout << "\nDerived parameterized constructor"
15. cout<<"\ni="<<i;
16. }
17. };

18. int main()


19. {
clrscr();
Base b;

19
3
ALPHORES W.D.C, KARIMNAGAR
Derived d1;
22. Derived d2(10);
23. return 0;
25. }

RUN

Explanation:In the above example, when both objects are created


in Derived class, Base class's default constructor is called.

Base class Parameterized Constructor in Derived class


Constructor
We can explicitly mention a call to the Base class's parameterized
constructor when Derived class's parameterized constructor is
called.
#include<iostream.h>
#include<conio.h>
class Base
{
public:
int x;
Base(int
i)
{ x = i;
cout << "\nBase Parameterized Constructor"<<endl;
}
};

class Derived : public Base


{
public:
int y;
Derived(int j) : Base(j)

19
4
ALPHORES W.D.C, KARIMNAGAR
{ y = j;
cout << "\nDerived Parameterized Constructor"<<endl;
}
};

int main()
{
clrscr();
Derived d(10)
;
cout << d.x <<endl;// Output will be
10 cout << d.y <<endl;// Output will
be 10 return 0;
}
Run

Why is Base class Constructor called inside Derived class ?


Constructors have a special job of initializing the object properly.
A Derived class constructor has access only to its own class
members, but a Derived class object also have inherited property
of Base class, and only base class constructor can properly
initialize base class members. Hence the Base class constructors
are called, else object wouldn't be constructed properly.
Constructor call in Multiple Inheritance
Its almost the same, all the Base class's constructors are called
inside derived class's constructor, in the same order in which they
are inherited.
class A : public B, public C ;
In this case, first class B constructor will be executed, then class
C constructor and then class A constructor.

19
5
ALPHORES W.D.C, KARIMNAGAR
Upcasting in C++
Upcasting is using the Super class's reference or pointer to refer
to a Sub class's object. Or we can say that, the act of converting a
Sub class's reference or pointer into its Super class's reference or
pointer is called Upcasting.

Example:
class Super
{ int x;
public:
void funBase() { cout << "Super function"; }
};

class Sub : public Super


{ int y;
};

int main()
{
Super* ptr;// Super class pointer
Sub obj;
ptr = &obj;

Super &ref;// Super class's reference


ref=obj;

19
6
ALPHORES W.D.C, KARIMNAGAR
}
The opposite of Upcasting is Downcasting, in which we convert
Super class's reference or pointer into derived class's reference or
pointer.
Functions that are never Inherited
 Constructors and Destructors are never inherited and hence
never overridden.
 Also, assignment operator = is never inherited. It can be
overloaded but can't be inherited by sub class.
Hybrid Inheritance and Virtual Class
In Multiple Inheritance, the derived class inherits from more than
one base class. Hence, in Multiple Inheritance there is a chance of
ambiguity.

class A
{ void show(); };

class B:public A {};

class C:public A {};

class D:public B, public C {};

int main()
{
D obj;
obj.show();
}
In this case both class B and C inherits function show() from class
A. Hence class D has two inherited copies of function show(). In
main() function when we call function show(), then ambiguity
arises, because compiler doesn't know which show() function to
call. Hence we use Virtual keyword while inheriting class.
class B : virtual public A {};
class C : virtual public A {};
class D : public B, public C {};

19
7
ALPHORES W.D.C, KARIMNAGAR
Now by adding virtual keyword, we tell compiler to call any one
out of the two show() funtions.
Hybrid Inheritance and Constructor call
Whenever a derived class object is instantiated, the base class
constructor is always called. But in case of Hybrid Inheritance, as
discussed in above example, if we create an instance of class D,
then following constructors will be called :
 Before class D's constructor, constructors of its super classes
will be called, hence constructors of class B, class C and class
A will be called.
 When constructors of class B and class C are called, they will
again make a call to their super class's constructor.
This will result in multiple calls to the constructor of class A,
which is undesirable. There is a single instance of virtual base
class which is shared by multiple classes that inherit from it;
hence the constructor of the base class is called only once by
the constructor of concrete class, it isclass D in our case.
If there is any call for initializing an object through the
constructor of class A via class B or class C, while creating object
of class D, all such calls will be skipped.
Polymorphism
Polymorphism means having multiple forms of one thing. In
inheritance, polymorphism is done, by method overriding, when
both super and sub class have member function with same
declaration but different definition.
Function Overriding
A function with same name and prototype is defined in both base
and derived classes, then that function is said to be overridden,
and this mechanism is called Function Overriding
Requirements for Overriding
 Inheritance should be there. Function overriding cannot be
done within a class. For this we require a derived class and a
base class.

19
8
ALPHORES W.D.C, KARIMNAGAR
 Function that is redefined must have exactly the same
declaration in both base and derived class, that means same
name, same return type and same parameter list.
Example of Function Overriding
class Base
{
public:
void show()
{
cout << "Base class";
}
};
class Derived:public Base
{
public:
void show()
{
cout << "Derived Class";
}
}
In this example, function show() is overridden in the derived
class.

Function Call Binding with class Objects(Early Binding)


Connecting the function call to the function body is
called Binding. When it is done before the program is run, its
called Early Binding or Static Binding or Compile-time Binding.
class Base
{
public:
void shaow()
{
cout << "Base class\t";
}
};
class Derived:public Base
{
public:
void
show()

19
9
ALPHORES W.D.C, KARIMNAGAR
{
cout << "Derived Class";
}
}

int main()
{
Base b;//Base class object
Derived d;//Derived class object
b.show();//Early Binding Ocuurs
d.show();
}
Output : Base classDerived class
In the above example, we are calling the overridden function using
Base class and Derived class object. Base class object will call
base version of the function and derived class's object will call the
derived version of the function.

Function Call Binding using Base class Pointer


When we use a Base class's pointer or reference to hold Derived
class's object, then Function call Binding gives some unexpected
results.
class Base
{
public:
void show()
{
cout << "Base class";
}
};
class Derived:public Base
{
public:
void show()
{
cout << "Derived Class";
}
}

int main()
{
Base* b;//Base class pointer

20
0
ALPHORES W.D.C, KARIMNAGAR
Derived d;//Derived class object
b = &d;
b->show();//Early Binding Occurs
}
Output : Base class
 In the above example, although, the object is of Derived class,
still Base class's method is called. This happens due to Early
Binding.
 Compiler on seeing Base class's pointer, set call to Base
class's show() function, without knowing the actual object
type.
Virtual Functions
 Virtual Function is a function in base class, which is
overridden in the derived class, and which tells the compiler to
perform Late Binding on this function.
 Virtual Keyword is used to make a member function of the
base class Virtual.
Late Binding
In Late Binding function call is resolved at runtime. Hence, now
compiler determines the type of object at runtime, and then binds
the function call. Late Binding is also called Dynamic Binding
or Runtime Binding.
Problem without Virtual Keyword
class Base
{
public:
void show()
{
cout << "Base class";
}
};
class Derived:public Base
{
public:
void show()
{
cout << "Derived Class";
}
}

20
1
ALPHORES W.D.C, KARIMNAGAR

int main()
{
Base* b;//Base class pointer
Derived d;//Derived class object
b = &d;
b->show();//Early Binding Ocuurs
}
Output : Base class
When we use Base class's pointer to hold Derived class's object,
base class pointer or reference will always call the base version of
the function
Using Virtual Keyword
We can make base class's methods virtual by using virtual
keyword while declaring them. Virtual keyword will lead to Late
Binding of that method.
class Base
{
public:
virtual void show()
{
cout << "Base class";
}
};

class Derived:public Base


{
public:
void show()
{
cout << "Derived Class";
}
}

int main()
{
Base* b;//Base class pointer
Derived d;//Derived class object
b = &d;
b->show();//Late Binding Ocuurs
}

20
2
ALPHORES W.D.C, KARIMNAGAR
Output : Derived class
On using Virtual keyword with Base class's function, Late Binding
takes place and the derived version of function will be called,
because base class pointer pointes to Derived class object.
Using Virtual Keyword and Accessing Private Method of
Derived class
We can call private function of derived class from the base class
pointer with the help of virtual keyword. Compiler checks for
access specifier only at compile time. So at run time when late
binding occurs it does not check whether we are calling the
private function or public function.

#include <iostream.h>
class A
{
public:
virtual void show()
{
cout << "Base class\n";
}
};

class B: public A
{
private:
virtual void show()
{
cout << "Derived class\n";
}
};

int main()
{
A *a
;
B b;
a = &b;
a -> show();
}
Output : Derived class

20
3
ALPHORES W.D.C, KARIMNAGAR
To accomplish late binding, Compiler creates VTABLEs, for each
class with virtual function. The address of virtual functions is
inserted into these tables. Whenever an object of such class is
created the compiler secretly inserts a pointer called vpointer,
pointing to VTABLE for that object. Hence when function is called,
compiler is able to resolve the call by binding the correct function
using the vpointer.
 Only the Base class Method's declaration needs
the Virtual Keyword, not the definition.
 If a function is declared as virtual in the base class, it will be
virtual in all its derived classes.
 The address of the virtual Function is placed in
the VTABLE and the compiler uses VPTR(vpointer) to point
to the Virtual Function.
Abstract Class
Abstract Class is a class which contains at least one Pure Virtual
function in it. Abstract classes are used to provide an Interface for
its sub classes. Classes inheriting an Abstract Class must provide
definition to the pure virtual function; otherwise they will also
become abstract class.
Characteristics of Abstract Class

 Abstract class cannot be instantiated, but pointers and


references of Abstract class type can be created.
 Abstract class can have normal functions and variables along
with a pure virtual function.
 Abstract classes are mainly used for Upcasting, so that its
derived classes can use its interface.
 Classes inheriting an Abstract Class must implement all
pure virtual functions, or else they will become Abstract too.

Pure Virtual Functions


Pure virtual Functions are virtual functions with no definition.
They start with virtual keyword and ends with= 0. Here is the
syntax for a pure virtual function,
virtual void f() = 0;

20
4
ALPHORES W.D.C, KARIMNAGAR
Example of Abstract Class
class Base//Abstract base class
{
public:
virtual void show() = 0;//Pure Virtual Function
};

class Derived:public Base


{
public:
void show()
{ cout << "Implementation of Virtual Function in
Derived class"; }
};

int main()
{
Base obj;//Compile Time Error
Base *b;
Derived d;
b = &d;
b->show();
}
Output :
Implementation of Virtual Function in Derived class
In the above example Base class is abstract, with pure
virtual show() function, hence we cannot create object of base
class.
Why can't we create Object of Abstract Class ?
When we create a pure virtual function in Abstract class, we
reserve a slot for a function in the VTABLE(studied in last topic),
but doesn't put any address in that slot. Hence the VTABLE will
be incomplete.
As the VTABLE for Abstract class is incomplete, hence the
compiler will not let the creation of object for such class and will
display an error message whenever we try to do so.

20
5
ALPHORES W.D.C, KARIMNAGAR
Pure Virtual definitions
Pure Virtual functions can be given a small definition in the
Abstract class, which we want all the derived classes to have. Still
we cannot create object of Abstract class.
Also, the Pure Virtual function must be defined outside the class
definition. If we will define it inside the class definition,
complier will give an error. Inline pure virtual definition is Illegal.
Example :
class Base//Abstract base class
{
public:
virtual void show() = 0;//Pure Virtual Function
};
void Base :: show()//Pure Virtual definition
{
cout << "Pure Virtual definition\n";
}
class Derived:public Base
{
public:
void show()
{ cout << "Implementation of Virtual Function in
Derived class"; }
};

int main()
{
Base *b;
Derived d;
b = &d;
b->show();
}
Output :
Pure Virtual definition
Implementation of Virtual Function in Derived class
Virtual Destructors

 Destructors in the Base class can be Virtual. Whenever


Upcasting is done, Destructors of the Base class must be
made virtual for proper destruction of the object when the
program exits.

20
6
ALPHORES W.D.C, KARIMNAGAR
 Constructors are never Virtual, only Destructors can be
Virtual.
Upcasting without Virtual Destructor
When we do not have a virtual Base class destructor the derived
class object exists with out deletion.

Example:
class Base
{
public:
~Base() {cout << "Base Destructor\t"; }
};
class Derived:public Base
{
public:
~Derived() { cout<< "Derived Destructor"; }
};
int main()
{
Base* b = new Derived;//Upcasting
delete b;
}
Output :
Base Destructor
In the above example, delete b will only call the Base class
destructor, which is undesirable because, then the object of
Derived class remains un-destructed, because its destructor is
never called. Which results in memory leak
Up casting with Virtual Destructor
When we have Virtual destructor in the base class we can avoid
the problem.
class Base
{
public:
virtual ~Base() {cout << "Base Destructor\t"; }
};

class Derived:public Base


{

20
7
ALPHORES W.D.C, KARIMNAGAR
public:
~Derived() { cout<< "Derived Destructor"; }
};

int main()
{
Base* b = new Derived;//Upcasting
delete b;
}
Output :
Derived Destructor
Base Destructor
When we have Virtual destructor inside the base class, then first
Derived class's destructor is called and then Base class's
destructor is called, which is the desired behavior.
Pure Virtual Destructors
 Pure Virtual Destructors are legal in C++. Also, pure virtual
Destructors must be defined, which is against the pure virtual
behavior.
 The only difference between Virtual and Pure Virtual
Destructor is, that pure virtual destructor will make its Base
class Abstract, hence we cannot create object of that class.
 There is no requirement of implementing pure virtual
destructors in the derived classes.
class Base
{
public:
virtual ~Base() = 0;//Pure Virtual Destructor
};
Base::~Base() { cout << "Base Destructor"; } //Definition of Pure
Virtual Destructor
class Derived:public Base
{
public:
~Derived() { cout<< "Derived Destructor"; }
};

20
8
ALPHORES W.D.C, KARIMNAGAR
Getting input and formatting Output

The purpose of writing a program is to accomplish a task. For a


program the user or programmer need to provide some input
values and the program in return provides the output values. For
providing input values to a program every programming language
provides some input statements as well as for providing output to
the users, some output statements are provided.
In C++, the input/output statements are based on OOP concept.
The basic input and output statements are described below:
Getting input from keyboard with cin object:
cin is an object of basic istream class. The class declaration is
done in iostream.h hearder file. The object uses the concept of
abstraction in OOP. It means that the object handles the process
of getting input stream (flow) of characters. Here the user is
exempted from knowing the internal details of how the input is
captured from input device to memory.
cin object gets the input values given by the user and keeps those
values in the memory locations specified in the input statement.
Here an operator called extraction operator (>>) is used in the
input operation.

abstraction of input operation through cin object


The following piece of code demonstrates how cin is used in a
program.

Explanation: In line 1: The two variables marks1 and marks2 are


declared. These are names of memory locations that can store two
integers with the names marks1 and marks2.

20
9
ALPHORES W.D.C, KARIMNAGAR
In line 2: The object cin is used for extracting input from the
keyboard. Here the compiler expects 2 values from the standard
input device keyboard, when the user enters 2 values, the values
are in sequence are received by cin object. Later the extraction
operator moves the values to the memory locations with the
specified names.

Sending output to screen with cout object:


cout is an object of basic ostream class. The class declaration is
done in iostream.h hearder file. The object uses the concept of
abstraction in OOP. It means that the object handles the process
of sending output stream (flow) of characters. Here the user is
exempted from knowing the internal details of how the output is
sent to screen from memory.
From memory location the output values are inserted into the
cout object through the operator called insertion operator (<<).
The cout object sends the output values to the screen.

Abstraction of output operation through cout object


The following piece of code demonstrates how cout is used in a
program.
cout<<"marks1="<<marks1<<"marks2="<<marks2;

In the above statement, marks1 and marks2 are two locations in


the memory. The string constant “marks1=” is sent first into the
cout object. The cout object then sends the string constant to the
screen. Latermarks1 value is sent. In the similar way the
“marks2=” is sent first and later mark2 value is sent.
More about cin object:
Every object has its own member functions. Those functions
perform various operations. Similarly, cin is an object of istream
class. It has its own member functions associated with it. Some of
the functions that are used frequently are discussed below:

21
0
ALPHORES W.D.C, KARIMNAGAR

Frequently used member function with cin object.


get() : This function is used to get single character as input. It
accepts all the characters along with space, new line, tab
characters as input. When cin is used with extraction operator the
input statement can’t accept the space, new line, and tab
character.
Syntax
cin.get(variable);

Example
cin.get(ch);
getline(): This function is used to get input from the user until
the user press the return key. When cin is used with extraction
operator it stops reading data when a space is found. But in this
case, the getline function accepts spaces and tab characters in the
input. And the input process is terminated only when return key
(enter key) is pressed.
Syntax
cin.getline(variable, size);

Example
cin.getline(x,30);

21
1
ALPHORES W.D.C, KARIMNAGAR
read():This function is an extension to getline() function. In this
case the input may contain even new line character. The input
process is terminated when the number of characters in the input
reaches the size mentioned in the read function.
Syntax
cin.read(variable, size);

Example
cin.read(x,30);
peek() :
When the programmer is intended to avoid some character in the
input the peek() function is useful. It checks the character in the
input stream and returns that character.
Example :cin.peek() = = ‘.’;
Here cin is an object and ‘.’ is a symbol to be caught in the
stream.
ignore():
This function is used with peek function. It ignores the character
which is returned by peek function so that character is avoided
from the reading process.
Example:cin.ignore(1,’.’);
The statement ignores 1 character ‘.’ in the stream
putback():
This function replaces one character in the input stream with the
other character specified in the function.
Example
while(cin.get(c))
{
if(c==’$’)
cin.putback(‘#’);
cout.put(c);
}

21
2
ALPHORES W.D.C, KARIMNAGAR
gcount():
This function returns the number of characters accepted through
the functions like getline() or read(). When gcount() is used, the
previous statement must be input statement like getline() or
read().
Example:
cin.getline(input,40);
int count=cin.gcount();
More about cout object:
Like cin object, cout object also has some member functions for
output operations. Few of them are described below:

Figure 4 : functions associated with cout object

put() : The put function is used to send one character from


memory to output device.
Syntax
cout.put(variable);

Example
cout.put(ch);

write():this function is used to send a sequence of characters with


the specified size to output device.
Syntax
cout.write(variable, size);

Example
cout.write(x,30);

21
3
ALPHORES W.D.C, KARIMNAGAR
Formatting output with member functions of cout object
cout object has the following member functions to format the
output of the programs.

Functions for formatting output using cout


width() : This function sets the width for a field to be displayed. In
the specified width the output will be displayed. If the width is set
more than thesize of the field then the additionally allocated width
is left blank.
Syntax :
cout.width(int);

Example :
cout.width(8);

precision(): The term precision refers number of digits to be


present after decimal point while displaying a floating point
number. The function precision() sets the number of digits to be
displayed when printing a floating point number.
Syntax :
cout.precision(int);

Example :
cout.precision(3);

fill():When width()function sets the space for printing output, in


this case some blank space may be created if the width is more

21
4
ALPHORES W.D.C, KARIMNAGAR
than the field size. In such case to fill the space with specified
character the function fill() is used.
syntax:
cout.fill(char);

Example:
cout.fill('*');

setf() : The term setf refers setting the flag. The flag setting is done
for formatting the output. Setting the flags with setf function is
done in two ways:
I) Flag setting with bit fields

cout.setf(f1,f2);
Here f1 refers flag and f2 refers bit field.

Purpose Flag Bit field


ios::left ios::adjustfield
Alignment
ios::right ios::adjustfield
Floating point ios::fixed ios::floatfield
representation ios::scientific ios::floatfield
ios::dec ios::basefield
Integer constant
ios::oct ios::basefield
Representation
io::hex ios::basefield
Flag setting options using setf function with bit fields

II) Flag setting without bit fields


cout.setf(f1);
Here f1 refers the flag. And No bit field is needed.

Purpose Flag

To get + sign explicitly before a positive number ios::showpos


To show the decimal point along with trailing
ios::showpoint
zeros
To show the capital letters (E and 0X) in
ios::uppercase
scientific and Hexa decimal notations

21
5
ALPHORES W.D.C, KARIMNAGAR
Flag setting options using setf function without bit fields

unsetf() :This function makes the flags inactivewhich were made


active with setf function.
Manipulators
The manipulators are similar to ios member functions.
Manipulators are used to format output using cout statement.
The manipulators are defined in iomanip.h header file.
Manipulators work for that statement only. Previous settings of
manipulators can’t be returned.
Some of the predefined manipulators are listed below:

Purpose Manipulator
setting the width for a field setw(int)
setting the number of digits after decimal point
setprecision(int)
for a floating point number
To start the new line by ending the existing one endl
to display the different integer constants hex, oct dec
Predefined manipulators
Program to print simple messages on the screen.

1/* My first C++ program


2It demonstrates the Output statement cout*/
3#include<iostream.h>
4int main()
5{
6cout<<"My Name is Akshara"<<endl;
7cout<<"I am pursuing Under Graduation
course"<<endl; 8cout<<"This is my first C++
program"<<endl;
9return 0;
10}

OUTPUT:
My Name is Akshara

21
6
ALPHORES W.D.C, KARIMNAGAR
This is my first C++ program

Explanation: In the above program, line 1 and 2 are comment


lines. In line 3, header file iostream.h is included in which the
definition for cout is mentioned. In line 4, header for main
function is given. The compiler begins execution from main(). Line
5 denotes beginning of the program. Lines 6 to 8 are output
statements, these statements print whatever is mentioned in
double quote marks on the screen. In line 9, return statement
returns 0 to operating system. This denotes that the program has
been executed successfully without any interruption. In Line 10,
the end of the program.

21
7
ALPHORES W.D.C, KARIMNAGAR
UNIT-4
Exception Handling

Introduction
Sometimes a programmer may find unexpected behavior of
program while it is being executed. Such abnormal or unexpected
behavior is because of two reasons:
 Errors
 Exceptions
Types of Errors
The errors can be divided into 3 types
 Syntax / Grammatical errors
 Logical / Semantic errors
 Runtime errors.
Syntax / Grammatical errors:
If a programmer doesn’t follow the rules in writing the
instructions in a program, the compiler generates an error or list
of errors and terminates the compilation process. The
grammatical errors that are occurred in a program are called the
syntax errors. These errors must be corrected for the successful
compilation of the program. The compiler detects only the syntax
errors.
Examples:
 Missing semi colon at the end of the statement
 intx//missing semicolon
 Parenthesis/braces mismatch
 (-b+(b*b)-(4*a*c) / (2*a);//parenthesis mismatch
 Spaces in variable names
tot_marks is a valid identifier, but tot marks is invalid
 Typing mistakes in keywords / variable
names. void is a valid keyword but Void, viod are
invalid.

21
8
ALPHORES W.D.C, KARIMNAGAR
Logical / Semantic errors:
Before writing a program, any programmer goes through an
algorithm. The algorithm is sketch or outline of a solution to a
problem. The programmer’s duty is to parse the algorithm into a
set of instructions i.e. a program. In this process if the
programmers’ interpretation is not correct, then some errors will
occur. Due to this reason, the solution may become incorrect. The
errors that are caused due to lack of understanding of the
programmer are called logical errors. The meaning of the
instructions may be changed because of such errors. Due to this
reason such errors are denoted as semantic errors. The compiler
doesn’t recognize the logical errors.
Example:
Every floating point constant in C++ is considered as double. If
the programmer is unaware of this he or she may find incorrect
output.

#include<iostream.h>
void main()
{
float a;
a=0.7;
if (a==0.7)
cout<<"a is 0.7";
else
cout<<"a is not 0.7";
}
Output
a is not 0.7
#include<iostream.h>
void main()
{
double a;
a=0.7;
if (a==0.7)
cout<<"a is 0.7";
else

21
9
ALPHORES W.D.C, KARIMNAGAR
cout<<"a is not 0.7";
}
Output
a is 0.7
Runtime errors:
Errors that are found during the execution of the program are
called runtime errors. Due to runtime errors a program may be
terminated abnormally or it may generate unexpected results.
These errors are not identified by compiler. Only when executing
the program, a programmer comes to know runtime errors. Often
it is difficult to identify are correct the runtime errors.
Examples:
int a,b,c,d;
d=a/(b-c);

if the expression (b-c) results 0, then the result of division is


undefined. This kind of errors are runtime errors. The Division
operation is based on the values of b, c.
int a[5];
for(i=0; i<6;i++)
cout<<a[i];
In the above code, at the end of the for loop i value becomes 5, but
a[5] is out of array boundary.
double *d;
d= new double[1000];
The above statement allocates memory for 1000 double variables.
It means it requires 8*1000 =8000 bytes contiguously. If that
much memory is not available in a small computer, this leads to
insufficient memory error.
The above are the 3 cases, programmers find runtime errors.
There are many such cases that leads to runtime errors.

22
0
ALPHORES W.D.C, KARIMNAGAR
Exceptions:
The errors that occur during the program execution are runtime
errors. The runtime errors are called exceptions. Due to the
exceptions in a program, the program may terminate abnormally
or it may provide incorrect results.
The exceptions are of two types.
Synchronous exceptions are the errors such as division by zero,
array index out of boundary, and insufficient memory. These
exceptions occur when a programmer is unaware of runtime
situation of his/her program logic.
Asynchronous exceptions occurbecause of hardware malfunction
such as disk failure or interrupt from the keyboard etc.
Exception Handling
Exception Handling is a newly added feature in C++. This feature
handles only synchronous exceptions. For every exception, there
will be certain code for handling it. Exception Handling is a
mechanism of detecting and reporting an abnormal condition in
order to take an appropriate action to manage the exceptions.
Steps in Handling Exception (try..catch)
The following are the tasks in handling exceptions
 Find the problem (Hit the exception)
 Inform that an error has occurred (Throw the exception)
 Receive the error (Catch the exception)
 Take corrective action (Handle the exception)
Finding the problem refers to identify the part of the program
where the error may occur. That part of the progrm has to be
enclosed in try block and the catch block contains the codes that
represent the action to be taken when the error occurs.
Try catch block
In C++ exception handling is done with the help of try..catch block
. The programmers can use the try.. catch block to handle the
exceptions that suit their programs. This avoids abnormal
termination of the program.

22
1
ALPHORES W.D.C, KARIMNAGAR
Syntax
…..….. …..…..…..….. …..…..

…..….. …..…..…..….. …..…..

try
{
//Statements that may generate the exception
throw exception;
…..….. …..…..…..….. …..…..

}
catch(type arg)
{
//Statements to process the exception
}
Try Block: Inside the try block we can include the statements
that may cause an exception and throw an exception. throw
keyword is used to throw the exception. It invokes the exception
handling code.
Throw:In try block, when an exception is encountered, thethrow
keyword throws an exception object.
Catch Bock: The catch block contains the code that handles the
exceptions. It may correct the exceptions to ensure normal
execution of the program. Catching the thrown exception object
from the try block is done by corresponding catch block. Hence
the catch block should immediately follow the try block.
We can have multiple catch blocks for a single try block.
EXAMPLE:
#include <iostream>

using namespace std;


double division(int a, int b);
int main()
{

22
2
ALPHORES W.D.C, KARIMNAGAR
int num1, num2;
double res = 0;
cout<<"enter num1:
"; cin>>num1;
cout<<"enter num2:
"; cin>>num2;

try {
res = division(num1, num2);
cout << "res="<<res << endl;
} catch (const char* msg) {
cerr << msg << endl;
}

return 0;
}

double division(int n1, int n2) {


if( n2 == 0 ) {
throw "Arithmetic Exception!";
}
return (n1/n2);
}

Output
Run 1
enter num1: 21
enter num2: 3
res=7

Run 2
enter num1: 21
enter num2: 0
Arithmetic Exception!

Explanation: in the above program num1 and num2 are two


operands used in division operation. These values are sent to
division function. In the division function when the value of n2 is

22
3
ALPHORES W.D.C, KARIMNAGAR
zero, an exception is raised and thrown. The catch block
terminated the program normally by giving the message
Arithmetic Exception. In other case it prints the result of
division operation between num1 and num2.
Multiple catch statements:
Several types of exceptions may arise when executing the
program. Those exceptions can be handled by using multiple
catch blocks for the same try block. In such cases when an
exception occurs, the run time system will try to find match for
the exception object from the parameters of the catch blocks in
the order of appearance. When a match is found, corresponding
catch block will be executed to handle the exception. catch blocks
are written one after the other in sequence. No program
statements will appear between any two catch blocks.
General form
…..….. …..…..…..….. …..…..

…..….. …..…..…..….. …..…..

try
{
//Statements that may generate the exception
throw exception;
…..….. …..…..…..….. …..…..

}
catch(type arg)
{
//Statements to process the exception
}
catch(type arg)
{
//Statements to process the exception
}

22
4
ALPHORES W.D.C, KARIMNAGAR
…..….. …..…..…..….. …..…..

Example:
#include<iostream>
using namespace
std;

int difference(int x, int y) {


try {
if (x > y)
cout<<"difference between "<<x<<"and "<< y <<"
is "<<(x-y);
else
if(y>x)
throw "result is negative";
else
throw (x-y);
} catch (const char* msg) {
cerr << msg;
} catch (int x) {
cerr << "No difference is found :";
}
}
int main() {
int n1, n2;
cout<<"enter n1: ";
cin>>n1;
cout<<"enter n2: ";
cin>>n2;
cout << "Testing multiple catches\n:";
difference(n1,n2);

return 0;

}
Run 1

enter n1: 25

22
5
ALPHORES W.D.C, KARIMNAGAR
enter n2: 12
Testing multiple catches
:difference between 25and 12 is 13

Run 2
enter n1: 6
enter n2: 12
Testing multiple catches
:result is negative
Run 3
enter n1: 6
enter n2: 6
Testing multiple catches
: No difference is found :

Explanation: In the above program, two numbers are compared, if


the difference between first number and second number is
positive then the difference is displayed. otherwise it displays
result is negative. If there is no difference it displays the message
“No. difference is found”. In this we used two catch statements.
User Defined Exceptions:
A programmer can define exceptions in their programs and
avoidunexpected behaviorof a program during runtime. To define
user defined exception always include exception header using
preprocessor directive. And define a function that returns
exception string.return type of the function is char *
Example :
1. char* what()
2. {
3. // codes here
4. }
char is as return type because we will return a string.
The below program demonstrates user defined exception.

#include <iostream>
#include <exception>
using namespace std;

22
6
ALPHORES W.D.C, KARIMNAGAR
class MyException : public exception{
public:
const char * what() const throw()
{
return "invalid marks!\n";
}
};
int main()
{
try
{
int marks;
cout << "Enter marks : \n";
cin >> marks;
if (marks<0 || marks>100)
{
MyException z;
throw z;
}
else
{
if(marks>80)
cout<<" Excellent"<<endl;
else if(marks>60)
cout<<"Good"<<endl;
else if (marks>40)
cout<<"keep it up"<<endl;
else
cout<<"work hard"<<endl;

}
}
catch(exception& e)
{
cout << e.what();
}
}

22
7
ALPHORES W.D.C, KARIMNAGAR
Run 1
Enter marks :

111

invalid marks

Run 2
Enter marks :
89
Excellent

Explanation:
In the above program marks are given as input. And marks are
treated as invalid marks if marks are less than 0 and more than
100. For other range of marks respective grade is printed. In this
program MyException class is derived from Exception class. a
function named what() is defined to return error message. The
return type of what() is const char *.
Exceptions in Constructors and Destructors:
Exceptions may be possible in any part of the program.Often it is
difficult to identify and fix those exceptions in some programs.
Likewise, exceptions may be possible in Constructors while
initializing the objects. And exception handling in main() function
other than destructor while destroying object may lead to
abnormal termination of program.
The below program demonstrates exception handling in object
creation.
#include <iostream>
using namespace std;
class Number
{
double num;
public:
Number()
{

22
8
ALPHORES W.D.C, KARIMNAGAR
num=0;
}
Number(double n)
{
if(n<0)
throw "negative number";
else
num=n;
}
double sqr()
{
return(num*num);
}
double getValue()
{
return num;
}
};

int main()
{
double d;
cout<<"enter a number";
cin>>d;
try
{
Number x(d);
double y=x.sqr();
cout<<"sqr of "<<x.getValue()<<" is : "<<y;
}
catch(const char* msg)
{
cerr<<msg;
}
return 0;
}

Run 1
enter a number 6.9
sqr of 6.9 is : 47.61

22
9
ALPHORES W.D.C, KARIMNAGAR

Run 2
enter a number -7
negative number

Explanation: In the above program, we wish to find square of only


positive numbers. When a negative number is given the object will
not be formed in the constructor. And it will throw an exception
by passing a message ‘negative number’. Thrown exception is
caught in catch block and the error message is printed.
Re throwing Exceptions:
throw keyword is used to throw the exceptions explicitly to the
try block without processing from the catch block. It means in
some cases, exception handler may decide to rethrow the
exception to try block without processing. The below program
demonstrates on such situation.
#include <iostream>

using namespace std;


double division(int a, int b);
int main()
{
int num1, num2;
double res = 0;
cout<<"enter num1:
"; cin>>num1;
cout<<"enter num2:
"; cin>>num2;

try {
res = division(num1, num2);
cout << "res="<<res << endl;
}
catch (const char* msg)
{
cout<<" In MAIN FUNCTION"<<endl;
cerr << msg << endl;
}

23
0
ALPHORES W.D.C, KARIMNAGAR

return 0;
}

double division(int n1, int n2) {


try
{
if( n2 == 0 )
throw "Arithmetic Exception!";
else
return (n1/n2);
}
catch(const char* msg)
{
cout<<"In TRY CATCH BLOCK OF CALLED FUNCTION"<<endl;
cout<<"re throwing exception"<<endl;
throw;
}
}

Run 1
enter num1: 25
enter num2: 5
res=5

Run 2
enter num1: 5
enter num2: 0

In TRY CATCH BLOCK OF CALLED FUNCTION


re throwing exception
In MAIN FUNCTION
Arithmetic Exception!

Explanation:
In the above program when exception is raised in division
function, it is re thrown from the catch block of that function to
main function. In the main function it is handled.

23
1
ALPHORES W.D.C, KARIMNAGAR
Standard Exceptions:
C++ provides standard exception handlers. In exception header
file, std::exception class is defined. The types of exceptions and
situation where they are raised are listed below:

logic_error :
The logical errors occur in the program due to poor
understanding of the programmer. This leads to unexpected
behavior of program.
 invalid_argument
When using standard library functions, if the user provides
incorrect argument this exception is raised.
 domain_error
when invalid arguments are passed to functions this exception is
raised.
 length_error
When the length of an object exceeds, maximum allowable length,
this exception is raised.
 out_of_range
It occurs when an array index is out of boundary
runtime_error
The runtime errors occur during program execution.
 range_error
It is the error in STL (Standard Template Library)
 overflow_error
It occurs due to the overflow in STL container.
 underflow_error
It occurs due to underflow in STL container.

Advantages of Exception Handling.

 Proper handling of exceptions avoids abnormal


termination of programs and increases the reliability.
 Error handling code is separated from program code. It
improves the understandability.

23
2
ALPHORES W.D.C, KARIMNAGAR
 The code after catch statement can be executed. If the
exception is not handled properly, the program is
terminated abnormally and remaining code will not be
executed.

Templates

Introduction:
Template is common term in day to day life. It is a pattern used
for painting, cutting out or shaping. One pattern can be used to
many things. Similarly, in programming, sometimes a bit of code
and logic may be exactly same and only the type of data given as
input may be different. In such cases, with traditional
programming approach, programmers used to write the code
repeated to deal with different types of data. Only because of
change in type of data, it was needed to write set of statements
repeatedly.
To avoid such repeated code in programs a new feature is
introduced in C++.Such feature is templates. Broadly a template
allows us to deal with different data items with same set of
instructions.
C++ supports
 Function templates
 Class templates
Function templates.
In C++, a function is block of statements, particularly written for
accomplish a task. A function takes set of parameters and returns
a value. Always when a programmer makes a call to the function,
he/she must pass the same type of values which were declared in
the prototype of the function. Otherwise a compiler flags an error
indicating mismatch in the type declared and type of the values
sent. Hence the programmer needs to write separate code for
different data types. But when Function templates are used, the
overhead of writing code for different data types is avoided. It
means one set of instructions work for all types of data.
For example, while writing programs for swapping values, finding
23
3
ALPHORES W.D.C, KARIMNAGAR
largest and smallest in set of values, writing separate code for int,
float, double types is not needed. Only one function template can
work for all types of data. Same function code is used for identical
operations.

General form of writing function template:


template<class T>
T functionName(T arguments)
{
... .. ...
}
template keyword is used to write function templates. The
declaration begins with template keyword. class is a keyword
used to declare generic type T. In the above code, T is a generic
type that accepts different data typesint, float etc. we can also use
typename in place of class.

When, an argument of a data type is passed to functionName( ),


compiler generates a new copy of functionName() for the given
data type.
The below program finds biggest in two values and demonstrates
function template.
#include <iostream>
using namespace
std;
// template function
template <class T>
T biggest(T x, T y)
{
if(x>y)
return x;
else
return y;
}
int main()
{
int n1,n2;
float f1, f2;
char ch1, ch2; 23
4
ALPHORES W.D.C, KARIMNAGAR
cout << "Enter two integers:\n";
cin >> n1 >> n2;
cout << biggest(n1, n2) <<" is big." << endl;
cout << "\nEnter two floating-point numbers:\n";
cin >> f1 >> f2;
cout << biggest(f1, f2) <<" is larger." << endl;
cout << "\nEnter two characters:\n";
cin >> ch1 >> ch2;
cout << biggest(ch1, ch2) << " has larger ASCII
value.";
return 0;
}

Run
Enter two integers:
2378
78 is big.

Enter two floating-point numbers:


3.98.6
8.6 is larger.

Enter two characters:


wa
w has larger ASCII value.
Explanation:
In the above program, a function template biggest() is defined. It
accepts two arguments x and y of data type T. T indicates that
argument can be of any data type.
biggest() function returns the biggest among the two arguments
using a simple if else statement.
Inside the main() function, variables of three different data types:
int, float and char are declared. The variables are then passed to
the biggest() function template as normal functions.

23
5
ALPHORES W.D.C, KARIMNAGAR
During run-time, when an integer is passed to the template
function, compiler knows it has to generate a biggest() function to
accept the int arguments and does so.
Similarly, when floating-point data and char data are passed, it
knows the argument data types and generates the biggest()
function accordingly.
This way, using only a single function template replaced three
identical normal functions.
Example 2 : For identical operation, the function templates are
very much suitable. For example, swap (interchanging ) values of
two variables will have common logic. When we wish to apply
same logic for two or more types of data using template is
appropriate.
The below program demonstrates use of function template for
interchanging the values of two variables.
#include <iostream>
using namespace
std;

template <typename T>


void Swap(T &v1, T
&v2)
{
T t;
t = v1;
v1 = v2;
v2 = t;
}

int main()
{
int num1, num2;
double d1,d2;
char ch1, ch2;

cout<<"enter two integers";


cin>>num1>>num2;

23
6
ALPHORES W.D.C, KARIMNAGAR
cout<<"enter two double values";
cin>>d1>>d2;

cout<<"enter two character values";


cin>>ch1>>ch2;

cout << "Before passing data to function template.\n";


cout << "num1 = " << num1 << "num2 = " << num2<<endl;
cout << "d1 = " << d1 << "d2 = " << d2<<endl;
cout << "ch1 = " << ch1 << "ch2 = " << ch2<<endl;

Swap(num1, num2);
Swap(d1, d2);
Swap(ch1, ch2);

cout << "\nAfter passing data to function


template.\n";
cout << "num1 = " << num1 << "num2 = " << num2<<endl;
cout << "\nd1 = " << d1 << "d2 = " << d2<<endl;
cout << "\nch1 = " << ch1 << "ch2 = " << ch2<<endl;

return 0;
}
Output
enter two integers 6 9
enter two double values9.76.4
enter two character values u a
Before passing data to function template.
num1 = 6num2 = 9
d1 = 9.7d2 = 6.4
ch1 = u ch2 = a

After passing data to function template.


num1 = 9num2 = 6
d1 = 6.4d2 = 9.7

ch1 = ach2 = u

23
7
ALPHORES W.D.C, KARIMNAGAR
Overloading with function templates
Function templates can be overloaded with normal functions or
template functions. When we make a call to those functions,
compiler tries to find accurate match of the function. When no
accurate function is found then the compiler generates an
error.Here no implicit conversion is carried out in the parameters
of template functions.
A compiler follows the rules mentioned below while selecting
appropriate function when overloaded.

Compiler tries to find exact match of function parameters. If


found, then it invokes that function.
If no exact match is found for given parameter list, compiler
checks for the match in template function. If the parameters are
matching then the fuction will be invoked.
If no match is found, an error will be generated.
The below program demonstrates overloading a template function.
#include <iostream>
using namespace
std;

template <typename T>

void display(T x)
{
cout<<"x="<<x<<endl;
}

void display(double d)
{
cout<<"d="<<d<<endl;
}

int main()
{
intx=5;
display(x);
23
8
ALPHORES W.D.C, KARIMNAGAR
double y=9.8;
display(y);
char ch='a';
display(ch);
return 0;
}

Output:
x=5
d=9.8
x=a
Explanation :In the above program display() is overloaded. When
the function is called with integer and character as there is no
exact match, the template function is called. And when used for
double parameter the template function is not called. Because,
there is a function display with exact match of parameter for
double.
Class Templates
imilar tofunction templates, we can also create class templates for
generic class operations. In some cases, we need a class
implementation that is common for different data items. Creating
separate class for different data types for the same
implementation of a class or creating more number of member
variables for different types in the same class cause lot of
overhead in a program. Class template resolves all this kind of
issues. Here only one class and one set of generic data is enough
when implementation logic is same. It means, class templates
make it easy to reuse the same code for all data types.
General form for class implementation.
template<class T>
class className
{
... .. ...
public:
T var;
T someOperation(T arg);
... .. ...

23
9
ALPHORES W.D.C, KARIMNAGAR
};
In the above declaration, the template argument T is a placeholder
for the data types used. the member variable var, argument arg
and return type of someOperation all are of type T. The type T will
be replaced with some data type.
Creatinga class template object
To create a class template object, we need to define the data type
inside apair of <>symbols.

className<dataType> classObject;
For example:

className<int> classObject;
className<float> classObject;
the below program demonstrates class template
#include <iostream>
using namespace std;
template <class T>
class ArithmeticOperations
{
private:
T num1, num2;

public:
ArithmeticOperations(T n1, T n2)
{
num1 = n1;
num2 = n2;
}
void showResult()
{
cout << "Numbers are: " << num1 << " and " << num2 <<
"." << endl;
cout << "Addition is: " << add() << endl;
cout << "Subtraction is: " << subtract() <<
endl; cout << "Product is: " << multiply() <<
endl; cout << "Division is: " << divide() <<
endl;

24
0
ALPHORES W.D.C, KARIMNAGAR
}
T add() { return num1 + num2; }

T subtract() { return num1 -

num2; } T multiply() { return num1

* num2; } T divide() { return num1

/ num2; }
};
int main()
{
ArithmeticOperations<int> wholeNum(8,2);
ArithmeticOperations<float> floatPoint(8.4, 2.2);

cout << "whole numbers arithmetic results:" << endl;


wholeNum.showResult();

cout << endl << "Float point arithmetic results:" <<


endl;
floatPoint.showResult();
return 0;
output:
whole numbers arithmetic
results: Numbers are: 8 and 2.
Addition is: 10
Subtraction is: 6
Product is: 16
Division is: 4

Float point arithmetic results:


Numbers are: 8.4 and 2.2.
Addition is: 10.6
Subtraction is: 6.2
Product is: 18.48
Division is: 3.81818

24
1
ALPHORES W.D.C, KARIMNAGAR
Explanation:
In the above program, a class template ArithmeticOperations is
declared.

The class contains two private members of type T: num1&num2,


and a constructor to initalize the members.
It also contains public member functions to calculate the addition,
subtraction, multiplication and division of the numbers which
return the value of data type defined by the user. Likewise, a
function showResult() to display the final output to the screen.

In the main() function, two ArithmeticOperations


different
objects wholeNum and floatPoint are created for data types: int
and float respectively. The values are initialized using the
constructor.

Notice we use <int> and <float> while creating the objects. These
tell the compiler the data type used for the class creation.

This creates a class definition each for int and float, which are
then used accordingly.

Then, showResult() of both objects is called which performs the


ArithmeticOperations operations and displays the output.
Class Templates and Inheritance:
Inheritance feature can be applied to template classes. We can
derive a class from a template class. template classes can work
like base classes. It is useful to create hierarchical structures also
called as container class. the following ways for derivation is
possible with class templates.
 From a template base class we can derive a template
derived class.
 We can derive a template class from non template base
class and add new type member to the derived class.
 It is also possible to derive classes from the template base
class and avoid inheriting template features to derived
class. Here template based characteristics are omitted for

24
2
ALPHORES W.D.C, KARIMNAGAR
derived class and all the template based variables are
substituted with basic data types.
General form of deriving a template class from other class:
template <class T, . . .>
class Sample
{
//Template – type data members and member functions
};
template <class T, . . .>
class Example : public Sample<T>
{
//Template – type data members and member functions
};
The below program demonstrates class template with inheritance.
#include <iostream>

using namespace std;


template<class T>
class A
{
protected:
T n1;
public:
void get()
{
cout<<"enter n1:";
cin>>n1;
}
void show()
{
cout<<"n1="<<n1<<endl;
}
};
template<class T>
class B:public
A<T>
{

T n2;

24
3
ALPHORES W.D.C, KARIMNAGAR

void get1()
{ A<T>::get(
);
cout<<"enter n2:";
cin>>n2;
}
void show1()
{
A<T>::show();
cout<<" n2="<<n2<<endl;
}
};

int main()
{
B<int> intOb;
intOb.get1();
intOb.show1();

B<float> floatOb;
floatOb.get1();
floatOb.show1();

return 0;
}
Output
enter n1:3
enter n2:4
n1=3

n2=4
enter n1:3.5
enter n2:4.7
n1=3.5
n2=4.7

24
4

You might also like