Вы находитесь на странице: 1из 21

1

Inline function:
Program:
It works like macro.Function
call replaced by function #include <iostream.h>
defintion. int max(int a, int b){
 It is best to use inline return a>b ? a : b;
only very small functions }
 Inline function should int max(int a, int b,int c){
be defined before it is if(a>b&&a>c)return a;
called. if(b>c&&b>a)return b;
if(c>a&&c>b)return c;
Program: }

#include <iostream.h>
inline int max(int a, int b) float max(float a, float b){
{ return a>b ? a : b;
return a>b ? a : b; }
}
int main() int main()
{ {
cout << max(10, 20); cout << max(10, 20);
cout << " " << max(99, 88); cout << max(10, 20,30);
return 0; cout << max(3.5f,4.5f);
} return 0;
}
Note:
• Inline function may not Static data member and
work if it contains any function
loop Static Data Members:
(s),switch,goto,static
varibles. • When you precede
• Inline function cant be a member
recurive. variable's
declaration with
• member function defined
static, you are
inside the class are
telling the
inline
compiler that
only one copy of
Function overloading:
that variable
will exist and
Functions having same
that all objects
name differ by number and
of the class
type of arguments is called
will share that
function overloading.
variable.
Compiler ignores the • Unlike regular
return type of the function. data members,
individual
2

copies of a class shared {


static member static int a;
variable are not int b;
made for each public:
object. void set(int i, int j) {a=i;
• No matter how b=j;}
many objects of void show();
a class are } ;
created, only int shared::a; // define a
one copy of a void shared::show()
static data {
member exists. cout << "This is static a: "
Thus, all << a;
objects of that cout << "\nThis is non-static
class use that b: " << b;
same variable. cout << "\n";
• All static }
variables are int main()
initialized to {
zero before the shared x, y;
first object is x.set(1, 1); // set a to 1
created. x.show();
y.set(2, 2); // change a to 2
When you declare a y.show();
static data member within a x.show(); /* Here, a has been
class, you are not defining changed for both x and y
it. (That is, you are not because a is shared by both
allocating storage for it.) objects. */
Instead, you must provide a return 0;
global definition for it }
elsewhere, outside the class. This program displays the
This is done by re declaring following output when run.
the static variable using the
scope resolution operator to This is static a: 1
identify the class to which This is non-static b: 1
it belongs. This causes This is static a: 2
storage for the variable to This is non-static b: 2
be allocated. (Remember, a This is static a: 2
class declaration is simply a This is non-static b: 1
logical construct that does
not have physical reality.)
Notice that the integer a is
To understand the usage and declared both inside shared
effect of a static data and outside of it. As
member, consider this program: mentioned earlier, this is
necessary because the
#include <iostream.h> declaration of a inside
3

shared does not allocate the name of the class of


storage. which it is a member.

A static member variable One use of a static member


exists before any object of variable is to provide access
its class is created. control to some shared
For example, in the following resource used by all objects
short program, a is both of a class. For example, you
public and static. Thus it might create several objects,
may be directly accessed in each of which needs to write
main(). Further, since a to a specific disk file.
exists before an object of Clearly, however, only one
shared is created, a can be object can be allowed to
given a value at any time. As write to the file at a time.
this program illustrates, the In this case, you will want
value of a is unchanged by to declare a static variable
the creation of object x. For that indicates when the file
this reason, both output is in use and when it is
statements display the same free. Each object then
value: 99. interrogates this variable
before writing to the file.
#include <iostream.h>
class shared { By using static member
public: variables, you should be able
static int a; to virtually eliminate any
} ; need for global variables.
int shared::a; // define a The trouble with global
void main(){ variables relative to OOP is
// initialize a before that they almost always
creating any objects violate the principle of
shared::a = 99; encapsulation.
cout << "This is initial
value of a: " << shared::a; Static Member Functions:
cout << "\n";
shared x; Member functions may
cout << "This is x.a: " << also be declared as static.
x.a; There are several
} restrictions placed on static
member functions.
Notice how ‘a’ is referred to  They may only directly
through the use of the class refer to other static
name and the scope resolution members of the class.
operator. In general, to (Of course, global
refer to a static member functions and data may
independently of an object, be accessed by static
you must qualify it by using member functions.)
4

 A static member function int getMonth()


does not have a ‘this’ const; // A read-only
pointer. function
 A static member function
may not be ‘virtual’. void setMonth( int mn );
 They cannot be declared // A write function; can't be
as const or volatile. const

Constant object and constant private:


member function:
int month;
The const keyword
specifies that a variable's };
value is constant and tells
the compiler to prevent the int Date::getMonth() const
programmer from modifying it.
{
Declaring a member return month;
function with the const
keyword specifies that the // Doesn't modify anything
function is a "read-only"
function that does not modify }
the object for which it is
called. void Date::setMonth( int mn )

To declare a constant { month = mn;


member function, place the
const keyword after the // Modifies data member
closing parenthesis of the
argument list. The const }
keyword is required in both
void main()
the declaration and the
definition. A constant member {
function cannot modify any
data members or call any Date MyDate( 7, 4, 1998 );
member functions that aren't
constant const Date BirthDate( 1,
18, 1953 );
Ex:
MyDate.setMonth( 4 ); /
class Date{ / Okay
public: BirthDate.getMonth(); /
Date(int mn,int dy, int yr ); / Okay
5

BirthDate.setMonth( 4 ); / Ex;
/ Error class sample
{
} private:
int a;
public:
this pointer: void set()
{
The key word "this" is a a=123;
local variable available in //or
the body of any nonstatic this->a=123;
member function. }
int get()
this is represent an object {
that invokes a member return *this;
function. }
this is a pointer that points
to the object for which this }
function was called.
this is to return the object Reference varibles and
it point to. Reference parameteters:

"this" is passed as a A reference is essentially an


hidden argument in all calls implicit pointer.
to non-static member A reference can be used: as a
functions. function parameter, as a
function return value, or as
a stand-alone reference.

The keyword "this" does By default, C++ uses call-


not need to be declared and by-value, but it provides two
is rarely referred to ways to achieve call-by-
explicitly in a function reference Parameter passing.
definition. First, you can explicitly
pass a pointer to the
However, it is used argument. Second, you can use
implicitly within the a reference parameter
function for member
references. When you create an
independent reference, all
For example, if x.func(y) is you are creating is another
called, where y is a member name for an object variable.
of X, the keyword All independent references
"this" is set to &x must be initialized when they
and y is set to this->y, are created.
which is equivalent to x.y.
6

A base class reference can be • They should be declared


used to refer to an object of in the public section
a derived class. • They are invoked
automaticlly when the
Restrictions to References objects are created.
• You cannot reference • They do no have return
another reference (you types,not even void
cannot obtain the
• They cant be
address of a reference.)
inherited ,through a
• You cannot create arrays derived class can call
of references. the base class
• You cannot create a constrcuor.
pointer to a reference. • Like other c++
• You cannot reference a function ,they can have
bit-field. default arguments.
• A reference variable • Construcor cannot be
must be initialized when virtual.
it is declared unless it • We cannot refer to their
is a member of a class, addresses.
a function parameter, or
• An object with a
a return value.
constructor (or
• Null references are destructor) cantnot be
prohibited used as a member of a
function.
• They make implicit class
Note:
to the opearators new
and delete when memory
int& p; // & associated with
allocation I s required.
type
int &p; // & associated with
Types of Constructor :
variable
1.No argument (default)
Constructor
Constructor :
2.Argument(parameterized)
Constructor
A constructor is a memeber
3.Copy Constructor
function having same name of
the class name used to
Destructor:
initlize the member of a
class and it is called
A destructor is a memeber
automtically when object
function having same name of
created.
the class name used to
destroy the object that have
Characterstics of Constructor
been created by a constructor
:
.
7

Characterstics of Destructor:
2.binary opearator overloaing
• A destructor never any ex:
arguments.so we cant complex complex ::
overload destructors. opearator+(complex c)
• They do no have return {
types,not even void complex temp;
temp.x=x+c.x;
• A destructor will be
temp.y=y+c.y;
invoked implictly by the
}
complier upon exit from
the program to claen up
storage that is no
longer accessible.
Rules for overloading
• Destructor can be
operators
virtual but Constructor
cant be virtual.
1. Only existing opearators
can be overloaded.New
opearators can not be created
2.the overload opearator must
have at least on operand tha
is of user defined type
3.we can not change the basic
Operator Overloading
meaning of an operator i.e we
can not use + for subtraction
4.overload operators follow
C++ permits to perfom
the syntax rules of the
opeartions on two varibles of
orginal opearators.they
user defined types with same
cannot be overriden.
syntax that is applied ton
5.sizeof,.(membership
the basic types.
opearator),. *(pointer to
member opearator) ,:: (scope
unary opearator(++,--,-) is
resolution operator),?:
act on one operand
(conditional operator) can’t
(ex a++,a--..)
be overloaded.
6. =(assignment operator), ()
binary opearator(+,-,&..) is
(function call operator),[]
act on more than one operand.
(subscripting operator),->
(ex a+b,a&b..)
(class member access
operator) can’t be overloaded
types of opearator overloading
using friend functions.
1.unary opearator overloaing
7.Unary operators,overloaded
by means of a member function
ex:void space::opearator –()
take no explicit arguments
{
and return no explicit
x=-x;
values,but, those overloaded
}
by means of a friend
8

function, take one referenece and the new one is called the
argument(the object of the derived class or sub class.
relvant class).
8.Binary operators overloaded Inheritance supports the
through a member function concept of classification.
function take one explicit (Provides relationships among
argument and those which are the classes)
overloaded through a friend
function take 2 explicit A derived class has
arguments. direct access to both its own
9.When using binary operators members and the public
overloaded through a member members of the base class.
function, the left hand
operand must be an object of Inheritance also
the relvant class. provides support for run-time
10.Binary arithmetic operator polymorphism through the
such as +,-,*,and / must mechanism of virtual function.
explicitly return a
value.They must not attempt Necessity of Inheritance:
to change their own arguments.
 Software reusability
 Consistence of interface
 Software components
 Rapid prototype

Inheritance Types of Inheritance:

In short we called 1. Single


reuseability. (simple)Inheritance:
Contains one
Inheritance is the derived class and base
process by which one object class
can acquire the properties of
another object. 2. Multilevel inheritance:
one derived class act as
The mechanism of base for another base
deriving a new class from an class.
old one is called inheritance
(or derivation). 3. Multiple Inheritance:
It is a technique of One class can be derived
organizing information in a from more than one class
hierarchical form. (contains one derived
It is like a child and more than one base)
inheriting the features of 4. Hierarchical
its parents. The old class is Inheritance: Deriving
referred to as the base class more than one class from
9

one class (contains one these multiple paths can be


base and more than one avoided by making the common
derived). base class as virtual base
5.Hybrid Inheritance: class while declaring the
Derivation of class direct or intermediate base
involving more htan one classes.
form of inheritance is
known as hybrid
inheritance. When a class is made a
virtual base class, C++ takes
necessary care to see that
Virtual Base Class: only one copy of that class
is inherited, regardless of
Ambiguity can be introduced how many inheritance paths
into a C++ program when exist betwwen the virtual
multiple base classes are base class and a derived
inherited. class.

Fig:
Function overriding:

when function having name


,type and signature(parameter
list) present in both base
and derived classes then
derived class
function overwrirites base
class function is called
function overriding.

Function overriding stop


Inheritance by the child as inheritance.
shown in above fig. might
pose some problems. All the A virtual function is a
public and protected members member function that is
of grandparent are inherited declared within a base class
into child twice, first via and redefined by a derived
parent1 and again via class
parent2. This means child
would have duplicate sets of
the members inheritedd from Program:
grandparent. This introduces
ambiguity and should be #include<iostream.h>
avoided. #include<conio.h>

The duplication of class base


inherited members due to {
10

public: Virtual Functions Are


virtual void display() Hierarchical.
{
cout<<"i am in base...\n"; A pure virtual function is a
} virtual function that has no
}; definition within the base
class.

class derived:public base To declare a pure virtual


{ function, use this general
public: form:
void display()
{ virtual type func-
cout<<"i am in derived...\n"; name(parameter-list) = 0;
}
}; Abstract Class is a class
that contains at least one
pure virtual function .
void main() we cannot create objects of
{ an abstract class.
we can create pointers and
clrscr(); references to an abstract
base *p; class.
base b;
derived d; Early binding(compiletie
polymorphism) refers to
p=&b; events that occur at compile
p->display(); time
normal function calls
p=&d; (including standard library
p->display(); functions), overloaded
function calls, and
getch(); overloaded operators are used
} to achieve early binding.
main advantage to early
Output: binding is efficiency

i am in base... Late binding(runtime


i am in derived... polymorphism) refers to
function calls that are not
resolved until run time.
Calling a Virtual Function Virtual functions are used to
Through a Base Class Reference achieve late binding.
The Virtual Attribute Is The main advantage to late
Inherited. binding is flexibility.
11

virtual destructor: both the classes in order to


ensure that all the space on
Destructor member function is the heap is released
invoked to free the memory
storage by C++ compiler
automatically. Program to demonstrate
virtual destructor
But the destructor member
function of the derived class
is invoked to free the memory #include<iostream.h>
storage which was allocated #include<conio.h>
by the constructor member class base {
function. public :
base(){
It is because the destructor cout<<"base class
member functions are non constructor\n";
virtual and the message will }
not reach the destructor
member function under late virtual~base() {
binding. cout<<"base class
destructor\n";
So it is better to have }
a destructor member function };
as virtual and virtual
destructors are essential in class derived:public base {
a program to free the memory public :
space effectively under late derived(){
binding. cout<<"derived class
constructor\n";
}
Note that whenever instances
(objects) are created at ~derived(){
runtime on the heap through cout<<"derived class
new operator, constructor destructor\n";
member functions are }
automatically. };

When the delete operator is void main()


used the destructors are {
automatically called to clrscr();
release the space occupied by base *p=new derived;
instance itself. delete p;
getch();
As a derived instance always }
contains a base class
instance, it is necessary to Output:
invoke the destructors of
12

base class constructor /*function template*/


derived class constructor program:
derived class destructor
base class destructor #include <iostream.h>
template <class T>
T max(T a, T b){
return a>b ? a : b;
Template: };

Construct a family of related int main()


functions and classes. {
cout << max(10, 20);
A generic function (function cout << max(‘a’,’b’);
template) defines a general cout << max(3.5f,4.5f);
set of operations that will return 0;
be applied to various types }
of data.
Generic Classes
A single general procedure (class template):
can be applied to a wide
range of data. When you create a generic
class, it defines all the
By creating a generic algorithms used by that
function, you can define the class, however, the actual
nature of the algorithm, type of the data being
independent of any data manipulated will be specified
as a parameter when objects
When you create a generic of that class are created.
function you are creating a
function that can Generic classes are useful
automatically overload itself. when a class uses logic that
can be generalized.
The general form of a
template function definition For example, the same
is shown here: algorithms that maintain a
queue of integers will also
template <class Ttype> ret- work for a queue of
type func-name(parameter list) characters.
{
// body of function Streams
}
Here, Ttype is a placeholder  A stream is sequence of
name for a data type used by bytes and serves as
the function. This name may source or destination
be used within the function for an I/O data.
definition.
13

 A program extracts the  It defines the input


bytes from an input functions such as
stream and inserts bytes get(),getline()and
into an output stream. read().

 The C++ I/O contains a  It contains overloaded


hierarchy of classes extraction operator >>
they are used to
defining various ostream(output stream):
streams. These classes  It is a derived class of
are called stream ios. hence it inherits
classes. the properties of ios.

 The following figure  It defined the output


illustrates the functions such as put()
hierarchy of stream and write().
classes used for input
and output operations.  It contains overload
These classes are insertion operator <<.
declared in a header
file iostream.h iostream(input/output
stream):
ios:
 It is a derived from
 It provides operations multiple base classes
common to both input and istream and ostream
output. which are inherited from the
base class ios.
 The classes derived from
ios are istream,  It defines all input and
ostream, iostream. Also output functions.
contains a pointer to a
buffer object(streambuf The three classes
object) istream-with assign,
iostream-with assign and
 Declare constants and ostream-with assign add
functions for handling assignment operators to these
input –output (formatted classes.
and unformatted)
operations. Streambuf:
 It is a base class for
istream(input stream) :It is the buffer class used in
a derived class of ios and files (act as a
hence inherits the properties base for filebuf class).
of ios.
14

 It provides an interface <iostream.h> in a


to physical devices C++ program. This
through buffers. is a C++ standard
header file
C++ I/O Operators: supplied by C++
complier.
 C++ provides a new way
to perform input and  cin represents to
output operators, in C+ input stream
+. The I/O operation is connected to the
performed by using I/O standard input
operators. Instead of device.
I/O functions the Input
operator is “>>” and the  cout represents to
output operator “<<”. output stream
connected to the
 The general form input standard output
operator is device.
cin>>variable;
Ex:  By default, most
int a; systems get their
cin>>a; standard input from
the keyboard,
The general form output therefore cin is
operator is cout<<exp; generally expected
Here is the expression is a to get information
valid C++ expression. from the user,
Ex: although there are
cout<<”welcome to c++”; many cases where
this can be
 This statement redirected to some
causes the string other source.
to be displayed on
the screen. cout is  By default, most
predefined stream systems have their
automatically standard output set
linked to the to the console,
console when a C++ where text messages
program begins to are shown, although
execute. this can generally
be redirected.
 In order to use
these C++ I/O  cerr:Standard
operations we output stream for
should include the errors
header file
15

Here, p_var is a pointer


variable that receives a
pointer to memory that is
large enough
 cerr is an object to hold an item of type type.
of class ostream
that represents the void main()
standard error {
stream. It is int *p;
associated with the p = new int;
cstdio stream // allocate space for an int
stderr. *p = 100;
cout << "At " << p << " ";
cout << "is the value " << *p
By default, most systems << "\n";
have their standard error delete p;
output set to the console, }
where text messages are
shown, although this can
generally be redirected. This program assigns to p
an address in the heap that
C++'s Dynamic Allocation is large enough to hold an
Operators: integer. It then assigns that
memory the value 100 and
C++ provides two dynamic displays the contents of the
allocation operators: new and memory on the screen.
delete. These operators are Finally, it frees the
used to allocate and free dynamically allocated memory.
memory at run time. Remember,if your compiler
C++ also supports dynamic implements new such that it
memory allocation functions, returns null on failure, you
called malloc() and free(). must change the preceding
. program appropriately.
The new operator allocates
memory and returns a pointer The delete operator must be
to the start of it. used only with a valid
The delete operator frees pointer previously allocated
memory previously allocated by using new.
using new. Using any other type of
pointer with delete is
The general forms of new and undefined and will almost
delete are shown here: Certainly cause serious
problems, such as a system
p_var = new type; crash.
delete p_var;
16

Although new and delete initialization is included:


perform functions similar to
malloc() and free(), they p_var = new
have several advantages. var_type(initializer);

First, new automatically Of course, the type of the


allocates enough memory to initializer must be
hold an object of the compatible with the type of
specified type. You do not data for which
need to use the sizeof memory is being allocated.
operator. Because the size is
computed automatically, it This program gives the
eliminates any possibility allocated integer an initial
for error in this regard. value of 87:

Second, new automatically void main()


returns a pointer of the {
specified type. You don't int *p;
need to use an p = new int (87);
explicit type cast as you do //initialize to 87
when allocating memory by cout << "At " << p << " ";
using malloc(). cout << "is the value " << *p
<< "\n";
Finally, both new and delete delete p;
can be overloaded, allowing }
you to create customized
allocation systems.

Although there is no formal Allocating Arrays:


rule that states this, it is
best not to mix new and You can allocate arrays using
delete with malloc() and new by using this general
free() in the same program. form:

There is no guarantee that p_var =new array_type [size];


they are mutually compatible.
Here, size specifies the
number of elements in the
array.
Initializing Allocated Memory To free an array, use this
form of delete:
You can initialize allocated
memory to some known value by delete [ ] p_var;
putting a initializer after
the type name in the new Here, the [ ] informs delete
statement. Here is the that an array is being
general form of new when an released.
17

For example, the next program function (if it has one) is


allocates a 10-element called. When
integer array. the object is freed, its
destructor function is
void main() executed.
{
int *p, i;
try {
p = new int [10];
// allocate 10 integer array EXCEPTION HANDLING
for(i=0; i<10; i++ )
p[i] = i;  The C++ language
for(i=0; i<10; i++) provides built-in
cout << p[i] << " "; support for raising and
delete [] p;
handling exceptions
// release the array
}  try ,throw ,catch are
Notice the delete statement.
As just mentioned, when an keywords implement
array allocated by new is exception handling
released, delete must be made
aware that an array is being
freed by using the [ ].
(As you will see in the next  These exceptions are
section, this is especially handled by code which is
important when you are outside the normal flow
allocating of control.
arrays of objects.)
One restriction applies to  If an exception (i.e.,
allocating arrays: They may an error) occurs within
not be given initial values. the try block, it is
That is, you may not specify Thrown (using throw).
an initializer when The exception is caught,
allocating arrays. using catch, and
processed
Allocating Objects:

You can allocate objects


dynamically by using new.
When you do this, an object is
created and a pointer is The general form of try and
returned to it. catch are shown here.
The dynamically created
object acts just like any try {
other object. When it is // try block
created, its constructor }
catch (type1 arg) {
18

// catch block  Any type of data may be


} caught, including
catch (type2 arg) { classes that you
// catch block create.
}
catch (type3 arg) {  If no exception is
// catch block thrown (that is, no
} error occurs within the
.. try block), then no
. catch statement is
catch (typeN arg) { executed.
// catch block
}  throw generates the
exception specified by
The general form of the throw
exception.
statement is shown here:
 If this exception is to
throw exception;
be caught, then throw
 When an exception is must be executed either
thrown, it is caught by from within a try block
its corresponding catch itself, or from any
statement,which function called from
processes the exception. within the try block
(directly or
indirectly).
 There can be more than
one catch statement
associated with a try.  If you throw an
exception for which
there is no applicable
 Which catch statement is
catch statement, an
used is determined by
abnormal program
the type of the
termination may occur.
exception.

That is, if the  The terminate() function


data type specified by a is called whenever the
catch matches that of the exception handling
exception, subsystem fails to find
then that catch a matching catch
statement is executed (and statement for an
all others are bypassed). exception.

 When an exception is  It is also called if


caught, arg will receive your program attempts to
its value. rethrow an exception
when no exception was
originally thrown.
19

catch (int i) { // catch an


 Throwing an unhandled error
exception causes the cout << "Caught an exception
standard library -- value is: ";
function terminate() to cout << i << "\n";
be invoked. }
cout << "End";
return 0;
}
 By default, terminate()
calls abort() to stop output:
your program
Start
 An exception can be Inside try block
thrown from outside the Caught an exception -- value
try block as long as it is: 100
is thrown by a End
function that is called
from within try block
/* 2.Throwing an exception
from a function outside the
 A try block can be try block.*/
localized to a function. #include <iostream>

void Xtest(int test)


{
cout << "Inside Xtest, test
 You can have more than
is: " << test << "\n";
one catch associated
if(test) throw test;
with a try. However,
}
each catch must catch a
different type of
int main()
exception.
{
cout << "Start\n";
/*1.A simple exception
try { // start a try block
handling example.*/
cout << "Inside try block\n";
Xtest(0);
#include <iostream>
Xtest(1);
int main()
Xtest(2);
{
}
cout << "Start\n";
catch (int i) { // catch an
try { // start a try block
error
cout << "Inside try block\n";
cout << "Caught an exception
throw 100; // throw an error
-- value is: ";
cout << "This will not
cout << i << "\n";
execute";
}
}
cout << "End";
20

return 0;
}
output:
Start
Inside try block
Inside Xtest, test is: 0
Inside Xtest, test is: 1
Caught an exception -- value
is: 1
End

/*4.Using Multiple catch


/*3.A try block can be Statements*/
localized to a function*/ #include <iostream>
// Different types of
#include <iostream> exceptions can be caught.
// Localize a try/catch to a void Xhandler(int test)
function. {
void Xhandler(int test) try{
{ if(test) throw test;
try{ else throw "Value is zero";
if(test) throw test; }
} catch(int i) {
catch(int i) { cout << "Caught Exception #:
cout << "Caught Exception #: " << i << '\n';
" << i << '\n'; }
} catch(const char *str) {
} cout << "Caught a string: ";
int main() cout << str << '\n';
{ }
cout << "Start\n"; }
Xhandler(1); int main()
Xhandler(2); {
Xhandler(0); cout << "Start\n";
Xhandler(3); Xhandler(1);
cout << "End"; Xhandler(2);
return 0; Xhandler(0);
} Xhandler(3);
cout << "End";
output: return 0;
}
Start
Caught Exception #: 1 output:
Caught Exception #: 2
Caught Exception #: 3 Start
End Caught Exception #: 1
Caught Exception #: 2
21

Caught a string: Value is zero type cast operator:


Caught Exception #: 3
End (type-name) expression//C
notation
/*5. This example uses
catch(...) as a default.*/ ex :avg=sum/(float)n;

#include <iostream> type-name( expression)//C++


void Xhandler(int test) notation
{
try{ ex : avg=sum/float(n);
if(test==0) throw test;
//throw int friend function:
if(test==1) throw 'a';
// throw char It is a non member function
if(test==2) throw 123.23; // can access private data.
throw double
} A function or entire class
catch(int i) { may be declared to be a
// catch an int exception friend of another class
cout << "Caught an integer\n";
} To declare a function as a
friend of a class precede
catch(...) { the function prototype in
// catch all other exceptions class definition with keyword
cout << "Caught One!\n"; friend
}
} It doesn’t matter where you
int main() declaring friend function(in
{ private or public section)
cout << "Start\n";
Xhandler(0); It canot be called by using
Xhandler(1); the object of the class in
Xhandler(2); which it is declared
cout << "End";
return 0; It can be called
} (invoked)like a normal
function without the help of
Output: any object.

Start
Caught an integer
Caught One!
Caught One!
End