CPP I-Ii BSC
CPP I-Ii BSC
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
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:
3
Keywords for repeated execution of statements on condition
for do while
inline
4
Keyword used in implementing genericity
template
virtual
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.
6
Examples:
7
Decimal Integers Octal Integers Hexadecimal Integers
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;
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.
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.
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;
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:
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
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.
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 ,
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.
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
Output
c=1.5
26
1.6 Control Structures
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.
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.
Run 2:
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:
{
Statements;
}
30
Explanation:
31
Run 2:
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
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.
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.
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:
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 :
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.
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.
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
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)
{
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.
51
Run:
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:
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:
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
56
=2*10+4=24
num=num/10
=34/10
3
Iteration
3:
58
Output
59
Output
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
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. }
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
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:
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: }
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:
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.
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.
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.
71
11 }
12 }
13 return 0;
14 }
Run
{ {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. }
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
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.
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
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)
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.
78
Step 5: otherwise search process continues till the end
of the list.
Step 6: element found or not message will be
displayed accordingly
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:
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 : ";
smallest = list[0];
for (i = 0; i < n; i+
+)
{
if (smallest > list[i])
smallest = list[i];
}
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.
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;
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
15. return 0;
16. }
RUN
Run
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;
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
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:
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
95
Functions
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 }
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
10
4
RUN
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
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:
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.
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
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:
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.
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.
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
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.
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.
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.
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.
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
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
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. };
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
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=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:
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
};
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. };
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.
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. };
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.
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
#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:
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;
}
#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;
return 0;
}
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;
}
void Rectangle::showData() {
cout<<"length="<<length<<endl;
cout<<"breadth="<<breadth<<endl;
}
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:
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:
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:
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
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
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. };
17
9
ALPHORES W.D.C, KARIMNAGAR
21. cout << "Enter marks1:";
22. cin>>marks1;
23. cout << "Enter marks2:";
24. cin>>marks2;
25. }
18
0
ALPHORES W.D.C, KARIMNAGAR
58. Output:
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.};
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. };
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;
}
};
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;
}
};
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;
}
};
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;
}
};
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.
19
3
ALPHORES W.D.C, KARIMNAGAR
Derived d1;
22. Derived d2(10);
23. return 0;
25. }
RUN
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
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"; }
};
int main()
{
Super* ptr;// Super class pointer
Sub obj;
ptr = &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(); };
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.
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.
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";
}
};
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
20
4
ALPHORES W.D.C, KARIMNAGAR
Example of Abstract Class
class Base//Abstract base class
{
public:
virtual void show() = 0;//Pure Virtual Function
};
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
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"; }
};
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
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.
21
0
ALPHORES W.D.C, KARIMNAGAR
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:
Example
cout.put(ch);
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.
Example :
cout.width(8);
Example :
cout.precision(3);
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
21
5
ALPHORES W.D.C, KARIMNAGAR
Flag setting options using setf function without bit fields
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.
OUTPUT:
My Name is Akshara
21
6
ALPHORES W.D.C, KARIMNAGAR
This is my first C++ 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);
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>
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;
}
Output
Run 1
enter num1: 21
enter num2: 3
res=7
Run 2
enter num1: 21
enter num2: 0
Arithmetic Exception!
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;
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 :
#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
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;
}
Run 1
enter num1: 25
enter num2: 5
res=5
Run 2
enter num1: 5
enter num2: 0
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.
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.
Run
Enter two integers:
2378
78 is big.
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;
int main()
{
int num1, num2;
double d1,d2;
char ch1, ch2;
23
6
ALPHORES W.D.C, KARIMNAGAR
cout<<"enter two double values";
cin>>d1>>d2;
Swap(num1, num2);
Swap(d1, d2);
Swap(ch1, ch2);
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
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.
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; }
/ num2; }
};
int main()
{
ArithmeticOperations<int> wholeNum(8,2);
ArithmeticOperations<float> floatPoint(8.4, 2.2);
24
1
ALPHORES W.D.C, KARIMNAGAR
Explanation:
In the above program, a class template ArithmeticOperations is
declared.
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.
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>
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