Object Oriented Programming in C++

Download as pdf or txt
Download as pdf or txt
You are on page 1of 130

Introduction

Object-Oriented Programming in C++ (4th Edition)


4th Edition

By Robert Lafore
What Is OOP ? - Part 1
What IS Object Oriented Programming ?

 Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects"

 A programming paradigm : is a style of programming, a way of thinking about software construction.

 A programming paradigm does not refer to a specific language but rather to a way to build a program

or a methodology to apply.

 Some languages make it easy to write in some paradigms but not others.

 Some Programming Languages allow the programmer to apply more than one Paradigm.
Example of Programming Paradigms
Example of Previous Programming Paradigm

Procedural Programming

Procedural programming (PP), also known as inline programming takes a top-down approach. It is about
writing a list of instructions to tell the computer what to do step by step. It relies on procedures or routines.
Procedural Programming Example : Program to Calculate Average of Array Items

Code To declare and initialize Array


Get Input ( )

Call To function To Accept Array Data

Calc Average ( ) Calc Sum ( )


Call To function To Calculate Average

Calc Sum ( )
 Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects"

Object : is a thing (Tangible – Intangible)


Objects in College Management Program

College Environment

Student Course Teacher

Section Hall Office


Objects in Super market Program

Super Market Environment

Product Customer Cashier

Loyalty
Cart Bager
Card
What Is OOP ? - Part 2
Objects in College Management Program

College Environment

Student Course Teacher

Section Hall Office


Object Is comprised Of ?

Object
Data

Operations ( )
Object Is comprised Of ?
Product
Data
1- Product _name ,
2- Product _code
3- Price
4- Producer
5-Discount

Operations ( )
1- Modify Price ()
2- Set Discount ()
3- Get Product Name ()
4- Get Product Price ()
Object Is comprised Of ?
Student
Data
1- Student_name ,
2- University_Id
3- Birth_Date
4- Address
5-GPA
6- Study_Level

Operations ( )
1- Modify GPA()
2- Change Study level ()
3- Get Student Name ()
4- Get Student Address ()
Object Is comprised Of ?
Car
Data
1- Factory,
2- Model
3- Fuel_Capacity
4- No_of_doors
5-Color
6- Shape

Operations ( )
1- Set Factory Name()
2- Change Color ()
3- Get Car Info ()
4- ………..
Classes & Objects
What is Class ? Why we need It ?
Student 1 Student 2 Student 3
Data: Data: Data:
1- Student_name , 1- Student_name , 1- Student_name ,
2- University_Id 2- University_Id 2- University_Id
3- Birth_Date 3- Birth_Date 5-GPA
4- Address 4- Address 6- Study_Level
5-GPA 6- Study_Level
6- Study_Level
Operations ( )
Operations ( )
Operations ( ) 1- Modify GPA()
1- Modify GPA()
2- Change Study level ()
1- Modify GPA() 2- Change Study level () 3- Get Student Name ()
2- Change Study level () 4- Get Student Address () 4- Get Student Address ()
3- Get Student Name ()
4- Get Student Address ()
What is Class ? Why we need It ?
Student 1 Student 3
Data: Data:
1- Student_name 1- Student_name
2- University_Id 2- University_Id
3- Birth_Date 3- Birth_Date
4- Address 4- Address
Class Student 5-GPA 5-GPA
6- Study_Level 6- Study_Level

Operations ( ) Operations ( )
Data: 1- Modify GPA() 1- Modify GPA()
1- Student_name , 2- Change Study level () 2- Change Study level ()
3- Get Student Name () 3- Get Student Name ()
2- University_Id 4- Get Student Address () 4- Get Student Address ()
3- Birth_Date
4- Address
5-GPA Student 2
6- Study_Level Data:
1- Student_name
Operations ( ) 2- University_Id
3- Birth_Date
1- Modify GPA() 4- Address
2- Change Study level () 5-GPA
6- Study_Level
3- Get Student Name ()
4- Get Student Address () Operations ( )
1- Modify GPA()
2- Change Study level ()
3- Get Student Name ()
4- Get Student Address ()
What is Class ? Why we need It ?
Student 1 Student 3
Data: Data:
1- Student_name
1- Student_name
2- University_Id
Class Student 3- Birth_Date
2- University_Id
3- Birth_Date
4- Address
4- Address
5-GPA
5-GPA
6- Study_Level
Data: 7- Email
6- Study_Level
7- Email
1- Student_name , Operations ( )
2- University_Id Operations ( )
1- Modify GPA()
1- Modify GPA()
3- Birth_Date 2- Change Study level ()
2- Change Study level ()
3- Get Student Name ()
4- Address 4- Get Student Address ()
3- Get Student Name ()
5-GPA 4- Get Student Address ()
5- Print Student Info ()
5- Print Student Info ()
6- Study_Level
7- Email Student 2
Data:
Operations ( ) 1- Student_name
2- University_Id
1- Modify GPA() 3- Birth_Date
2- Change Study level () 4- Address
3- Get Student Name () 5-GPA
6- Study_Level
4- Get Student Address ()
5- Print Student Info () 7- Email
Operations ( )
1- Modify GPA()
2- Change Study level ()
3- Get Student Name ()
4- Get Student Address ()
5- Print Student Info ()
What is Class ? Why we need It ?

Student
Class Student
1
Data:
1- Student_name , = Ahmed

2- University_Id = 1050

5-GPA =3.75

6- Study_Level =5

Operations ( )
1- Modify GPA()
2- Change Study level ()
3- Get Student Name ()
4- Get Student GPA ()
Objects and Classes
• Classes: Where Objects Come From
– A class is code that describes a particular type of object. It specifies the
data that an object can hold (the object's fields), and the actions that an
object can perform (the object's methods).

– You can think of a class as a code "blueprint" that can be used to create
a particular type of object.
Objects and Classes
• When a program is running, it can use the class to create, in
memory, as many objects of a specific type as needed.

• Each object that is created from a class is called an instance of


the class.
Classes & Objects
 A class is defined (declared) and used as follows:

class MyClass void main()


{ {
[private:] // define objects of type
variables (data members) // class_name
… MyClass MyObject1;
functions (methods) MyClass MyObject2;

// call a member function
public:
MyObject1.func1(…);
variables (data members)
// assign value to data members

MyObject1.Index = 12;
functions (methods)
}

};
Classes & Objects
 The class CPoint represents a point in the 2D space…
class CPoint #include <iostream.h>
{
int x , y; void main()
{
public: CPoint p1, p2;
void Init()
{ p1.Init();
x = 0; p2.Set(4,6);
y = 0;
} p1.Print();
p2.Print();
void Set (int ax, int ay) }
{
x = ax;
y = ay;
}
void Print()
{
cout<<"x = "<<m_x<<", y = "<<m_y<<endl;
}
};
Create Your First Class
Part 1
What is Class ? Why we need It ?
Student 1 Student 3
Data: Data:
1- Student_name
1- Student_name
2- University_Id
Class Student 3- Birth_Date
2- University_Id
3- Birth_Date
4- Address
4- Address
5-GPA
5-GPA
6- Study_Level
Data: 7- Email
6- Study_Level
7- Email
1- Student_name , Operations ( )
2- University_Id Operations ( )
1- Modify GPA()
1- Modify GPA()
3- Birth_Date 2- Change Study level ()
2- Change Study level ()
3- Get Student Name ()
4- Address 4- Get Student Address ()
3- Get Student Name ()
5-GPA 4- Get Student Address ()
5- Print Student Info ()
5- Print Student Info ()
6- Study_Level
7- Email Student 2
Data:
Operations ( ) 1- Student_name
2- University_Id
1- Modify GPA() 3- Birth_Date
2- Change Study level () 4- Address
3- Get Student Name () 5-GPA
6- Study_Level
4- Get Student Address ()
5- Print Student Info () 7- Email
Operations ( )
1- Modify GPA()
2- Change Study level ()
3- Get Student Name ()
4- Get Student Address ()
5- Print Student Info ()
What is Class ? Why we need It ?

Student
Class Student
1
Data:
1- Student_name , = Ahmed

2- University_Id = 1050

5-GPA =3.75

6- Study_Level =5

Operations ( )
1- Modify GPA()
2- Change Study level ()
3- Get Student Name ()
4- Get Student GPA ()
Writing a Class, Step by Step
• A Rectangle object will have the following fields:

Rectangle

length
width

setLength()
setWidth()
getLength()
getWidth()
getArea()
Writing the Code Rectangle

public class Rectangle length


width
{
private: setLength()
setWidth()
float length; getLength()
getWidth()
float width; getArea()
}
Access Modifiers
• An access modifier is a C++ keyword that indicates how a field or method can
be accessed.
• public
– When the public access modifier is applied to a class member, the member can be
accessed by code inside the class or outside. Data Hiding
• private
– When the private access modifier is applied to a class member, the member cannot be
accessed by code outside the class. The member can be accessed only by methods that
are members of the same class.
Data Hiding
• An object hides its internal, private fields from code that is outside the class
that the object is an instance of.
• Only the class's methods may directly access and change the object’s internal
data.
• Code outside the class must use the class's public methods to operate on an
object's private fields.
• Data hiding is important because classes are typically used as components in
large software systems, involving a team of programmers.
• Data hiding helps enforce the integrity of an object's internal data.
Return Rectangle
Type - width : float
Access Method
- length : float
specifier Name
+ setWidth(w : float) : void
+ setLength(len : float): void
+ getWidth() : float
Public: + getLength() : float
+ getArea() : float
void setLength(float len)

Parameter variable declaration


public class Rectangle
{
private:
float length;
float width;

Public:
void setLength(float len)
{
If (len >=0)
length = len;
Else cout<<“Error , Please Enter positive value”;
}
}
Create Your First Class
Part 2
class Rectangle Rectangle
{ - width : float
private: - length : float
float length; + setWidth(w : float) : void
float width; + setLength(len : float): void
+ getWidth() : float
+ getLength() : float
Public: + getArea() : float
void setLength(float len)
{
If (len >=0)
length = len;
Else cout <<“Error , Please Enter positive value”;
}
}
Creating a Rectangle object
Rectangle box; Int X; String name;
A Rectangle object
The box
variable holds length: 0.0
the address of address
the Rectangle width: 0.0
object.
Create Your First Class
Part 3
More Examples

Setter , Mutator

Getter, Accessor
Separating Class Code into 2 files.
The class code can be separated into 2 files:

Header File - .h

• Contains the declaration of all the class members.

• Only attributes declaration and methods prototypes

Implementation File - .cpp

• Contains the implementation of the class methods.

Client Code

• client code, is the one that includes the main function. This file should be stored by the name main.cpp
public class Rectangle
{ float getArea()
private: {
return length * width;
float width; }
float length; }

public :
void setWidth(float w)
{ width = w;
}
void setLength(float len)
{ length = len;
}
float getWidth()
{ return width;
}
float getLength()
{ return length;
}
Instance Fields and Methods

• Instance fields and instance methods require an object to be


created in order to be used.
• For example, every room can have different dimensions.

Rectangle kitchen = new Rectangle();


Rectangle bedroom = new Rectangle();
Rectangle den = new Rectangle();
States of Three Different Rectangle Objects

The kitchen variable length: 10.0


holds the address of a address
Rectangle Object. width: 14.0

The bedroom variable length: 15.0


holds the address of a address
Rectangle Object. width: 12.0

The den variable


length: 20.0
holds the address of a address
Rectangle Object.
width: 30.0
Constructor & Destructor
Part 1
Constructors
• Classes can have special methods called constructors.

• A constructor is a method that is automatically called when an object is


created. Recatngle r1; -------- Car c1;

• Constructors typically initialize object attributes and perform other object


initialization tasks.

• Constructors are used to perform operations at the time an object is created.


Constructors
• Constructors have a few special properties that set them apart from
normal methods.
– Constructors have the same name as the class.
– Constructors have no return type (not even void).
– Constructors may not return any values.
– Constructors are typically public.

public :
Rectangle( )
{
length = 0;
width = 0;
}
Constructor & Destructor
Part 2
Constructors – Initialization list
public :
Rectangle( ): length(0), Width (0)
{
Cout <<“The Rectangle Length and width are initialized”;
}

public :
public :
Rectangle(float len, float w)
Rectangle(float len, float ):
{ length(len),width(w)
length = len; {
width = w; }
}
Destructor
• A destructor is a special method that is automatically called when an object
life time is ended.

• Like constructors, destructors do not have a return value.

• The most common use of destructors is to deallocate memory that was


allocated for the object by the constructor

public :
~Rectangle( )
{

}
Method and Constructor
Overloading – Part 1
Overloading Methods and Constructors
• Two or more methods in a class may have the same name as long as
their signatures are different.
• Method signature (No of Args – Types of Args – Order of Args)
• When this occurs, it is called method overloading. This also applies
to constructors.
• Method overloading is important because sometimes you need
several different ways to perform the same operation.
Overloaded Method add
int add(int num1, int num2)
{
int sum = num1 + num2;
return sum;
}

int add(int num1, int num2, int num3)


{
int sum = num1 + num2 + num3 ;
return sum;
}

Float add(float num1, float num2)


{
float sum = num1 + num2;
return sum;
}
Method and Constructor
Overloading – Part 2
Constructor Overloading
Rectangle::Rectangle ( ):length(0),width(0)
{
}
Rectangle::Rectangle(float l , float w):length(l),width(w)
{
}
Rectangle Class Constructor Overload

Rectangle box1();

Rectangle box2(5.0, 10.0);

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Default Copy Constructor
The Default Copy Constructor
- It is another way to initialize an object:
- Used to initialize an object with another object of the same type.
- No need to create a special constructor for this; one is already built into all classes

Class : Distance Object 1 Object 2


- Feet
- Inches Feet = 5 Feet = 5

Inches = 3.5 Inches = 3.5


Distance ( )
~Distance ( )
The Default Copy Constructor
class Distance //English Distance class
{
private: int main()

int feet; {
float inches; Distance d1;

public: Distance dist2 (11, 6.25);


Distance() : feet(0), inches(0.0) Distance dist3 (dist2);
{}
Distance(int ft, float in) : feet(ft), inches(in) Distance dist4 = dist2;
{}
}
The Default Constructor
• When an object is created, its constructor is always called.
• If you do not write a constructor, C++ provides one when the class is
compiled. The constructor that C++ provides is known as the default
constructor.
The Default Constructor
• The default constructor is a constructor with no parameters, used to
initialize an object in a default configuration.
• The only time that Java provides a default constructor is when you do not
write any constructor for a class.
• A default constructor is not provided by Java if a constructor is already
written.
Writing Your Own No-Arg Constructor
• A constructor that does not accept arguments is known as a no-arg
constructor.
• The default constructor (provided by Java) is a no-arg constructor.
• We can write our own no-arg constructor

public Rectangle()
{
length = 1.0;
width = 1.0;
}
Passing Objects to Methods
Passing Objects as Arguments
• Objects can be passed to methods as arguments.

• When an object is passed as an argument, the value of the reference variable is passed.

• The value of the reference variable is an address or reference to the object in memory.

• A copy of the object is not passed, just a pointer to the object.

• When a method receives a reference variable as an argument, it is possible for the method
to modify the contents of the object referenced by the variable.
Class Calculator Main()
{ {
Float add(float num1, float num2) Calculator calc;
{ Float x = 50.0 ;
return num1 + num2; Float Y = 10.0;
}
Calc.add (x , y);
string add(string a, string b)
{ }
return a + " " + b;
}
}

Distance Add_distances (Distance d1 , Distance d2)


{
}

Rectangle Merge (Rectangle r1 , Rectangle r2)


{
}
Class : Distance
d1 d2
- Feet
- Inches
Feet = 5 Result.feet = d1.feet + d2.feet Feet = 3
Distance ( )
Inches = 3.5 Result.inches = d1.inches + d2.inches Inches = 4.25
Distance Add_distance(Distance d2)

~Distance ( )

Feet = 8

Inches = 7.75

Result
Static Class Members
Static Class Members
• Static fields and static methods do not belong to a single instance of a class.
• A static data item is useful when all objects of the same class must share a
common item of information.
• Its lifetime is the entire program. It continues to exist even if there are no
objects of the class.
• To invoke a static method or a static field, use the class name, rather than
the instance name.
class Car int Car::count = 0;
{
int main()
string Maker ; {
Car c1, c2, c3; //create three objects
int model ;
cout << “count is “ << c1.getcount() << endl;
static int count;
cout << “count is “ << c2.getcount() << endl;
public: cout << “count is “ << c3.getcount() << endl;
Car( ) //increments count when object created return 0;
{ count++; } }
int getcount( ) //returns count
{ return count; }
};
Static Fields
instanceCount field
(static)

Object1 Object2 Object3


Static Methods
• Static methods are convenient because they may be called at the class level.
• They are typically used to create utility classes.
• Static methods may not communicate with instance fields, only static fields.
Class Calc
{
Public:

Static int add(int num1 , int num2)


{
return num1 + num2;
}
Static int multiply (int num1 , int num2)
{
return num1 * num2;
}
}
Operator Overloading
Operators in C++
Operator Overloading

Integers String Class Distance


Int I = 5, j = 10, sum = 0; string a="Hello"; Distance d1(5,3);
Sum = I + j; string b = "World"; Distance d2 (4,7);
Cout << Sum << endl ; string sum = a + b; Distance D3 = d1 + d2;
cout << sum;

Output  15 Output  Hello World Error


Operator overloading
• The term operator overloading refers to giving the normal C++ operators, such as +, *, <=,
and +=, additional meanings when they are applied to user-defined data types.

• Operator overloading is one of the most exciting features of object-oriented programming.

• It can transform complex program listings into easy ones.


int a , b, c;

c= a + b ;

Counter c1, c2 , c3;

c3 = c1+ c2;

The operator Keyword is used to overload operators


Overloading Unary Operators
int main()
{
Counter c1, c2;
cout << c1.get_count();
cout << c2.get_count();

//Operator Overloading
++c1; //increment c1
++c2; //increment c2
++c2; //increment c2

cout << c1.get_count();


cout << c2.get_count();
Overloading Unary Operators – PostFix Notation
Overloading Binary Operators
Caller Input
Operator
Object 1 Object 2
+, - , * , /
Distance d1 , d2, d3;
d3= d1 + d2
Caller Input
Operator
d1 d2
+, - , * , /
Counter c1 , c2, c3;
c3= c1 + c2
Caller Input
Operator
c1 c2
+, - , * , /
Overloading Binary Operators

F=5 + F=4 = F= 9

I=7 + I=3 = I=10

D1 D2 Result
Inheritance – Part 1
What is Inheritance?
• Inheritance is probably the most powerful feature of object-oriented
programming, after classes themselves.

• Inheritance is the process of creating new classes, called derived classes, from
existing or base classes

• The derived class inherits all the capabilities of the base class but can add its
own features. And the base class is unchanged by this process.
• Inheritance permits code reusability.

• Reusing existing code saves time and money and increases


a program’s reliability.
class Counter //base class
{ class CountDn : public Counter //derived class
protected: //NOTE: not private {
int count; public:
public: Counter operator -- ()
Counter() : count(0) {
{} return Counter(--count);
Counter(int c) : count(c) }
{} };
int get_count()
{ return count; }
Counter operator ++ ()
{
return Counter(++count);
}
};

int main()
{
CountDn c1; //c1 of class CountDn

++c1; ++c1; ++c1; //increment c1, 3 times

--c1; --c1; //decrement c1, twice


}
Without Inheritance
Inheritance – Part 2
The “is a” Relationship
• The relationship between a Base Class and an derived class is called an “is
a” relationship.
– A post graduate student “is a” Student.
– An Employee “is a” Person.
– Salaried Employee “is a” Employee.
– A car “is a” vehicle.
• A specialized object has:
– all of the characteristics of the general object, plus
– additional characteristics that make it special.
• In object-oriented programming, inheritance is used to create an “is a”
relationship among classes.
Inheritance – Part 3
Order of Constructor Call with Inheritance in C++

• Whether derived class's default constructor is called or


parameterized is called, base class's default constructor is always
called inside them.

• To call base class's parameterized constructor inside derived class's


parameterized constructor, we must mention it explicitly while
declaring derived class's parameterized constructor.
Inheritance – Part 4
Function Overriding
• It is the redefinition of base class function in its derived class
with same signature.
Function Overloading
• It provides multiple definitions of the function by changing
signature i.e changing number of parameters, change datatype of
parameters.
• It can be done in base as well as derived class.
Inheritance – Part 5
Multiple Inheritance in C++
• Multiple inheritance occurs when a class inherits from more than one base class. So the
class can inherit features from multiple base classes in the same time.

• Unlike other object oriented programming languages, C++ allow this important features
to programmers.
Polymorphism – Virtual Functions
What is Polymorphism ?
• Polymorphism is an object-oriented programming concept that
refers to the ability of a variable, function or object to take
on multiple forms.
• with polymorphism, class objects belonging to the same hierarchical tree
(inherited from a common parent class) may have functions with the same
name, but with different behaviors.
Shape
String : Color
Draw ( )
Erase ( )
Get_area ( )

Rectangle Box Circle


int : Length int : SideLength int : radius
int : width Draw ( ) Draw ( )
Draw ( ) Erase ( ) Erase ( )
Erase ( ) Get_area ( ) Get_area ( )
Get_area ( ) Get_circumference ( )
Types of Polymorphism

Shape
String : Color
Get_area ( )

Method overloading Method Overriding


Box
int : SideLength
int Add(int x , int y); Get_area ( )
double Add (double x, double y); Box b;
b.Get_area ( );
Functions Overriding using Virtual Functions
• A virtual function a member function which is declared within a base class
and is re-defined(Overriden) by a derived class. When you refer to a derived
class object using a pointer to the base class, you can call a virtual function for
that object and execute the derived class’s version of the function.

• Virtual functions ensure that the correct function is called for an object,
regardless of the type of reference (or pointer) used for function call.
Shape Shape* shap_ptr ;
String : Color
Draw ( )
Erase ( )
Get_area ( )
shap_ptr

Rectangle R;
Box B ; Circle C ;

Rectangle Box Circle


int : Length int : SideLength int : radius
int : width Draw ( ) Draw ( )
Draw ( ) Erase ( ) Erase ( )
Erase ( ) Get_area ( ) Get_area ( )
Get_area ( ) Get_circumference ( )
Pure Virtual Functions
Abstract Class – Final Classifier
Abstract Classes - Interfaces
• An interface (Abstract Class) describes the behavior or capabilities of a C++
class without committing to a particular implementation of that class.
• The purpose of an abstract class is to provide the Desired base class Form
which will be inherited by other classes in the class hierarchy.
• Abstract classes cannot be used to instantiate objects and serves only as
an interface.
• A class is made abstract by declaring at least one of its functions as pure
virtual function.
Shape
String : Color
Draw ( )
Erase ( )
Get_area ( )

Rectangle Box Circle


int : Length int : SideLength int : radius
int : width Draw ( ) Draw ( )
Draw ( ) Erase ( ) Erase ( )
Erase ( ) Get_area ( ) Get_area ( )
Get_area ( ) Get_circumference ( )
• A class is made abstract by declaring at least one of its functions
as pure virtual function.
Friend Function & Friend Class
Friend Function
• A friend function of a class is defined outside that class' scope but
it has the right to access all private and protected members of the
class.
• The prototypes for friend functions appear in the class definition.
• friends are not member functions.
Friend Class
• Just like friend functions, we can also have a friend class.
• Friend class can access private and protected members of the class to which it
is a friend.
• Note that the friendship is not mutual unless we make it so.
• The friendship of the class is not inherited. This means that as class B is a
friend of class A, it will not be a friend of the subclasses of class A.
Employee
String : Name
String : SSN
Double : Salary
Get_TotalSalary();
Print ( );

Sales Engineer
Float : Goss_Sales String : Speciality
Float : Commission_Rate Int : Experience
Set_Gross_Sales( ) int: overtime_hours
Set_commission_Rate ( ) Float:overtime_hour_rate
Set_OverTime_Hours( )
Set_OverTime_hour_rate ( )
Exception Handling
Introduction
• Exceptions
– Indicate problems that occur during a program’s execution
– A C++ exception is a response to an exceptional circumstance that arises
while a program is running, such as an attempt to divide by zero.
• Exception handling
– Can resolve exceptions
• Allow a program to continue executing or
• Notify the user of the problem and
• Terminate the program in a controlled manner
– Makes programs robust and fault-tolerant
Exception Handling
• An exception is a class
• Usually derived from one of the system’s exception base classes
• Exception Class is the standard C++ base class for all exceptions
• Provides derived classes with virtual function what()
– Returns the exception’s stored error message

• If an exceptional or error situation occurs, program throws an


object of that class.
• Exceptions provide a way to transfer control from one part of a program to
another. three keywords: try, catch , throw are used
• try − A try block identifies a block of code for which particular exceptions
will be activated. It's followed by one or more catch blocks.
• throw − A program throws an exception when a problem shows up. This is
done using a throw keyword.
• catch − A program catches an exception with an exception handler at the place
in a program where you want to handle the problem. The catch keyword
indicates the catching of an exception.
int x = 10, y = 2;
try
{
if (y == 0)
throw exception ( )";
else
cout << x / y << endl;
}
catch (exception e)
{
cout << e.what ( ) <<endl;
}
cout << "The Program Continued" << endl;
int x = 10, y = 2;
try
{
if (y == 0)
throw "division by zero Exception";
else
cout << x / y << endl;
}
catch (const char* msg)
{
cout << msg <<endl;
cout << "Y must be greater than 0" << endl;
}
cout << "The Program Continued" << endl;
try {
int age = 15;
if (age > 18) {
cout << "Access granted - you are old enough.";
} else {
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Age is: " << myNum;
}
Exception Handling – General Syntax

• try {
// Block of code to try
throw exception; // Throw an exception when a problem arise
}
catch ( ) {
// Block of code to handle errors
}
Exception Handling
try {
// code to try
}
catch (exceptionClass1 &name1) {
// handle exceptions of exceptionClass1
} catch clauses attempted
in order; first match wins!
catch (exceptionClass2 &name2) {
// handle exceptions of exceptionClass2
}

catch (exceptionClass3 &name3) {


// handle exceptions of exceptionClass3
}
...
Handle Any Type of Exceptions (...)
int x = 10, y = 2;
try
{
if (y == 0)
throw "Integer division by zero";
else
cout << x / y << endl;
}
catch (…)
{ cout << “An exception Caught"<<endl;
}
cout << "The Program Continued" << endl;
Exception Specifications
• Also called throw lists
• Keyword throw
– Comma-separated list of exception classes in parentheses
• Example
– int someFunction( double value )
throw ( ExceptionA, ExceptionB, Optional!
ExceptionC )
{
...
}
– Indicates someFunction can throw types ExceptionA, ExceptionB and
ExceptionC
Exception Specifications (continued)
• A function can throw only exceptions of types in its specification (or
derived types)
– If a function throws a non-specification exception, function unexpected is called
• This normally terminates the program
• Absence of exception specification indicates that the function can throw
any exception
• An empty exception specification, throw(), indicates the function
cannot throw any exceptions

You might also like