C++ Final Material
C++ Final Material
C++ Final Material
(EID201)
Course File
GITAM UNIVERSITY
HYDERABAD CAMPUS
PREPARED BY
D.SRINIVASA RAO
ASSISTANT PROFESSOR
DEPARTMENT OF IT
2
CONTENTS
S.No Topic Page no.
1 Syllabus 1-2
2 Module-1 3-54
3 Module-2 55-100
4 Module-3 101-130
5 Module-4 131-181
6 Module-5 182-217
7 Previous modelpaper-1 218-219
1
Module II
Control Structures.
Classes and Objects: Specifying a class, defining member functions,
C++ program with class, private member functions, arrays within
class, memory allocation for objects, static data members, static
member functions, arrays of objects, returning objects.
Functions in C++: main function, function prototyping, call by
reference, return by reference, inline functions, default arguments.
Module III
More about Functions: Function overloading, friendly functions: friend
function, a function friendly to two classes, objects as function
arguments.
Constructors & Destructors: Constructors, parameterized
constructors, multiple constructors in a class, constructors with
default arguments, copy constructors, dynamic constructors,
destructors.
2
Module IV
Module V
Polymorphism and Virtual Functions: Compile-time polymorphism,
runtime polymorphism, virtual functions.
Managing Console I/O Operations: Unformatted I/O operations,
formatted console i/o operations (width( ), precision( ), fill( )),
managing output with manipulators (setw( ), endl).
Templates: Introduction, function templates, class templates.
Exception Handling: Introduction, exception handling mechanism,
throwing mechanism, catching mechanism.
Text Book(s)
1. E. Balagurusamy, Object Oriented Programming with C++, 6/e,
McGraw Hill, 2013.
References
1. Sourav Sahay, Object Oriented Programming with C++, 2/e, Oxford
University Press, 2012.
2. Behrouz A. Forouzan and Richard F. Gilberg, Computer Science : A
Structured Approach Using C++, 2/e, Cengage Learning, 2003.
3. Ashok N. Kamthane, Object Oriented Programming with ANSI and
Turbo C++, 1/e, Pearson Education, 2006.
3
•
Procedure oriented programming basically consists of writing a
list of instructions for the computer to follow, and organizing
these instructions into groups known as functions.
• We normally use flowcharts to organize these actions and
represent the flow of control from one action to another.
• In a multi-function program, many important data items are
placed as global so that they may be accessed by all the
functions.
• Each function may have its own local data.
• Global data are more vulnerable to an inadvertent change by a
function.
• In a large program, it is very difficult to identify what data is
used by which function.
• In case we need to revise an external data structure, we also
need to revise all functions that access the data.
• This provides an opportunity for bugs to creep in.
• Another serious drawback with the procedural approach is that
we do not model real world problems very well.
• This is because functions are action-oriented and do not really
corresponding to the element of the problem.
Some Characteristics exhibited by procedure-oriented
programming are:
Emphasis is on doing things (algorithms).
• Large programs are divided into smaller programs known as
functions.
• Most of the functions share global data.
• Data move openly around the system from function to function.
• Employs top-down approach in program design.
5
Data may get passed from one Data never get passed
Passing of data function to another. from one object to
another.
No. C C++
10) C does not provide the feature of C++ supports the feature of
namespace. namespace.
8
1. Classes
2. Objects
3. Data abstraction
4. Data encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic Binding
8. Message Passing
Classes:
• The entire set of data and code of an object can be made a user-
defined data type with the help of a class. Objects are actually
variable of the type class.
• Once a class has been defined, we can create any number of
objects belonging to that class. Thus, a class is collection of
objects of similar type.
• Classes are user defined data types and behaves like the built-
in type of a programming language.
9
Objects:
#include <iostream>
using namespace std;
class Student
{
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
};
int main()
{
Student s1; //creating an object of Student
s1.id = 201;
s1.name = "surya maggi";
cout<<s1.id<<endl;
cout<<s1.name<<endl;
return 0;
}
OUTPUT:
201
surya maggi
10
Data Abstraction :
• Abstraction refers to the act of representing essential features
without including the background details or explanation.
• Classes use the concept of abstraction and are defined as a list of
abstract attributes such as size, wait, and cost, and function operate
on these attributes.
• They encapsulate all the essential properties of the object that are to
be created.
• The attributes are some time called data members because they hold
information. The functions that operate on these data are sometimes
called methods or member function.
Data encapsulation :
• The wrapping up of data and functions into a single unit called
class is known as encapsulation.
• The data is not accessible to the outside world, and only those
functions which are wrapped in the class can access it.
• These functions provide the interface between the objects data and
the program. This insulation of the data from direct access by the
program is called data hiding or information hiding
Inheritance :
• Inheritance is the process by which object of one class acquire the
properties of objects of another class.
• In OOPs, the concept of inheritance provides the idea of
reusability. This means that we can add additional features to an
existing class without modifying it.
• This is possible by deriving a new class from the existing one. The
new class wil1 have combined features of both the classes.
11
Polymorphism :
• Polymorphism is important oops concept. It means ability to take
more than one form.
• In polymorphism an operation may shows different behavior in
different instances. The behavior depends upon the type of data
used in the operation.
• For Ex- Operation of addition for two numbers, will generate a sum.
If the operands are strings, then the operation would produce a
third string by concatenation.
• The process of making an operator to show different behavior in
different instance is called as operator overloading.
• C++ support operator overloading.
EX:
Dynamic Binding :
• Binding refers to the linking of a procedure call to the code to be
executed in response to the call.
• Dynamic binding means that the code associated with a given
procedure call is not known until the time of the call at run
time.
• It is associated with polymorphism and inheritance.
• A function call associated with a polymorphic reference depends on
the dynamic type of that reference.
• Consider the procedure “draw” in fig. by inheritance, every object
will have this procedure. Its algorithm is, however, unique to each
object and so the draw procedure will be redefined in each class
that defines the object. At run-time, the code matching the object
under current reference will be called.
Message Passing :
• An object-oriented program consists of a set of objects that
communicate with each other.
• The process of programming in an object-oriented language, involves
the following basic steps:
✓ Creating classes that define object and their behaviour
✓ Creating objects from class definitions, and
✓ Establishing communication among objects.
• Objects communicate with one another by sending and receiving
information much the same way as people pass messages to one
another.
• The concept of message passing makes it easier to talk about building
systems that directly model or simulate their real-world
counterparts.
• A Message for an object is a request for execution of a procedure, and
therefore will invoke a function (procedure) in the receiving object
that generates the desired results.
13
1. Reusability:
2. Inheritance:
Through this we can eliminate redundant code and extend the use
of existing classes.
3. Data Hiding:
The programmer can hide the data and functions in a class from other
classes. It helps the programmer to build the secure programs.
6. Message Passing:
7. Modifiability:
Applications of OOP:
5. CAM/CAE/CAD System: -
Computer has wide use of OOP approach. This is due to time saving
in writing OOP codes and dynamic behaviour of OOP codes.
5. Structure of C++
• Documentation Section
✓ Link Section
✓ Definition Section
• Global Declaration Section
Documentation Section
/* Text Line 1
Text Line 2
Text Line 3 */
For Example: /* Write a C++ program to find the sum and average of
five numbers. */
Preprocessor Directives
It becomes very useful during the compilation and the linkage phase.
17
or
For example:
#include <iostream.h>
#include <conio.h>
#include "dos.h"
For example:
#define PI 3.142
#define A 100
6. Namespace scope
cout<<"Hello World";
cout<<"Hello World";
#include<iostream>
using namespace std;
Some old compilers may not support these statements.
#include<iostream.h>
• But we still can’t run these object files until to convert them into
executable file, now here linker comes into play, which links all
the object files to generate single executable file.
Example: CC file1.C
Linking
float r;
9 TOKENS
KEYWORDS:
Constants in C++:
• Constants refer to fixed values that the program may not alter.
• Constants can be of any of the basic data types.
• The way each constant is represented depends upon its type.
• Constants are also called literals.
• C++ has two kinds of constants: literal, and symbolic.
Definition: "A constant value is the one which does not change
during the execution of a program."
Numeric Constant
Escape Sequences
A list of backslash character constant or escape sequence is as in the
below table:
Symbolic constants
We can use the #define preprocessor directive in order to declare a
symbolic constant:
#define DOLLAR 122
int nYen = nDollars *
DOLLAR;
29
There are two major problems with symbolic constants declared using
#define.
o First, because they are resolved by the preprocessor, which
replaces the symbolic name with the defined value, #defined
symbolic constants do not show up in the debugger. Thus, if
you only saw the statement int nYen = nDollars * DOLLAR;, you
would have to go looking for the #define declaration in order to
find out what value of DOLLAR was used.
✓ A data type determines the type and the operations that can be
performed on the data.
✓ C++ provides various data types and each data type is
represented differently within the computer's memory.
✓ The various data types provided by C++ are built-in data types,
derived data types and user-defined data types as shown in
Figure.
Integral Data Type: The integral data type is used to store integers
and includes char (character) and int (integer) data types.
Char: Characters refer to the alphabet, numbers and other characters
(such as {, @, #, etc.) defined in the ASCII character set.
31
✓ In C++, the char data type is also treated as an integer data type
as the characters are internally stored as integers that range in
value from -128 to 127.
✓ The char data type occupies 1 byte o f memory (that is, it holds
only one character at a time).
✓ The modifiers that can precede char are signed and unsigned.
The various character data types with their size and range are
listed in Table
Void:
✓ The void data type is used for specifying an empty parameter list
to a function and return type for a function.
✓ When void is used to specify an empty parameter list, it
indicates that a function does not take any arguments and
when it is used as a return type for a function, it indicates that
a function does not return any value.
✓ For void, no memory is allocated and hence, it cannot store
anything. As a result, void cannot be used to declare simple
variables, however, it can be used to declare generic pointers.
Data types that are derived from the built-in data types are known as
derived data types.
The various derived data types provided by C++ are arrays, junctions,
references and pointers.
Array
✓ An array is a set of elements of the same data type that are
referred to by the same name.
✓ All the elements in an array are stored at contiguous (one after
another) memory locations and each element is accessed by a
unique index or subscript value.
✓ The subscript value indicates the position of an element in an
array.
Function
✓ A function is a self-contained program segment that carries out
a specific well-defined task. In C++, every program contains one
or more functions which can be invoked from other parts of a
program, if required.
Reference
✓ A reference is an alternative name for a variable.
✓ That is, a reference is an alias for a variable in a program.
✓ A variable and its reference can be used interchangeably in a
program as both refer to the same memory location.
✓ Hence, changes made to any of them (say, a variable) are
reflected in the other (on a reference).
34
Pointer
✓ A pointer is a variable that can store the memory address of
another variable.
✓ Pointers allow to use the memory dynamically.
✓ That is, with the help of pointers, memory can be allocated or
de-allocated to the variables at run-time, thus, making a
program more efficient.
Enumeration:
✓ An enumeration is a set of named integer constants that specify
all the permissible values that can be assigned to enumeration
variables.
✓ These set of permissible values are known as enumerators.
Country1 = 3; //warning
Country1 = UN; / /valid
12 Variables in C++
Examples of Invalid Variable names are: 123, (area), 6th, %abc etc.
Declaration of Variables
data_type variable_name;
int x, y, z;
Initialization of Variables
int i=10;
#include<iostream>
using namespace std;
int main ()
{
int num1 = 5, num2 = 6; //static initialization using constant
int num3 = num1 + num2; // Dynamic initialization using
expression cout<<num3;
return 0;
}
13 Reference Variables
#include<iostream>
int main ( )
14 Operators in C++
int x = 1;
==
}= ==
int x
= 2;
} = ==
# include<iostream>
int m = 10;
main ( )
int m = 20;
int k = m;
int m = 30;
Manipulators
Manipulators are operators that are used to format he data display.
There are two important manipulators.
1) endl
2) setw
1) endl:
Ex- cout< <"a="< < a << endl <<"n="< < n<< endl< <"p="<<p< endl;
OUTPUT:
a = 2568
n = 34
p = 275
2 Setw :
With the setw, we can specify a common field width for all the
numbers and force them to print with right alignment.
EX : cout< <setw (5)< < sum< endl;
The manipulator setw(5) specifies a field width of 5 for printing the
value of variable sum the value is right justified.
3 5 6
Type cast operator:
C+ permits explicit type conversion of variables or expressions using
the type cast operator.
Syntax - type name (expression)
Ex : avg = sum/float(i)
Here a type name behaves as if it is a function for converting
values to a designated type
49
18 Storage classes
Storage classes are used to specify the lifetime and scope of variables.
How storage is allocated for variables and How variable is treated by
complier depends on these storage classes.
These are basically divided into 5 different types :
1. Global variables
2. Local variables
3. Register variables
4. Static variables
5. Extern variables
Global Variables
These are defined at the starting , before all function bodies and are
available throughout the program.
using namespace std;
int globe; // Global variable
void func();
int main()
{
.....
}
Local variables
They are defined and are available within a particular scope. They are
also called Automatic variablebecause they come into being when
scope is entered and automatically go away when the scope ends.
The keyword auto is used, but by default all local variables are auto,
so we don't have to explicitly add keyword auto before variable
dedaration. Default value of such variable is garbage.
50
Register variables
This is also a type of local variable. This keyword is used to tell the
compiler to make access to this variable as fast as possible. Variables
are stored in registers to increase the access speed.
But you can never use or compute address of register variable and
also , a register variable can be declared only within a block, that
means, you cannot have global or static register variables.
Static Variables
Static variables are the variables which are initialized & allocated
storage only once at the beginning of program execution, no matter
how many times they are used and called in the program. A static
variable retains its value until the end of program.
void fun()
{
static int i = 10;
i++;
cout << i;
}
int main()
{
fun(); // Output = 11
fun(); // Output = 12
fun(); // Output = 13
}
As, i is static, hence it will retain its value through function calls, and
is initialized only once at the beginning.
Static specifiers are also used in classes, but that we will learn later.
Extern Variables
This keyword is used to access variable in a file which is declared &
defined in some other file, that is the existence of a global variable in
one file is declared using extern keyword in another file.
51
52
NOTES:-MODULE-1
53
54
55
Module II
Control Structures.
Classes and Objects: Specifying a class, defining member functions,
C++ program with class, private member functions, arrays within
class, memory allocation for objects, static data members, static
member functions, arrays of objects, returning objects.
Functions in C++: main function, function prototyping, call by
reference, return by reference, inline functions, default arguments.
1. Control structures
• if statement
• switch statement
• conditional operator statement
• goto statement
1. Simple if statement
2. If....else statement
3. Nested if....else statement
4. else if statement
56
Simple if statement
The general form of a simple if statement is,
if( expression )
{
statement-inside;
}
statement-outside;
If the expression is true, then 'statement-inside' it will be executed,
otherwise 'statement-inside' is skipped and only 'statement-outside' is
executed.
Example :
#include< iostream.h>
int main( )
{
int x,y;
x=15;
y=13;
if (x > y )
{
cout << "x is greater than y";
}
}
Output :
x is greater than y
if...else statement
The general form of a simple if...else statement is,
if( expression )
{
statement-block1;
}
else
{
statement-block2;
}
57
}
else
{
statement-block3;
}
if 'expression' is false the 'statement-block3' will be executed,
otherwise it continues to perform the test for 'expression 1' . If the
'expression 1' is true the 'statement-block1' is executed otherwise
'statement-block2' is executed.
Example :
void main( )
{
int a,b,c;
clrscr();
cout << "enter 3 number";
cin >> a >> b >> c;
if(a > b)
{
if( a > c)
{
cout << "a is greatest";
}
else
{
cout << "c is greatest";
}
}
else
{
if( b> c)
{
cout << "b is greatest";
}
59
else
{
printf("c is greatest");
}
}
getch();
}
else-if ladder
The general form of else-if ladder is,
if(expression 1)
{
statement-block1;
}
else if(expression 2)
{
statement-block2;
}
else if(expression 3 )
{
statement-block3;
}
else
default-statement;
The expression is tested from the top(of the ladder) downwards. As
soon as the true condition is found, the statement associated with it is
executed.
60
Example :
void main( )
{
int a;
cout << "enter a number";
cin >> a;
if( a%5==0 && a%8==0)
{
cout << "divisible by both 5 and 8";
}
else if( a%8==0 )
{
cout << "divisible by 8";
}
else if(a%5==0)
{
cout << "divisible by 5";
}
else
{
cout << "divisible by none";
}
getch();
}
61
break;
default:
The break statement is used to prevent the code running into the next
case.
62
Looping in C++
In any programming language, loops are used to execute a set of
statements repeatedly until a particular condition is satisfied.
How it works
1. while loop
2. for loop
3. do-while loop
63
while loop
while loop can be address as an entry control loop. It is completed in
3 steps.
Syntax :
variable initialization ;
while (condition)
{
statements ;
variable increment or decrement ;
}
for loop
for loop is used to execute a set of statement repeatedly until a
particular condition is satisfied. we can say it an open ended
loop. General format is,
for(initialization; condition ; increment/decrement)
{
statement-block;
}
In for loop we have exactly two semicolons, one after initialization and
second after condition. In this loop we can have more than one
initialization or increment/decrement, separated using comma
operator. for loop can have only one condition.
64
do while loop
In some situations it is necessary to execute body of the loop before
testing the condition. Such situations can be handled with the help
of do-while loop. do statement evaluates the body of the loop first and
at the end, the condition is checked using while statement. General
format of do-while loop is,
do
{
....
.....
}
while(condition);
1) break statement
When break statement is encountered inside a loop, the loop is
immediately exited and the program continues with the statement
immediately following the loop.
2) continue statement
It causes the control to go directly to the test-condition and then
continue the loop process. On encountering continue, cursor leave the
current cycle of loop, and starts with the next cycle.
66
For example:
void read( );
void display( );
Here c1 is object of class circle and operator dot (.) is used to access
member functions.
• Access Specifiers are used to identify access rights for the data
members and member functions of the class.
• Depending upon the access level of a class member, access to it
is allowed or denied.
68
1. Private:
class PrivateAccess
{
private: // private access specifier
int x; // Data Member Declaration
void display(); // Member Function decaration
2. Public:
class PublicAccess
{
public: // public access specifier
int x; // Data Member Declaration
void display(); // Member Function decaration
}
3. Protected:
class ProtectedAccess
{
protected: // protected access specifier
int x; // Data Member Declaration
void display(); // Member Function decaration
}
(The beginning of the main program can be done by using left curly
brace "{").
• The member function define in the class are access by using dot
(.) operator.
• Suppose we have two-member functions void read () and void
display ().
• We have to access these members function in the main
program.
(The right curly brace "}" is used to end the main program).
71
void setRollno(int i)
{
rollno=i;
}
};
int main()
{
Student A;
A.rollono=1; //Compile time error
cout<< A.rollno; //Compile time error
A.setRollno(1); //Rollno initialized to 1
cout<< A.getRollno(); //Output will be 1
}
73
So this is how we access and use the private data members of any
class using the getter and setter methods. We will discuss this in more
details later.
Example:
#include<iostream>
const int size=5;
class student
{
int roll_no;
int marks[size];
public:
void getdata ();
void tot_marks ();
} ;
void main()
{
student stu;
stu.getdata() ;
stu.tot_marks() ;
getch();
}
Output:
Enter roll no: 101
Enter marks in subject 1: 67
Enter marks in subject 2 : 54
Enter marks in subject 3 : 68
Enter marks in subject 4 : 72
Enter marks in subject 5 : 82
Total marks = 343
76
Memory Allocation
Example:
#include <iostream>
class Box
{
public:
Box() {
cout << "Constructor is called!" <<endl;
}
~Box() {
cout << "Destructor is called!" <<endl;
}
};
void main( )
{
Box* myBoxArray = new Box[4];
delete [] myBoxArray; // Delete array
getch();
}
77
Output:
Constructor is called!
Constructor is called!
Constructor is called!
Constructor is called!
Destructor is called!
Destructor is called!
Destructor is called!
Destructor is called!
78
Static Keyword
Static variables when used inside function are initialized only once,
and then they hold there value even through function calls.
These static variables are stored on static storage area , not in stack.
void counter()
{
static int count=0;
cout << count++;
}
int main(0
{
for(int i=0;i<5;i++)
{
counter();
}
}
Output :
01234
void counter()
{
int count=0;
cout << count++;
}
79
int main()
{
for(int i=0;i<5;i++)
{
counter();
}
}
Output :
00000
Static keyword works in the same way for class objects too. Objects
declared static are allocated storage in static storage area, and have
scope till the end of program.
Static objects are also initialized using constructors like other normal
objects. Assignment to zero, on using static keyword is only for
primitive datatypes, not for user defined datatypes.
class Abc
{
int i;
public:
Abc()
{
i=0;
cout << "constructor";
}
~Abc()
{
cout << "destructor";
}
};
80
void f()
{
static Abc obj;
}
int main()
{
int x=0;
if(x==0)
{
f();
}
cout << "END";
}
Output :
You must be thinking, why was destructor not called upon the end of
the scope of if condition. This is because object was static, which has
scope till the program lifetime, hence destructor for this object was
called when main() exits.
Static data members of class are those members which are shared by
all the objects. Static data member has a single piece of storage, and
is not available as separate copy with each object, like other non-
static data members.
class X
{
static int i;
public:
X(){};
};
int X::i=1;
81
int main()
{
X obj;
cout << obj.i; // prints value of i
}
Once the definition for static data member is made, user cannot
redefine it. Though, arithmetic operations can be performed on it.
NOTES:
These functions work for the class as whole rather than for a
particular object of a class.
Example :
class X
{
public:
static void f(){};
};
83
int main()
{
X::f(); // calling member function directly with class name
}
It doesn't have any "this" keyword which is the reason it cannot access
ordinary members. We will study about "this" keyword later.
#include<iostream.h>
#include<conio.h>
class student
{
private:
int rollno, age;
char sex;
float weight, height;
public:
void get info ()
{
cout<<”\n enter roll number”;
cin>>rollno;
cout<<”\n enter age”;
cin>>age;
cout<<”\n enter sex”;
cin>>sex;
84
void main ()
{
student obj [100];
int i, n;
cout<<”how many student?”;
cin>>n;
cout<<”\n enter the information:”;
for (i=0; i<n;i++)
{
obj [i].disinfo ();
}
getch ();
}
85
Example 2:
#include <iostream>
#include <string>
class Student
{
string name;
int marks;
public:
void getName()
{
getline( cin, name );
}
void getMarks()
{
cin >> marks;
}
void displayInfo()
{
cout << "Name : " << name << endl;
cout << "Marks : " << marks << endl;
}
};
int main()
{
Student st[5];
for( int i=0; i<5; i++ )
{
cout << "Student " << i + 1 << endl;
cout << "Enter name" << endl;
st[i].getName();
cout << "Enter marks" << endl;
st[i].getMarks();
}
Returning Objects
int main() {
cout << “Added Result for this C++ tutorial: “<< AddToFriend(4) <<
endl;
}
88
Functions in C++
main function, function prototyping, call by reference, return by
reference, inline functions, default arguments.
C++ Functions
Syntax:
return_type function_name( parameter list )
{
body of the function
}
Return Type:
Function Name:
Parameters:
Function Body:
Example:
#include <iostream>
// function declaration
int max(int num1, int num2);
int main ()
{
// local variable declaration:
int a = 99;
int b = 97;
int ret;
return 0;
}
return result;
}
Output:
Max value is : 99
Function prototyping
Old style:
Prototype style:
Call by Reference
Example:
#include <iostream>
// function declaration
void swap(int &x, int &y);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
return 0;
}
OUTPUT:
Return by Reference
Example:
#include <iostream>
int n;
int& test();
int main()
{
test() = 5;
cout<<n;
return 0;
}
int& test()
{
return n;
}
OUTPUT:
Note:
Syntax:
inline return-type function-name(arguments)
{
return ( conditions );
}
#include <iostream>
Max (30,40): 40
Max (0,100): 100
Max (700,10): 700
95
#include<iostream>
25
50
80
97
Example 2
#include<iostream>
using namespace std;
Output:
25
50
80
98
Notes: Module2
99
100
101
Module III
More about Functions: Function overloading, friendly functions:
friend function, a function friendly to two classes, objects as function
arguments.
Constructors & Destructors: Constructors, parameterized
constructors, multiple constructors in a class, constructors with
default arguments, copy constructors, dynamic constructors,
destructors.
1.Function Overloading
✓ Two or more functions having same name but different
argument(s) are known as overloaded functions.
int main()
{
sum (10,20);
sum(10.5,20.5);
}
104
class printData
{
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};
void main(void)
{
printData pd;
// Call print to print integer
pd.print(9);
// Call print to print float
pd.print(100.200);
// Call print to print character
pd.print("Hello C++");
getch();
}
Printing int: 9
Printing float: 100.200
Printing character: Hello C++
105
Note:
Here, the display() function is called three times with different type or
number of arguments.
106
Friend function
Syntax:
class class_name
{
...... .... ........
friend return_type function_name(arguments);
...... .... ........
}
• Now, you can define friend function of that name and that
function can access the private and protected data of that
function.
• No friend keyword is used in the definition.
• For accessing the data, the declaration of a friend function
should be made inside the body of the class (can be anywhere
inside class either in private or public section) starting with
keyword friend.
107
class className
{
... .. ...
friend return_type functionName(argument/s);
... .. ...
}
return_type functionName(argument/s)
{
... .. ...
// Private and protected data of className can be
accessed from
// this function because it is a friend function of
className.
... .. ...
}
/* C++ program to demonstrate the working of friend function.*/
#include <iostream>
using namespace std;
class Distance
{
private:
int meter;
public:
Distance(): meter(0) { }
//friend function
friend int addFive(Distance);
};
// friend function definition
int addFive(Distance d)
{
//accessing private data from non-member function
d.meter += 5;
return d.meter;
}
int main()
{
Distance D;
cout<<"Distance: "<< addFive(D);
return 0;
}
OUTPUT:
Distance: 5
// forward declaration
class B;
class A {
private:
int numA;
public:
A(): numA(12) { }
// friend function declaration
friend int add(A, B);
};
class B {
private:
int numB;
public:
B(): numB(1) { }
// friend function declaration
friend int add(A , B);
};
int main()
{
A objectA;
B objectB;
cout<<"Sum: "<< add(objectA, objectB);
return 0;
}
Sum: 13
In this program, classes A and B have declared add() as a friend function. Thus, this
function can access private data of both class.
Here, add() function adds the private data numA and numB of two objects objectA
and objectB, and returns it to the main function.
To make this program work properly, a forward declaration of a class class B should
be made as shown in the above example.
This is because class B is referenced within the class A using code: friend int
add(A , B);.
109
Call by value
Arguments are passed by value, the function create its own copy of
the objects and works with it. Any modification made to the object in
the function does not affect the object used to call the function.
Let us understand passing arguments by value by the following
example more clearly :-
#include <iostream>
using namespace std;
class Convert
{
public :
int i;
void increment(Convert obj)
{
obj.i=obj.i*2;
cout << "Value of i in member function : " << obj.i;
}
};
int main ()
{
Convert obj1;
obj1.i=3;
obj1.increment(obj1);
cout << "\nValue of i in main : " << obj1.i << "\n";
system("pause");
return 0;
}
Call by reference
If arguments are passed by reference, the memory address is passed
directly to the function. And the function works directly works directly
with the original object.
Let us understand more clearly calling functions by giving reference in
the methods by the following example :-
#include <iostream>
using namespace std;
class Convert
{
public :
int i;
void increment(Convert &obj)
{
obj.i=obj.i*2;
cout << "Value of i in member function : " <<
obj.i;
}
};
int main ()
{
Convert obj1;
obj1.i=3;
obj1.increment(obj1);
cout << "\nValue of i in main : " << obj1.i << "\n";
system("pause");
return 0;
}
Constructors
• Constructor has the same name as that of the class and it does
not have any return type. Also, the constructor is always public.
class temporary
{
private:
int x;
float y;
public:
// Constructor
temporary(): x(5), y(5.5)
{
// Body of constructor
}
... .. ...
};
int main()
{
Temporary t1;
... .. ...
}
You can also initialize the data members inside the constructor's body
as below. However, this method is not preferred.
113
Suppose you are working on 100's of Person objects and the default
value of a data member age is 0. Initialising all objects manually will
be a very tedious task.
Constructor in detail:
Syntax
class_name () { Constructor Definition }
Example:
#include <iostream>
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor
private:
double length;
};
// Member functions definitions including constructor
Line::Line(void)
{
cout << "Object is being created" << endl;
}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
// Main function for the program
void main( )
{
Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
}
OUTPUT:
Object is being created
Length of line : 6
115
Parameterized Constructors
Example:
class Cube
{
public:
int side;
Cube(int x)
{
side=x;
}
};
int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
}
OUTPUT : 10 20 30
Example:2
#include <iostream>
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(double len); // This is the constructor
private:
double length;
};
// Member functions definitions including constructor
Line::Line( double len)
{
cout << "Object is being created, length = " << len << endl;
length = len;
}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
// Main function for the program
void main( )
{
Line line(10.0);
// get initially set length.
cout << "Length of line : " << line.getLength() <<endl;
// set line length again
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
getch();
}
OUTPUT:
Object is being created, length = 10
Length of line : 10
Length of line : 6
117
Overloaded constructors have the same name (name of the class) but
different number of arguments.
Example1
// Source Code to demonstrate the working of overloaded
constructors
#include <iostream>
using namespace std;
class Area
{
private:
int length;
int breadth;
public:
// Constructor with no arguments
Area(): length(5), breadth(2) { }
void GetLength()
{
cout << "Enter length and breadth respectively: ";
cin >> length >> breadth;
}
int main()
{
Area A1, A2(2, 1);
int temp;
return 0;
}
OUTPUT:
Example2:
class Student
{
int rollno;
string name;
public:
Student(int x)
{
rollno=x;
name="None";
}
Student(int x, string str)
{
rollno=x ;
name=str ;
}
};
int main()
{
Student A(10);
Student B(11,"Ram");
}
Syntax
class_name ()
{ Constructor Definition }
class Cube
{
int side;
public:
Cube()
{
side=10;
}
};
int main()
{
Cube c;
cout << c.side;
}
Output : 10
In this case, as soon as the object is created the constructor is called
which initializes its data members.
A default constructor is so important for initialization of object
members, that even if we do not define a constructor explicitly, the
compiler will provide a default constructor implicitly.
class Cube
{
public:
int side;
};
int main()
{
Cube c;
cout << c.side;
}
121
OUTPUT:
0
In this case, default constructor provided by the compiler will be
called which will initialize the object data members to default value,
that will be 0 in this case.
Copy Constructor
....
int main()
{
Area A1, A2(2, 1);
Syntax:
class-name (class-name &)
{
. . . .
}
Example:
#include<iostream.h>
#include<conio.h>
class copy
{
int var,fact;
public:
copy(int temp)
{
var = temp;
}
double calculate()
{
fact=1;
for(int i=1;i<=var;i++)
{
fact = fact * i;
}
return fact;
}
};
void main()
{
clrscr();
int n;
cout<<"\n\tEnter the Number : ";
cin>>n;
copy obj(n);
copy cpy=obj;
cout<<"\n\t"<<n<<" Factorial is:"<<obj.calculate();
cout<<"\n\t"<<n<<" Factorial is:"<<cpy.calculate();
getch();
}
OUTPUT:
Im Constructor
Values :10 20
Values :10 20
124
Dynamic Constructors
Example:
#include <iostream.h>
#include <conio.h>
class dyncons
{
int * p;
public:
dyncons()
{
p=new int;
*p=10;
}
dyncons(int v)
{
p=new int;
*p=v;
}
int dis()
{ return(*p);
}
};
void main()
{
clrscr();
dyncons o, o1(9);
cout<<"The value of object o's p is:";
cout<<o.dis();
cout<<"\nThe value of object 01's p is:"<<o1.dis();
getch();
}
Destructor
Syntax:
class A
{
public:
~A();
};
For example, a constructor may have opened a file and a memory area
may be allotted to it. Similarly, a constructor may have allocated
memory to some other objects.
126
class A
{
A()
{
cout << "Constructor called";
}
~A()
{
cout << "Destructor called";
}
};
int main()
{
A obj1; // Constructor Called
int x=1
if(x)
{
A obj2; // Constructor Called
} // Destructor Called for obj2
} // Destructor called for obj1
Notes: Module3
129
130
131
MODULE-IV
Inheritance: Introduction to inheritance, single inheritance, making a
private member inheritable (protected member), multi-level
inheritance, multiple inheritance, hierarchical inheritance, hybrid
inheritance.
Operator Overloading: Rules for overloading operators, overloading
unary operators, overloading binary operators.
Pointers: Introduction to pointers, declaring and initializing pointers,
arithmetic operations on pointers, pointers with arrays, arrays of
pointers, pointers to objects, 'this' pointer.
INHERITANCE:
Purpose of Inheritance
1. Code Reusability
2. Method Overriding (Hence, Runtime Polymorphism.)
3. Use of Virtual Keyword
While defining a subclass like this, the super class must be already
defined or atleast declared before the subclass declaration.
Example:
Example
class Animal
{ public:
int legs = 4;
};
int main()
{
Dog d;
cout << d.legs;
cout << d.tail;
}
OUTPUT
41
133
1) Public Inheritance
This is the most used inheritance mode. In this the protected member
of super class becomes protected members of sub class and public
becomes public.
2) Private Inheritance
3) Protected Inheritance
Protected
Base class Public Mode Private Mode
Mode
Types of Inheritance:
C++, we have 5 different types of Inheritance. Namely,
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance (also known as Virtual Inheritance)
Single Inheritance
In this type of inheritance one derived class inherits from only one
base class. It is the most simplest form of Inheritance.
Multiple Inheritance
In this type of inheritance a single derived class may inherit from two
or more than two base classes.
135
Hierarchical Inheritance
Multilevel Inheritance
Multilevel Inheritance
140
141
Multiple Inheritance
142
143
Hierarchical Inheritance
144
145
146
Hybrid Inheritance
147
148
149
class base_class2
{
properties;
methods;
};
... ... ...
... ... ...
class base_classN
{
properties;
methods;
};
Operator Overloading:
In C++, operators like '+', '-' have specified functions for native data-
types. For example, division operator "/" divides two integers when
used as a / b. But, the functions of these operators can also be
extended for user-defined data-types as well, this is known as
Operator Overloading.
For example:
c = add(c1,c2);
Here, c1 and c2 are two complex number to be added and c holds the
result returned by the function. c, c1 and c2 are objects of a class
complex. Using operator overloading, we can replace the calling
statement as,
c = c1+c2;
This statement gives more sense and user can clearly understand that
two complex numbers are being added. Further statements like
z = add(mult(a,b),sub(x,y));
can be replaced by
z = (a*b)+(x-y);
class example
{
int a,b;
public:
void input()
{
cout<<"Enter a and b: ";
cin>>a>>b;
}
void operator -() //operator function as a member function
{
a=-a;
b=-b;
}
void display()
{
cout<<"a="<<a<<endl<<"b="<<b<<endl;
}
};
int main()
{
example e;
e.input();
cout<<"Before overloading unary minus operator"<<endl;
e.display();
-e;
cout<<"After overloading unary minus operator"<<endl;
e.display();
getch();
return 0;
}
Enter a and b: 13 -9
Before overloading unary minus operator
a=13
b=-9
After overloading unary minus operator
a=-13
b=9
157
Unary operators:
#include <iostream>
public:
Test(): count(5){}
Introduction to pointers
type *var-name;
Here, type is the pointer's base type; it must be a valid C++ type and
var-name is the name of the pointer variable. The asterisk you used to
declare a pointer is the same asterisk that you use for multiplication.
However, in this statement the asterisk is being used to designate a
variable as a pointer. Following are the valid pointer declaration −
The actual data type of the value of all pointers, whether integer, float,
character, or otherwise, is the same, a long hexadecimal number that
represents a memory address. The only difference between pointers of
different data types is the data type of the variable or constant that
the pointer points to.
164
Example:
#include <iostream>
int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable
return 0;
}
OUTPUT:
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
165
Pointer variables are declared like normal variables except for the
addition of the unary ∗ character.
type ∗var_name ;
where type is any valid C++ data type and var_name is the name of
the pointer variable. Following declarations declares pointers of
different types :
When we say that iptr is an integer pointer, it means that the memory
location being pointer to by iptr can hold only integer values.
Thus, it is the base type of the pointer that defines what types of
variables the pointer can point to.
Two special operators ∗ and & are used with pointers. The & is a
unary operator that returns the memory address of its operand. For
example,
The pointer operator ∗ (called "at address" sign) is the same sign as
multiply operator ∗ and the pointer operator & ( called "address of"
sign) is same as bitwise AND operator &. But these operators have no
relationship to each other, Both pointer operator & and ∗ have a
higher precedence than all other arithmetic operators except the
unary minus, with which they have equal precedence.
int ∗iptr = NULL ; //iptr gets initialized but does not to a legal
address
:
if(iptr != NULL)
{
: //use the pointer if it pointers to a legal address
}
When we use NULL for initializing pointers then before using the
pointer anywhere in the program, first check that it is non-zero or
non-NULL as shown in the above code fragment.
#include <iostream>
int main()
cout << "Value lives at: " << value << "\n";
return 0;
p1++ ;
what would the above expression do? The value of p1 (i.e. the address
pointed to by p1) gets changed. The address becomes 104 not 101
because an integer occupies 4 bytes. If an integer occupied 2 bytes
then the result would be address 102. Similarly if you do:
p1--;
p1 = p1 + 10;
This makes p1 point to the tenth element of p1's data type beyond the
current position. If p1 points to a character type then p1 + 10 would
move the pointer 10 bytes. Suppose p1 were a integer then p1 would
move 20 bytes (if int occupies 2 bytes).
169
170
171
Pointers are the variables that hold address. Not only can pointers
store address of a single variable, it can also store address of cells of
an array.
int* ptr;
int a[5];
ptr = &a[2]; // &a[2] is the address of third element of a[5].
Since ptr points to the third element in the above example, ptr + 1 will
point to the fourth element.
You may think, ptr + 1 gives you the address of next byte to the ptr.
But it's not correct.
This is because pointer ptr is a pointer to an int and size of int is fixed
for a operating system (size of int is 4 byte of 64-bit operating system).
Hence, the address between ptr and ptr + 1 differs by 4 bytes.
If pointer ptr was pointer to char then, the address between ptr and
ptr + 1 would have differed by 1 byte since size of a character is 1
byte.
172
int main()
{
float arr[5];
float *ptr;
cout << "Displaying address using arrays: " << endl;
for (int i = 0; i < 5; ++i)
{
cout << "&arr[" << i << "] = " << &arr[i] << endl;
}
// ptr = &arr[0]
ptr = arr;
cout<<"\nDisplaying address using pointers: "<< endl;
for (int i = 0; i < 5; ++i)
{
cout << "ptr + " << i << " = "<< ptr + i << endl;
}
return 0;
}
Displaying address using arrays:
&arr[0] = 0x7fff5fbff880
&arr[1] = 0x7fff5fbff884
&arr[2] = 0x7fff5fbff888
&arr[3] = 0x7fff5fbff88c
&arr[4] = 0x7fff5fbff890
In the above program, a different pointer ptr is used for displaying the address of
array elements arr. But, array elements can be accessed using pointer notation by
using same array name arr. For example:
int arr[3];
Arrays of pointers
int *ptr[MAX];
#include <iostream>
int main () {
int var[MAX] = {10, 100, 200};
int *ptr[MAX];
return 0;
}
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
174
Pointers to objects
The pointers pointing to objects are referred to as Object Pointers.
class-name ∗ object-pointer ;
this pointer
As soon as we define a class, the member functions are created and
placed in the memory space only once.
That is, only one copy of member functions is maintained that is
shared by all the objects of the class.
Only space for data members is allocated separately for each object
(See the following figure).
How could the member function3 come to know which object's data
member2 is to be changed ?
The this pointer can be thought of analogous to the ATM card. For
instance, in a bank there are many accounts.
Now, these ATMs can withdraw from any account in the bank, but
which account are they supposed to work upon ? This is resolved by
the ATM card, which gives the identification of user and his accounts,
from where the amount is withdrawn.
Similarly, the this pointer is the ATM cards for objects, which
identifies the currently-calling object. The this pointer stores the
address of currently-calling object. To understand this, consider the
following example program (following program illustrates the
functioning of this pointer) :
#include<iostream.h>
#include<conio.h>
#include<string.h>
class Salesman
{
char name[1200];
float total_sales;
public:
Salesman(char *s, float f)
{
strcpy(name, "");
strcpy(name, s);
total_sales = f;
}
void prnobject(void)
{
cout.write(this->name, 26); // use of
this pointer
cout<<" has invoked prnobject().\n";
}
};
void main()
{
clrscr();
Salesman Rajat("Rajat", 21450), Ravi("Ravi", 23190),
Vikrant("Vikrant", 19142);
/* above statement creates three objects */
Rajat.prnobject();
Vikrant.prnobject();
Ravi.prnobject();
getch();
}
178
Notes:-Module4
179
180
181
182
Module V
Polymorphism and Virtual Functions: Compile-time polymorphism,
runtime polymorphism, virtual functions.
Managing Console I/O Operations: Unformatted I/O operations,
formatted console i/o operations (width( ), precision( ), fill( )),
managing output with manipulators (setw( ), endl).
Templates: Introduction, function templates, class templates.
Exception Handling: Introduction, exception handling mechanism,
throwing mechanism, catching mechanism.
Polymorphism in C++
Suppose if you are in class room that time you behave like a
student, when you are in market at that time you behave like a
customer, when you at your home at that time you behave like a
son or daughter, Here one person have different-different behaviors.
183
Type of polymorphism
• Method overloading
• Method overriding
Output
30
60
Output
Base class
Derived Class
187
.......
.......
}
188
bptr=&bobj;
bptr->show(); // call derive class function
getch();
}
Output
Templates
Templates are often used in larger codebase for the purpose of code
reusability and flexibility of the programs.
• Function Templates
• Class Templates
Function Templates
A single function template can work with different data types at once
but, a single normal function can only work with one set of data types.
#include <iostream>
using namespace std;
// template function
template <class T>
T Large(T n1, T n2)
{
return (n1 > n2) ? n1 : n2;
}
int main()
{
int i1, i2;
float f1, f2;
char c1, c2;
return 0;
}
Output
Enter two integers:
12 13
13 is larger.
Large() function returns the largest among the two arguments using a
simple conditional operation.
Similarly, when floating-point data and char data are passed, it knows
the argument data types and generates the Large() function
accordingly.
#include <iostream>
using namespace std;
template <typename T>
void Swap(T &n1, T &n2)
{
T temp;
temp = n1;
n1 = n2;
n2 = temp;
}
int main()
{
int i1 = 1, i2 = 2;
float f1 = 1.1, f2 = 2.2;
char c1 = 'a', c2 = 'b';
cout << "Before passing data to function template.\n";
cout << "i1 = " << i1 << "\ni2 = " << i2;
cout << "\nf1 = " << f1 << "\nf2 = " << f2;
cout << "\nc1 = " << c1 << "\nc2 = " << c2;
Swap(i1, i2);
Swap(f1, f2);
Swap(c1, c2);
cout << "\n\nAfter passing data to function template.\n";
cout << "i1 = " << i1 << "\ni2 = " << i2;
cout << "\nf1 = " << f1 << "\nf2 = " << f2;
cout << "\nc1 = " << c1 << "\nc2 = " << c2;
return 0;
}
Output
i1 = 1
i2 = 2
f1 = 1.1
f2 = 2.2
194
c1 = a
c2 = b
i1 = 2
i2 = 1
f1 = 2.2
f2 = 1.1
c1 = b
c2 = a
The Swap() function template takes two arguments and swaps them
by reference.
195
Class Templates
Like function templates, you can also create class templates for
generic class operations.
Normally, you would need to create a different class for each data type
OR create different member variables and functions within a single
class.
This will unnecessarily bloat your code base and will be hard to
maintain, as a change is one class/function should be performed on
all classes/functions.
However, class templates make it easy to reuse the same code for all
data types.
class className
... .. ...
public:
T var;
T someOperation(T arg);
... .. ...
};
To create a class template object, you need to define the data type
inside a < > when creation.
className<dataType> classObject;
For example:
className<int> classObject;
className<float> classObject;
className<string> classObject;
Example 3: Simple calculator using Class template
#include <iostream>
using namespace std;
template <class T>
class Calculator
{
private:
T num1, num2;
public:
Calculator(T n1, T n2)
{
num1 = n1;
num2 = n2;
}
void displayResult()
{
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;
}
197
int main()
{
Calculator<int> intCalc(2, 1);
Calculator<float> floatCalc(2.4, 1.2);
return 0;
}
Output
Int results:
Addition is: 3
Subtraction is: 1
Product is: 2
Division is: 2
Float results:
Division is: 2
The class contains two private members of type T: num1 & num2, and
a constructor to initalize the members.
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.
1. cin
2. cout
A) void get()
Syntax:
char c=cin.get();
200
#include<iostream>
using namespace std;
int main()
{
char c=cin.get();
cout<<c<<endl;
return 0;
}
K
K
B) void put()
It is a method of cout object and it is used to print the specified character on the
screen or monitor.
Syntax:
cout.put(variable / character);
#include<iostream>
using namespace std;
int main()
{
char c=cin.get();
cout.put(c); //Here it prints the value of variable c;
cout.put('c'); //Here it prints the character 'c';
return 0;
}
I
Ic
201
This is a method of cin object and it is used to input a string with multiple spaces.
Syntax:
char x[30];
cin.getline(x,30);
#include<iostream>
using namespace std;
int main()
{
cout<<"Enter name :";
char c[10];
cin.getline(c,10); //It takes 10 charcters as input;
cout<<c<<endl;
return 0;
}
Enter name :Srinu
Srinu
It is a method of cout object. This method is used to read n character from buffer
variable.
Syntax:
cout.write(x,2);
#include<iostream>
using namespace std;
int main()
{
cout<<"Enter name : ";
char c[10];
cin.getline(c,10); //It takes 10 charcters as input;
cout.write(c,9); //It reads only 9 character from buffer c;
return 0;
}
E) cin
Syntax:
cin>>variable / character / String / ;
#include<iostream>
using namespace std;
int main()
{
int num;
char ch;
string str;
cout<<"Enter Number"<<endl;
cin>>num; //Inputs a variable;
cout<<"Enter Character"<<endl;
cin>>ch; //Inputs a character;
cout<<"Enter String"<<endl;
cin>>str; //Inputs a string;
return 0;
}
Enter Number
07
Enter Character
h
Enter String
Srinu
F) cout
Syntax:
cout<< variable / charcter / string;
#include<iostream>
using namespace std;
int main()
{
int num=100;
char ch='X';
string str="Srinu";
return 0;
}
203
Number is 100
Character is X
String is srinu
A) width(n)
Syntax:
cout<<setw(int n);
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int x=10;
cout<<setw(20)<<variable;
return 0;
}
10
204
B) fill(char)
Syntax:
cout<<setfill('character')<<variable;
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int x=10;
cout<<setw(20);
cout<<setfill('#')<<x;
return 0;
}
##################10
D) precison(n)
Syntax:
cout<<setprecision('int n')<<variable;
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
float x=10.12345;
cout<<setprecision(5)<<x;
return 0;
}
10.123
E) setflag(arg 1, arg,2)
Syntax:
F) unsetflag(arg 2)
Syntax:
resetiosflags(argument 2);
G) setbase(arg)
Syntax:
setbase(argument);
206
Exception
1. try
2. catch
3. throw
207
try
catch( ExceptionName e1 )
// catch block
catch( ExceptionName e2 )
// catch block
catch( ExceptionName eN )
// catch block
}
208
Try Block
Catch block
Example
#include<iostream.h>
#include<conio.h>
void main()
{
int a, ans;
a=10;
ans=a/0;
cout<<"Result: "<<ans;
}
Output
Example
#include<iostream.h>
#include<conio.h>
void main()
{
int a=10, ans=0;
try
{
ans=a/0;
}
catch(int i)
{
cout<<"Denominator not be zero";
}
}
Output
try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {
// catch block
}
You can list down multiple catch statements to catch different type
of exceptions in case your try block raises more than one exception
in different situations.
Throwing Exceptions
Exceptions can be thrown anywhere within a code block using throw
statement. The operand of the throw statement determines a type for
the exception and can be any expression and the type of the result of
the expression determines the type of exception thrown.
Catching Exceptions
The catch block following the try block catches any exception. You
can specify what type of exception you want to catch and this is
determined by the exception declaration that appears in parentheses
following the keyword catch.
try {
// protected code
} catch( ExceptionName e ) {
// code to handle ExceptionName exception
}
Above code will catch an exception of ExceptionName type. If you
want to specify that a catch block should handle any type of
exception that is thrown in a try block, you must put an ellipsis, ...,
between the parentheses enclosing the exception declaration as
follows −
try {
// protected code
} catch(...) {
// code to handle any exception
}
1 std::exception
2 std::bad_alloc
3 std::bad_cast
4 std::bad_exception
5 std::bad_typeid
6 std::logic_error
7 std::domain_error
8 std::invalid_argument
9 std::length_error
10 std::out_of_range
11 std::runtime_error
12 std::overflow_error
214
13 std::range_error
14 std::underflow_error
Notes:-Module5
216
217
218
219